Skip to content

Instantly share code, notes, and snippets.

Created November 20, 2015 04:27
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
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

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

Copy link

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

Copy link

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

Copy link

TimChey commented Sep 21, 2022

help me!! how to do in java . i have try many method , and can not get same result

aesEncrypt(data, key){
    data = new Buffer(data).toString('base64');
    let clearEncoding = 'utf8';
    let cipherEncoding = 'base64';
    let cipherChunks = [];
    let cipher = crypto.createCipheriv('aes-256-ecb', key, "");
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    return cipherChunks.join('');

aesDecrypt(data, key){
    if (!data) {
        return "";
    let clearEncoding = 'utf8';
    let cipherEncoding = 'base64';
    let cipherChunks = [];
    let decipher = crypto.createDecipheriv('aes-256-ecb', key, "");
    cipherChunks.push(decipher.update(data, cipherEncoding, clearEncoding));
    return cipherChunks.join('');

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