从TripleDES .Net到TripleDES(crypto-js)Javascript

时间:2019-05-08 04:53:08

标签: cryptojs tripledes

我花了一些时间查看所有解决方案,但似乎仍然存在问题。我在.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 ==

1 个答案:

答案 0 :(得分:0)

我已解决此问题。在Tripledes.js(CryptoJS软件包)中的控制台日志显示,在MD5 Hash之后,密钥中又丢失了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);   
 }