Search code examples
javascriptandroidkotlincryptojs

CryptoJS.AES.encrypt giving different result in android (kotlin)


Android client needs to use the same encryption which is used in our other Javascript application. i.e.

const key = CryptoJS.enc.Utf8.parse(getSecretKey()); 
const piv = new Date().toISOString().substring(0, 16);
const iv = CryptoJS.enc.Utf8.parse(piv);
const miv = piv + userCredentials;
const msg = CryptoJS.enc.Utf8.parse(miv);
   
val msg = "64 character long string"
val key = "32 character long string"
val iv = "32 character long string"
const encrypted = CryptoJS.AES.encrypt(msg, key, {
      keySize: 16,
      iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });

I tried using the following in Kotlin

val key = toHexString(getSecretKey())
val iv = toHexString(getCurrentUTCTime())
val msg = toHexString(getMessage())
 
//1. Create a cipher object
val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")

//2. Initialize cipher
val keySpec = SecretKeySpec(key.toByteArray(),0,16,"AES")
val ivParameterSpec = IvParameterSpec(iv.toByteArray(),0,16)
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec)

//3. Encryption and decryption
val encrypt = cipher.doFinal(msg.toByteArray())
return Base64.getEncoder().encodeToString(encrypt)

private fun toHexString(bytes: ByteArray): String {
        val formatter = Formatter()
        for (b in bytes) {
            formatter.format("%02x", b)
        }
        return formatter.toString()
    }

Both are returning a different value. Can someone please tell that if both algorithms which are same, their configs are same, their keys are same why are they returning a different value?


Solution

  • Instead of doing this

    val key = toHexString(getSecretKey())
    val iv = toHexString(getCurrentUTCTime())
    val msg = toHexString(getMessage())
     
    

    I had to remove the function calling.

    val key = getSecretKey()
    val iv = getCurrentUTCTime()
    val msg = getMessage()
     
    

    then both results were same on javascript app and on android client.