I'm trying to find the similar java code for the below Node JS code,
Node JS Code:
var crypto = require('crypto');
var mykey = crypto.createCipher('aes-128-ecb', 'XXXXXXXX00000000');
var mystr = mykey.update('HelloWorld', 'utf8', 'hex')
mystr += mykey.final('hex');
console.log(mystr);
Encryption Result: ce25d577457cf8113fa4d9eb16379529
Java Code:
public static String toHex(String arg) throws UnsupportedEncodingException {
return String.format("%x", new BigInteger(1, arg.getBytes("UTF-8")));
}
public static void main(String args[]) throws Exception{
byte[] key = "XXXXXXXX".getBytes();
String message = "HelloWorld";
try {
key = Arrays.copyOf(key, 16);
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte encstr[] = cipher.update(message.getBytes());
String encData = new String(encstr, "UTF-8");
encData = toHex(encData);
byte encstr2[] = cipher.doFinal();
String encData2 = new String(encstr2);
encData = encData + toHex(encData2);
System.out.println(encData);
} catch (NoSuchAlgorithmException nsae) {
throw new Exception("Invalid Java Version");
} catch (NoSuchPaddingException nse) {
throw new Exception("Invalid Key");
}
}
Encryption Result: 056efbfbdefbfbd7c7760efbfbdefbfbdefbfbd39262cefbfbdefbfbd5166
crypto.createCipher(algorithm, password[, options])version, hence the key you specify is handled as password and the actual key should be MD5(password) according to the node.js crypt documentation. On Java side you just use the string bytes as key without MD5 (which is insecure as well as using ECB mode).toHeximplementation that directly expects abyte[]would be more useful (by the way, the currenttoHexomits leading 0-values). Also, theupdatecall isn't necessary, the plaintext can be passed directly todoFinal. The encoding of the plaintext should be specified explicitly.createCipher, you need a Java implementation of the (relatively insecure) key derivation functionEVP_BytesToKey. An alternative iscreateCipheriv, see the NodeJS documentation.openssl encalso stackoverflow.com/questions/8357941 stackoverflow.com/questions/31947256