Csharp TripleDes解密代码转换为Nodejs代码-已解决

时间:2019-02-09 12:54:48

标签: 3des tripledes

我有一个用Csharp编写的TripleDes解密代码。我需要将此代码转换为Nodejs代码。我要转换的文件格式为二进制,因此不确定是否需要执行其他操作。我对应该如何做感到很困惑。

byte[] content = Convert.FromBase64String(UTF8Encoding.UTF8.GetString(TripleDESCDecryptoText (attachSection1, attachDecryptionKey)));

public byte[] TripleDESCDecryptoText(byte[] toEncryptArray, string key)
{
    int ivLen = 8;

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

    tdes.Key = System.Convert.FromBase64String(key); // keyArray;        
    tdes.Mode = CipherMode.CBC; //CipherMode.ECB;         
    tdes.Padding = PaddingMode.None; // PaddingMode.PKCS7;


    if (toEncryptArray.Length < ivLen)
        return null;

    byte[] buffer = new byte[ivLen];

    for (int n = 0; n < ivLen; n++)
        buffer[n] = toEncryptArray[n];

    tdes.IV = buffer;

    ICryptoTransform cTransform = tdes.CreateDecryptor();

    byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0 + ivLen, toEncryptArray.Length - ivLen);

    tdes.Clear();
    int nn2 = resultArray.Length;
    int nn2a = 0;
    while ((resultArray[nn2 - 1] == '\b' || resultArray[nn2 - 1] ==Convert.ToChar(4)) && nn2a < 15)
    {
        nn2--;
        nn2a++;
    }
    byte[] resultArray2 = new byte[nn2];
    Array.Copy(resultArray, 0, resultArray2, 0, resultArray2.Length);
    return resultArray2;
}

您对如何转换有建议吗?如果您有任何想法,请提前谢谢。

问题已解决。解决方法如下。

Nodejs代码:

exports.FilesDecrypt = function (input, keyInfo, callback) {

var chunks = [];

var fileBuffer;

var fileStream = fs.createReadStream(input);


fileStream.once('error', function (err) {
    // Be sure to handle this properly!
    console.error(err);
});

fileStream.once('end', function () {

    fileBuffer = Buffer.concat(chunks);

    var key = new Buffer(keyInfo, 'base64');
    var alg = "des-ede3-cbc";
    var autoPad = false;

    var ivLen = 8;

    var keyiv = new Buffer(ivLen); //byte[] keyiv = new byte[ivLen];

    for (var i = 0; i < ivLen; i++) {
        keyiv[i] = fileBuffer[i];
    }

    var dataLen = fileBuffer.length - ivLen; //int dataLen = input.length-ivLen;
    var data = new Buffer(dataLen); //byte[] data = new byte[dataLen];

    for (var i = 0; i < dataLen; i++) {
        data[i] = fileBuffer[i + ivLen];
    }
    //decrypt
    var decipher = crypto.createDecipheriv(alg, key, keyiv);
    decipher.setAutoPadding(autoPad);
    var txt = decipher.update(data);
    txt += decipher.final('base64');

    var utf8encoded = (new Buffer(txt, 'base64')).toString('utf8');

    callback(null, utf8encoded);
});

fileStream.on('data', function (chunk) {
    chunks.push(chunk);
});

 };

最好的问候,

0 个答案:

没有答案