Search code examples
javanode.jsaescryptojsecb

How to convert Java AES ECB Encryption Code to Nodejs


I have code in java for encryption

public String encrypt() throws Exception {
    String data = "Hello World";
    String secretKey = "j3u8ue8xmrhsth59";
    byte[] keyValue = secretKey.getBytes();
    Key key = new SecretKeySpec(keyValue, "AES");
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.ENCRYPT_MODE, key);
    byte[] encVal = c.doFinal(StringUtils.getBytesUtf8(data));
    String encryptedValue = Base64.encodeBase64String(encVal);
    return encryptedValue;
}

It returns same value ( eg5pK6F867tyDhBdfRkJuA== ) as the tool here enter image description here

I converted the code to Nodejs (crypto)

var crypto = require('crypto')

encrypt(){
      var data = "Hello World"
      var cipher = crypto.createCipher('aes-128-ecb','j3u8ue8xmrhsth59')
      var crypted = cipher.update(data,'utf-8','base64')
      crypted += cipher.final('base64')
      return crypted;
}

But this is giving a different value ( POixVcNnBs3c8mwM0lcasQ== )

How to get same value from both? What am I missing?


Solution

  • Thanks to dave now I am getting same result both for Java and Nodejs/JavaScript

    var crypto = require('crypto')
    
    encrypt(){
          var data = "Hello World"
          var iv = new Buffer(0);
           const key = 'j3u8ue8xmrhsth59'
          var cipher = crypto.createCipheriv('aes-128-ecb',new Buffer(key),new Buffer(iv))
          var crypted = cipher.update(data,'utf-8','base64')
          crypted += cipher.final('base64')
          return crypted;
    }