Skip to content

Instantly share code, notes, and snippets.

@fratuz610
Created November 20, 2015 04:27
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save fratuz610/9f8c733dc1277ecee51f to your computer and use it in GitHub Desktop.
Save fratuz610/9f8c733dc1277ecee51f to your computer and use it in GitHub Desktop.
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 + aesDec.final();
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());
}
@TimChey
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, "");
    cipher.setAutoPadding(true);
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(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, "");
    decipher.setAutoPadding(true);
    cipherChunks.push(decipher.update(data, cipherEncoding, clearEncoding));
    cipherChunks.push(decipher.final(clearEncoding));
    return cipherChunks.join('');
}`

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