【不怕坑】之 Node.js加密 C#解密

本人也不太瞭解AES加密解密,爲了解決Node.js加密,可是沒法C#解密的問題,在網上搜了大量的相關文章。node

可是多數是Node.js vs Java 或 Java vs C#的雙向加密解密代碼,可是沒有Node.js vs C#。數組

而後經過反覆試驗,找到了解決辦法。ide

很少說了,上代碼,有坑不怕,隨我衝!ui

 

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#解密spa

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解密,待續~code

相關文章
相關標籤/搜索