Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Encrypt from Java and decrypt on Node.js - aes 256 ecb
// we determine the key buffer
var stringKey = "example";
var cipherText = ".........";
// we compute the sha256 of the key
var hash = crypto.createHash("sha256");
hash.update(stringKey, "utf8");
var sha256key = hash.digest();
var keyBuffer = new Buffer(sha256key);
var cipherBuffer = new Buffer(cipherText, 'hex');
var aesDec = crypto.createDecipheriv("aes-256-ecb", keyBuffer , ''); // always use createDecipheriv when the key is passed as raw bytes
var output = aesDec.update(cipherBuffer);
return output +;
try {
String stringKey = "example";
byte[] key = HashUtils.SHA256(stringKey);
byte[] input = "this is a test".getBytes();
byte[] output = null;
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // this is actually aes 256 ecb and NOT aes-128 as we passed a 32bytes key
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
output = cipher.doFinal(input);
return output;
} catch (Exception ex) {
throw new RuntimeException("Unable to AES-Encrypt: " + ex.getMessage());
Copy link

alikashmar commented Jul 12, 2017

That comment in the node section about using createDecipheriv fixed my problem. Thank you!

Copy link

ryeborja commented Jul 28, 2020

How to do it in reverse? Encrypt in NodeJS and decrypt in Java

Copy link

smit-code commented Oct 15, 2021

Data encryption in Android and decrypting in node.js how this is possible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment