TripleDES .Net 到 TripleDES (crypto-js) Javascript

TripleDES .Net to TripleDES (crypto-js) Javascript

我花了一些时间查看所有解决方案,但似乎仍然有些不对劲。我在 .Net 中看到的加密字符串与我在 Cryto-JS 中看到的输出不匹配。有什么问题吗?

    public static void Encrypt()
    {
        string toEncrypt = "123456";
        string key = "hello";

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        byte[] keyArray = hashmd5.ComputeHash(UnicodeEncoding.Unicode.GetBytes(key));
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;

        ICryptoTransform cTransform = tdes.CreateEncryptor();
        byte[] toEncryptArray = UnicodeEncoding.Unicode.GetBytes(toEncrypt);
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        string finalString = Convert.ToBase64String(resultArray);

        Console.WriteLine("Output encrypted .Net: " + finalString);
    }

使用 crypto-js 的等效 Javascript 是

    Encrypt = () => {
        var CryptoJS = require('crypto-js');
        var text = '123456'
        var key = "hello";

        key = CryptoJS.enc.Utf16LE.parse(key);
        key = CryptoJS.MD5(key)

        var options = {
           mode: CryptoJS.mode.ECB, 
        };

        var textWordArray = CryptoJS.enc.Utf16LE.parse(text); 
        var encrypted = CryptoJS.TripleDES.encrypt(textWordArray, key, options);   
        var base64String = encrypted.toString();    
        console.log('Output JS Encrypted: ' + base64String);   
     }  

我在 .Net 中得到 yGOnLhoVpIHQOCbAn51FTA==,在 crypto-js 中得到 d5Lg8k8cz68T6akDI0KQrA==

我已经解决了这个问题。 tripledes.js(CryptoJS 包)中的控制台日志显示我在 MD5 哈希后的密钥中丢失了 64 位。

this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));

key.words 长度是 4 而不是 6。因此,des3 有一个空的字数组。解决方案是将索引 0 和 1 的值推入关键字数组。现在长度为 6,des3 获得 des1 的值。即 keyWords.slice(0, 2) = keyWords.slice(4, 6)。

Encrypt = () => {
    var CryptoJS = require('crypto-js');
    var text = '123456'
    var key = "hello";

    key = CryptoJS.enc.Utf16LE.parse(key);
    key = CryptoJS.MD5(key)
    key.words.push(key.words[0], key.words[1]) // FIX FIX FIX

    var options = {
       mode: CryptoJS.mode.ECB, 
    };

    var textWordArray = CryptoJS.enc.Utf16LE.parse(text); 
    var encrypted = CryptoJS.TripleDES.encrypt(textWordArray, key, options);   
    var base64String = encrypted.toString();    
    console.log('Output JS Encrypted: ' + base64String);   
 }