本人也不太了解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解密,待續~