javascriptencryptionaescryptojskey-generator

Alternate Code in JavaScript for javax.crypto


I want to implement below code in JavaScript instead of using javax.crypto packages.

Below code will generate key using AES.

    KeyGenerator kgen;
    String key;
    try {
        kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        SecretKey secretkey = kgen.generateKey();
        BASE64Encoder encode = new BASE64Encoder();
        key = encode.encode(secretkey.getEncoded());
    } catch (NoSuchAlgorithmException e) {
       // exceptionLogFile(e, null);
        e.printStackTrace();
        key = "Error@SecretKeyGeneration: No Such Algorith Exception. " + e.getMessage();
    } catch (Exception e) {
       // exceptionLogFile(e, null);
        e.printStackTrace();
        key = "Error@SecretKeyGeneration: " + e.getMessage();
    }
    return key;

This is perfectly working in Java, Now can anyone suggest me alternative in JavaScript.

I got to know about Crypto.js but how i can use here, not understanding.

For Encrypt and Decrypt, I am using "AES/ECB/PKCS5Padding" so is it compatible with the javascript code ?

Please help.

Thanks in advance.


Solution

  • An AES key consists simply of random bytes. So for a 128 byte key you can just do:

    var key = CryptoJS.lib.WordArray.random(128/8);
    

    and to encode it:

    var keyBase64 = CryptoJS.enc.Base64.stringify(key);
    

    Of course the key won't be identical to the one you generated before, you need to decode the previously generated base 64 encoded key to do that.


    To use the key, use the explicit key parameters:

    var encrypted = CryptoJS.AES.encrypt("Message", key, { mode: CryptoJS.mode.ECB});
    

    PKCS#7 padding - which is identical to PKCS#5 padding - is already the default and ECB doesn't use an IV.