Skip to content

Instantly share code, notes, and snippets.

@yingca1
Created November 1, 2017 02:51
Show Gist options
  • Save yingca1/7266e35328839106132c929624adb264 to your computer and use it in GitHub Desktop.
Save yingca1/7266e35328839106132c929624adb264 to your computer and use it in GitHub Desktop.
AES encrypt & decrypt in java and nodejs
private static byte[] iv = "0000000000000000".getBytes();
private static String decrypt(String encrypted, String seed)
throws Exception {
byte[] keyb = seed.getBytes("utf-8");
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] thedigest = md.digest(keyb);
SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
Cipher dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
dcipher.init(Cipher.DECRYPT_MODE, skey, new IvParameterSpec(iv));
byte[] clearbyte = dcipher.doFinal(Base64.decode(encrypted, Base64.DEFAULT));
return new String(clearbyte);
}
public static String encrypt(String content, String key) throws Exception {
byte[] input = content.getBytes("utf-8");
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] thedigest = md.digest(key.getBytes("utf-8"));
SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skc, new IvParameterSpec(iv));
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
return Base64.encodeToString(cipherText, Base64.DEFAULT);
}
var crypto = require('crypto');
var iv = new Buffer('0000000000000000');
// reference to converting between buffers http://nodejs.org/api/buffer.html#buffer_new_buffer_str_encoding
// reference node crypto api http://nodejs.org/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv
// reference to ECB vs CBC cipher methods http://crypto.stackexchange.com/questions/225/should-i-use-ecb-or-cbc-encryption-mode-for-my-block-cipher
var encrypt = function(data, key) {
var decodeKey = crypto.createHash('sha256').update(key, 'utf-8').digest();
var cipher = crypto.createCipheriv('aes-256-cbc', decodeKey, iv);
return cipher.update(data, 'utf8', 'base64') + cipher.final('base64');
};
var decrypt = function(data, key) {
var encodeKey = crypto.createHash('sha256').update(key, 'utf-8').digest();
var cipher = crypto.createDecipheriv('aes-256-cbc', encodeKey, iv);
return cipher.update(data, 'base64', 'utf8') + cipher.final('utf8');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment