Anbazhagan p
Anbazhagan p

Reputation: 943

Encrypt a string using Triple Data encryption standard(3DES) with PKCS7 padding

Requirement:

I have a Ruby on rails application and i need to do the following.

The following string should be encrypted using 3DES algorithm and work key. Encrypted value for ABJGTU9 will be vV51P0OGXt0=

work key is A5157A0D77B24AEA868AD73288366826

The 3DES algorithm mentioned in following document uses below steps for data encryption : i. Encrypt data using left part of key with CBC cipher mode and PKCS7 padding. ii. Decrypt data using right part of key with CBC cipher mode and no padding. iii. Encrypt data using left part of key with CBC cipher mode and without padding.

I tried the following article This is what i did and my output is "hsYUuA/Mo6A=\n" Expected is vV51P0OGXt0=

  cipher = OpenSSL::Cipher::Cipher.new('DES-EDE3-CBC')
  cipher.encrypt # Must be called before anything else

  # Generate the key and initialization vector for the algorithm.
  # Alternatively, you can specify the initialization vector and cipher key
  # specifically using `cipher.iv = 'some iv'` and `cipher.key = 'some key'`
  # cipher.pkcs5_keyivgen('SOME_PASS_PHRASE_GOES_HERE')

  key = Digest::MD5.base64digest('A5157A0D77B24AEA')
  cipher.key = key
  data = "ABJGTU9"
  output = cipher.update(data)
  output << cipher.final
  output
end

I am not sure if i am going the right way.

Upvotes: 1

Views: 1017

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 93948

There are many things wrong in the scheme mentioned in the question:

  1. the key is a two-key triple DES key, you need to hex decode it, not perform MD5 on it;
  2. if your code doesn't work with a 128 bit DES key as shown, you should copy the first 8 bytes and append them to the end of the key (so DES key 1 and DES key 3 are identical) - OpenSSL should however work fine with keys of 16 bytes;
  3. the method of encryption described in steps i, ii and iii only works for for each separate block that needs to be encrypted - you don't need it if you already use cipher 'DES-EDE3-CBC'.

OpenSSL already pads using PKCS#7 padding by default, so there is no reason to do anything special for that.

CBC requires a unique, unpredictable IV for each encryption operation with the same key, which seems to be missing from the scheme described.

Upvotes: 0

Related Questions