How to convert Java AES ECB Encryption Code to Nodejs

天涯浪子 提交于 2021-02-08 10:24:43

问题


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

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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/57447707/how-to-convert-java-aes-ecb-encryption-code-to-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!