本人也不太了解AES加密解密,为了解决Node.js加密,但是无法C#解密的问题,在网上搜了大量的相关文章。
但是多数是Node.js vs Java 或 Java vs C#的双向加密解密代码,但是没有Node.js vs C#。
然后通过反复试验,找到了解决办法。
不多说了,上代码,有坑不怕,随我冲!
Node.js加密
var crypto = require('crypto'); var secretKey = 'password'; var aesEncrypt = function(data) { var cipher = crypto.createCipher('aes-128-ecb',secretKey); return cipher.update(data,'utf8','hex') + cipher.final('hex'); } console.log(aesEncrypt('hello world!')); //输出 c552d8545e864fd8f8b73e442cca9276 ,注意这里是16位形式的字符串
C#解密
static void Main(string[] args) { Console.WriteLine(Decrypt("c552d8545e864fd8f8b73e442cca9276")); //输出 hello world! } private static string Decrypt(string toDecrypt) { byte[] keyArray = get_key(); //坑1:需要MD5转换 byte[] toEncryptArray = HexToByte(toDecrypt); //坑2:需要将16位形式的字符串转成字节数组 RijndaelManaged rDel = new RijndaelManaged(); rDel.Key = keyArray; //rDel.KeySize = 128; //坑3:rDel.KeySize已经是128,但是加上这句话后,就不会正确解密 //rDel.BlockSize = 128;//坑3:rDel.BlockSize已经是128,但是加上这句话后,就不会正确解密 rDel.Mode = CipherMode.ECB; rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return UTF8Encoding.UTF8.GetString(resultArray); } private static byte[] get_key() { string key = "password"; byte[] result = Encoding.UTF8.GetBytes(key); MD5 md5 = new MD5CryptoServiceProvider(); return md5.ComputeHash(result); } private static byte[] HexToByte(string msg) { //msg = msg.Replace(" ", "");//移除空格 byte[] comBuffer = new byte[msg.Length / 2]; for (int i = 0; i < msg.Length; i += 2) { comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16); } return comBuffer; }
C#加密,node.js解密,待续~