I generate 128bit AES/CBC/PKCS5Padding
key using Java javax.crypto
API. Here is the algorithm that I use:
public static String encryptAES(String data, String secretKey) {
try {
byte[] secretKeys = Hashing.sha1().hashString(secretKey, Charsets.UTF_8)
.toString().substring(0, 16)
.getBytes(Charsets.UTF_8);
final SecretKey secret = new SecretKeySpec(secretKeys, "AES");
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
final AlgorithmParameters params = cipher.getParameters();
final byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
final byte[] cipherText = cipher.doFinal(data.getBytes(Charsets.UTF_8));
return DatatypeConverter.printHexBinary(iv) + DatatypeConverter.printHexBinary(cipherText);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public static String decryptAES(String data, String secretKey) {
try {
byte[] secretKeys = Hashing.sha1().hashString(secretKey, Charsets.UTF_8)
.toString().substring(0, 16)
.getBytes(Charsets.UTF_8);
// grab first 16 bytes - that's the IV
String hexedIv = data.substring(0, 32);
// grab everything else - that's the cipher-text (encrypted message)
String hexedCipherText = data.substring(32);
byte[] iv = DatatypeConverter.parseHexBinary(hexedIv);
byte[] cipherText = DatatypeConverter.parseHexBinary(hexedCipherText);
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretKeys, "AES"), new IvParameterSpec(iv));
return new String(cipher.doFinal(cipherText), Charsets.UTF_8);
} catch (BadPaddingException e) {
throw new IllegalArgumentException("Secret key is invalid");
}catch (Exception e) {
throw Throwables.propagate(e);
}
}
I can easily encrypt and decrypt messages using secretKey with these methods. Since Java has 128bit AES encryption by default, it generates a hash of the original secret key with SHA1 and takes the first 16-bytes of the hash to use it as secret key in AES. Then it dumps the IV and cipherText in HEX format.
For example encryptAES("test", "test")
generates CB5E759CE5FEAFEFCC9BABBFD84DC80C0291ED4917CF1402FF03B8E12716E44C
and I want to decrypt this key with CryptoJS.
Here is my attempt:
var str = 'CB5E759CE5FEAFEFCC9BABBFD84DC80C0291ED4917CF1402FF03B8E12716E44C';
CryptJS.AES.decrypt(
CryptJS.enc.Hex.parse(str.substring(32)),
CryptJS.SHA1("test").toString().substring(0,16),
{
iv: CryptJS.enc.Hex.parse(str.substring(0,32)),
mode: CryptJS.mode.CBC,
formatter: CryptJS.enc.Hex,
blockSize: 16,
padding: CryptJS.pad.Pkcs7
}).toString()
However it returns an empty string.
PKCS5Padding
, but JS code ispad.Pkcs7
. 5 and 7 are not the same. – PaperbackRSA/ECB/PKCS1Padding
also doesn't make sense, because ECB is not applicable to RSA. – Tuberculate