Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.security.MessageDigest;
- import javax.crypto.Cipher;
- import javax.crypto.spec.SecretKeySpec;
- import javax.xml.bind.DatatypeConverter;
- public class AES {
- 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(DatatypeConverter
- .parseHexBinary(encrypted));
- 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 DatatypeConverter.printHexBinary(cipherText);
- }
- public static void main(String[] args) throws Exception {
- String data = "hello";
- String key = "hi";
- String cipher = AES.encrypt(data, key);
- String decipher = AES.decrypt(cipher, key);
- System.out.println(cipher);
- System.out.println(decipher);
- }
- }
- $ javac AES.java
- $ java AES
- DD0D07B77C1606C97A1B10AC8D9AC180
- hello
- var crypto = require('crypto');
- var iv = new Buffer('0000000000000000');
- 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', 'hex') + cipher.final('hex');
- };
- 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, 'hex', 'utf8') + cipher.final('utf8');
- };
- var data = 'hello'
- var key = 'hi';
- var cipher = encrypt(data, key);
- var decipher = decrypt(cipher, key);
- console.log(cipher);
- console.log(decipher);
- node aes.js
- dd0d07b77c1606c97a1b10ac8d9ac180
- hello
Add Comment
Please, Sign In to add comment