Skip to content

Instantly share code, notes, and snippets.

@sobiodarlington
Forked from fratuz610/decrypt.js
Created March 27, 2020 19:07
Show Gist options
  • Save sobiodarlington/7819d65073fd5befeaf6366aa1cc58e7 to your computer and use it in GitHub Desktop.
Save sobiodarlington/7819d65073fd5befeaf6366aa1cc58e7 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());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment