0

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?

Abhishek Kumar
  • 2,136
  • 3
  • 24
  • 36
  • [See the param name and paras 4 to 6 of the documentation](https://nodejs.org/api/crypto.html#crypto_crypto_createcipher_algorithm_password_options). Use createCipheriv, even though the IV for ECB is empty (`new Buffer(0)`). Also, using a small set of printable characters for the key is weak, and using ECB is usually insecure, but those are topics for a different Stack. – dave_thompson_085 Aug 11 '19 at 07:52

1 Answers1

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;
}
Abhishek Kumar
  • 2,136
  • 3
  • 24
  • 36