1 package com.LOLnet;
2 import java.security.MessageDigest;
3
4 import javax.crypto.Cipher;
5 import javax.crypto.spec.SecretKeySpec;
6
7 public class AESForNodejs {
8 public static final String DEFAULT_CODING = "utf-8";
9
10 //解密
11 public static String decrypt(String encrypted, String seed) throws Exception {
12 byte[] keyb = seed.getBytes(DEFAULT_CODING);
13 MessageDigest md = MessageDigest.getInstance("MD5");
14 byte[] thedigest = md.digest(keyb);
15 SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
16 Cipher dcipher = Cipher.getInstance("AES");
17 dcipher.init(Cipher.DECRYPT_MODE, skey);
18
19 byte[] clearbyte = dcipher.doFinal(toByte(encrypted));
20 return new String(clearbyte);
21 }
22
23 //加密
24 public static String encrypt(String content, String key) throws Exception {
25 byte[] input = content.getBytes(DEFAULT_CODING);
26
27 MessageDigest md = MessageDigest.getInstance("MD5");
28 byte[] thedigest = md.digest(key.getBytes(DEFAULT_CODING));
29 SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
30 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
31 cipher.init(Cipher.ENCRYPT_MODE, skc);
32
33 byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
34 int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
35 ctLength += cipher.doFinal(cipherText, ctLength);
36
37 return parseByte2HexStr(cipherText);
38 }
39
40 //字符串转字节
41 private static byte[] toByte(String hexString) {
42 int len = hexString.length() / 2;
43 byte[] result = new byte[len];
44 for (int i = 0; i < len; i++) {
45 result = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
46 }
47 return result;
48 }
49
50
51 //字节转16进制数组
52 private static String parseByte2HexStr(byte buf[]) {
53 StringBuffer sb = new StringBuffer();
54 for (int i = 0; i < buf.length; i++) {
55 String hex = Integer.toHexString(buf & 0xFF);
56 if (hex.length() == 1) {
57 hex = '0' + hex;
58 }
59 sb.append(hex);
60 }
61 return sb.toString();
62 }
63 }
/**
* Created with JetBrains WebStorm.
* User: rube
* Date: 4/7/14
* Time: 4:33 PM
* To change this template use File | Settings | File Templates.
*/
var crypto = require('crypto');
/**
* aes128加密
* @param data 明文
* @param secretKey 密钥
* @returns {*}
*/
exports.encrypt = function (data, secretKey) {
var cipher = crypto.createCipher('aes-128-ecb',secretKey);
return cipher.update(data,'utf8','hex') + cipher.final('hex');
};
/**
* aes128解密
* @param data 密文
* @param secretKey 密钥
* @returns {*}
*/
exports.decrypt = function(data, secretKey) {
var cipher = crypto.createDecipher('aes-128-ecb',secretKey);
return cipher.update(data,'hex','utf8') + cipher.final('utf8');
}