Usman Afzal

Usman Afzal

  • NA
  • 4
  • 942

First 16 Characters of decrypted string are garbage

Apr 28 2021 1:04 AM
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:
  1. decrypt(source: string, iv: string): string {  
  2. var key = environment.config.KEY_PAYMENT.substring(0, 32);  
  3. const keyValue = CryptoJS.enc.Utf8.parse(key);  
  4. const ivValue = CryptoJS.enc.Utf8.parse(iv);  
  5. const plainText = CryptoJS.AES.decrypt(source, keyValue,  
  6. {  
  7. keySize: 16, iv: ivValue, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });  
  8. return CryptoJS.enc.Latin1.stringify(plainText);  
  9. }
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:
  1. fun decrypt( source: ByteArray, key: String, iv: ByteArray ): ByteArray  
  2. {  
  3. val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")  
  4. cipher.init(Cipher.DECRYPT_MODE, makeKey(key), makeIv(iv)) return cipher.doFinal(source)  
  5. }  
  6. private fun makeIv(iv: ByteArray): AlgorithmParameterSpec  
  7. {  
  8. return IvParameterSpec(iv)  
  9. }  
  10. private fun makeKey(baseKey: String): Key? {  
  11. return try  
  12. {  
  13. val key = baseKey.substring(0, 32) .toByteArray(charset("UTF-8")) SecretKeySpec(key, "AES")  
  14. }  
  15. catch (e: UnsupportedEncodingException) { null }  
  16. }  
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.