· 8 years ago · Jan 01, 2018, 04:36 AM
1var crypto = require('crypto');
2
3var encKey = "FOO"; // Not the real key. Assume it works though.
4
5var encrypt = function(str) {
6 var cipher = crypto.createCipher('aes-256-cbc', encKey);
7 var crypted = cipher.update(str, 'utf-8', 'hex');
8 crypted += cipher.final('hex');
9 return crypted;
10};
11
12var crypto = require('crypto');
13
14var encKey = "FOO"; // Not the real key. Assume it works though.
15
16var decrypt = function(str) {
17 var decipher = crypto.createDecipher('aes-256-cbc', encKey);
18 var decrypted = decipher.update(str, 'hex', 'utf-8');
19 decrypted += decipher.final('utf-8');
20 return decrypted;
21};
22
23import javax.crypto.Cipher;
24import javax.crypto.spec.SecretKeySpec;
25
26import java.security.MessageDigest;
27import java.util.Arrays;
28
29private static final String encKey = "FOO";
30private static SecretKeySpec secretKey;
31private static byte[] key;
32
33public static String decrypt(String str) throws Exception {
34 String hexDecodedStr = new String(Hex.decodeHex(str.toCharArray()));
35 setKey(encKey);
36 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
37 cipher.init(Cipher.DECRYPT_MODE, secretKey);
38 return new String(cipher.doFinal(hexDecodedStr.getBytes()));
39}
40
41private static void setKey(String myKey) throws Exception {
42 MessageDigest sha = null;
43 try {
44 key = myKey.getBytes("UTF-8");
45 sha = MessageDigest.getInstance("SHA-1");
46 key = sha.digest(key);
47 key = Arrays.copyOf(key, 16);
48 secretKey = new SecretKeySpec(key, "AES");
49 }
50 catch (Exception e) {
51 throw e;
52 }
53}