I want to encrypt a frame using DES using a given key.
The padding style I am using is PKCS5Padding. This pads the string with 02 02 if 2 bytes are to be added and with 03 03 03 if 3 bytes are to be added to make multiple of 8. But my requirement is to pad a string with my particular bytes. e.g if 2 bytes are to be added then 30 30 and 3 bytes are to be added then 30 30 30 (in hex 0's value is 30). Also, I must know how many padded bytes have been added. Which padding technique should I follow and how can I use it?
Below is my code for encryption:
byte[] keyValue = new byte[]{(byte) 0x30, (byte) 0x30, (byte) 0x30, (byte) 0x30, (byte) 0x30, (byte) 0x16,(byte) 0x05, (byte) 0x12};
myKeySpec = new DESKeySpec(keyValue);
mySecretKeyFactory = SecretKeyFactory.getInstance("DES");
key = mySecretKeyFactory.generateSecret(myKeySpec);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
IvParameterSpec iv2 = new IvParameterSpec(new byte[8]);
cipher.init(Cipher.ENCRYPT_MODE, key, iv2);
byte[] plainText = function.HexStringToByteArray(payloadRecv);
byte[] encryptedText = cipher.doFinal(plainText);
Do not select PKCS5Padding
in the cipher specification. Select NoPadding
. You'll have to add the padding onto the data yourself prior to encrypting it. After decrypting it (also using no padding), you'll have to inspect the last byte to know how many bytes of padding to remove and remove it yourself.
Basically, just code exactly what you described.
来源:https://stackoverflow.com/questions/10634065/encryption-using-provided-key-using-des-with-padding