最近在做android游戲,客戶端與Nodejs服務端數據的交互用AES進行加密,發現Nodejs與java的加密形式不一樣。查詢N久資料發現java端需要對密鑰再MD5加密一遍(我了個大擦),本來對加密一類就陌生,這。。。
下面把nodejs 和 JAVA的代碼貼這了
JAVA:
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[i] = 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[i] & 0xFF); 56 if (hex.length() == 1) { 57 hex = '0' + hex; 58 } 59 sb.append(hex); 60 } 61 return sb.toString(); 62 } 63 }
Node:
/** * 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'); }
google了一天頭好疼啊~