Reputation: 476
I have a scenario where data is encrypted from the API and then decrypted in typescript. I have used cryptoJS for decryption in typescript. Following is my decryption code:
decrypt(source: string, iv: string): string {
var key = environment.config.KEY_PAYMENT.substring(0, 32);
const keyValue = CryptoJS.enc.Utf8.parse(key);
const ivValue = CryptoJS.enc.Utf8.parse(iv);
const plainText = CryptoJS.AES.decrypt(source, keyValue, {
keySize: 16,
iv: ivValue,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return CryptoJS.enc.Latin1.stringify(plainText);
} The IV and key value are provided. I have a Java Sample Code that is being used for decryption for mobile application which is working as expected. Code sample is here:
fun decrypt(
source: ByteArray,
key: String,
iv: ByteArray
): ByteArray {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, makeKey(key), makeIv(iv))
return cipher.doFinal(source)
}
private fun makeIv(iv: ByteArray): AlgorithmParameterSpec {
return IvParameterSpec(iv)
}
private fun makeKey(baseKey: String): Key? {
return try {
val key = baseKey.substring(0, 32)
.toByteArray(charset("UTF-8"))
SecretKeySpec(key, "AES")
} catch (e: UnsupportedEncodingException) {
null
}
}
Sample Output:
ªîto7“ßH«3©@V¨sr","paymentType":"credit_card",...
The first 16 characters are garbage and rest of the string is decrypted successfully. I am stuck here.
Upvotes: 0
Views: 815
Reputation: 476
This worked from me:
decrypt(source: string, iv: string) {
debugger;
var key = environment.config.KEY_PAYMENT.substring(0, 32);
const keyValue = CryptoJS.enc.Utf8.parse(key);
const ivVal = CryptoJS.enc.Base64.parse(iv);//This Line
const plainText = CryptoJS.AES.decrypt(source, keyValue, { iv: ivVal });
return CryptoJS.enc.Latin1.stringify(plainText);
}
The crypto JS has it's own base64 encoding function that returned the correct result.
Upvotes: 1
Reputation: 206
"First 16 characters wrong; everything else looks good" typically means you got the IV wrong.
Everything in the code you provided looks legit; I suspect that the caller to decrypt is not passing the correct IV value.
Upvotes: 2