Manual implementation of 3DES (academic)

For the course that I am taking, we manually implement the 3DES scheme, which is pretty straightforward on paper (two keys, with EDE encryption). I chose Java as the implementation language, but ran into a problem of how it handles encryption / decryption using different keys. I keep getting the javax.crypto.BadPaddingException error when trying to apply the second round (i.e., "Decryption" with K2). By default, DES Cipher uses PKCS5Padding, and I assume this is a problem, but I'm not sure how to get around this. My code for encryption is lower (I hope this is not too straightforward, less I missed something simple). Thank you in advance.

Key definitions (quite simple, and I will try to improve it, since I saw several different approaches while watching)

KeyGenerator kgen = KeyGenerator.getInstance("DES"); SecretKey sk_1 = kgen.generateKey(); SecretKey sk_2 = kgen.generateKey(); byte[] raw_1 = sk_1.getEncoded(); byte[] raw_2 = sk_2.getEncoded(); spec_1 = new SecretKeySpec(raw_1, "DES"); //key 1 spec_2 = new SecretKeySpec(raw_2, "DES"); //key 2 cipher = Cipher.getInstance("DES"); //standard mode is ECB which is block-by-block w/PKCS5Padding cipher2 = Cipher.getInstance("DES"); protected byte[] get3DESEncryption(byte[] plaintext) throws Exception{ byte[] output = new byte[plaintext.length]; System.out.println("output len init: " + output.length); cipher.init(Cipher.ENCRYPT_MODE, spec_1); cipher2.init(Cipher.DECRYPT_MODE, spec_2); //first encryption round, key 1 used output = cipher.doFinal(plaintext); //second "encryption" round, key 2 used but decrypt run output = cipher2.doFinal(output); //third encryption round, key 1 used output = cipher.doFinal(output); //return ciphertext return output; } 
+4
source share
1 answer

The problem is that you should not use indentation in the second (decrypting) and third (encrypted) steps. When you actually use EDE , you should use only plain text.

The conversion has the form:

“algorithm / mode / padding” or “algorithm” (in the latter case, vendor-specific default values ​​for the padding mode and scheme used).

So, you must explicitly say that do not use padding on cipher2 and cipher3 (you have not created the latter yet).

Thus, you should have three encryption objects:

  • cipher1 DES / ECB / PKCS5Padding
  • cipher2 DES / ECB / NoPadding
  • cipher3 DES / ECB / NoPadding

[EXTRA HINT]

To decrypt, you must initialize the ciphers in different ways, and you must also change the encryption order.

+2
source

Source: https://habr.com/ru/post/1438544/


All Articles