0

I am trying to attempt the following:

Encrypt a string using the AES algorithm with a 128 bit secret key. The cipher mode I've been told to use is CBC with PKCS5 padding. The initialization vector is 16 bytes of 00.

Here are the instructions I was given:

  1. Using the secret key I need to generate a 128-bit secret key using the first 16 bytes.

  2. Read the bytes of the string to be encoded in "UTF-8".

  3. Encrypt the string using the AES algorithm and your 128 bit key. Be sure to use CBC mode and PKCS5 padding.

  4. Convert the encrypted bytes to hex string.

Here is what I have so far:

message = "string to be encoded"
secret = "mysecretkey".encode('UTF-8')
key = secret[0..15]
iv = "/0" * 16
cipher = OpenSSL::Cipher.new('aes-128-cbc')
cipher.encrypt
cipher.key = aes_key = key
cipher.iv = aes_iv = iv
encrypted = cipher.update(message)
encrypted << cipher.final()

My output is gibberish. I'm assuming it's because I'm not properly converting to hex? Also how do I set PKCS5 padding? And am I doing the iv correctly? Or am I completely off track on this altogether?

Any help would be greatly appreciated!

1 Answer 1

3
+50

My output is gibberish. I'm assuming it's because I'm not properly converting to hex?

That is correct.

Converting a binary String to hex is relatively straightforward (this is a standard "trick" in Ruby using String#unpack):

ciphertext_hex = encrypted.unpack('H*').first

Also how do I set PKCS5 padding?

Ruby/OpenSSL will use PKCS7, but that should be compatible with PKCS5 for your purpose (PKCS7 is an extension of PKCS5, but you should not see any of the extended behaviour in your chosen AES-128-CBC mode).

And am I doing the iv correctly?

No, you are using the wrong character to escape the character code 0, so your string is "/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0/0" which you could confirm by printing it. What you want is actually:

iv = "\0" * 16

Although normally you would set a random new iv for each message, as it reduces risk that messages with repeated content can be used to attack your encryption.

Or am I completely off track on this altogether?

Not too far away, just a couple of misses/gaps. I hope the above helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Phenomenal - thanks so much! Can't believe I had the escape character reversed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.