Reputation: 417
I am trying to dectypt data,
which was encrypted with mcrypt
DES, ECB mode
and then wrapped into Base64.
Here is my code:
static {
Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
}
// ...
// Crypted input data and the key
String criptedInput = "vsm1/sLWAUxW7JjKT/Amww==";
final String KEY = "jf7746yghndd";
// Decoding base64
byte[] bytesDecoded = Base64.decodeBase64(criptedInput.getBytes());
SecretKeySpec key = new SecretKeySpec(KEY.getBytes(), "DES");
Cipher cipher = null;
String result = null;
try {
cipher = Cipher.getInstance("DES/ECB/PKCS7Padding", "BC");
// Initialize the cipher for decryption
cipher.init(Cipher.DECRYPT_MODE, key);
// Decrypt the text
byte[] textDecrypted = cipher.doFinal(bytesDecoded);
result = new String(textDecrypted);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
Now I am catching java.security.invalidkeyexception: des key too long - should be 8 bytes..
What is wrong?
Upvotes: 0
Views: 1947
Reputation: 61892
DES supports only a key size of 56 bit (64 bit with parity). So you cannot use a larger key with it. Mcrypt knows this and silently only uses the first 8 bytes. Mcrypt also doesn't implement proper padding. Instead it pads with 0x00 bytes. You should be able to use a similar, but not same, padding in BouncyCastle:
Cipher.getInstance("DES/ECB/ZeroBytePadding", "BC");
Never use ECB mode. It's deterministic and therefore not semantically secure. You should at the very least use a randomized mode like CBC or CTR. It is better to authenticate your ciphertexts so that attacks like a padding oracle attack are not possible. This can be done with authenticated modes like GCM or EAX, or with an encrypt-then-MAC scheme.
Upvotes: 2