Search code examples
javascriptcryptojswebcrypto-api

Migrate from CryptoJS library to Web Crypto API


I need help migrating from CryptoJS to the WebCrypto API. Currently, i'm encrypting like this using CryptoJS:

let data = global.CryptoJS.AES.encrypt(
     "Data to encrypt", 
     global.CryptoJS.enc.Latin1.parse("encryption_key"), {
         iv : global.CryptoJS.enc.Latin1.parse("1234567891123456"),
         mode : global.CryptoJS.mode.CBC
     }
).toString();

But i didn't get it right trying to do this with WebCrypto API. I tried the following:

let key = await window.crypto.subtle.importKey(
     "raw",
     (new TextEncoder().encode("encryption_key")),
     "AES-CBC",
     true,
     ["encrypt", "decrypt"]
);

let data = await window.crypto.subtle.encrypt(
   {
     name: 'AES-CBC',
     iv: new TextEncoder().encode("1234567891123456")
   },
   key,
   new TextEncoder().encode("Data to encrypt")
);

All i'm trying to archive is a "simple" AES encryption which i can then decrypt backendside using PHP and openssl.


Solution

  • I figured it out. When you convert a CryptoJS encrypted Buffer .toString it makes a OpenSSL compatible Base64 string. So all what was missing from my example above was converting the data object (byteArray) to a Base64 String. I did this using the following Code snippet:

    byteArrayToBase64 = function byteArrayToBase64(array)
    {
        let u_binary = '';
        let u_bytes = new Uint8Array( array );
        let u_len = u_bytes.byteLength;
        for (let i = 0; i < u_len; i++) {
            u_binary += String.fromCharCode(u_bytes[i]);
        }
    
        return btoa(u_binary);
    },