NodeJS 3DES ECB加密不等于C#加密

时间:2017-02-23 04:18:31

标签: c# node.js encryption 3des ecb

我尝试将C#代码转换为使用3DES ECB加密文本 (您可以将其复制并粘贴到https://dotnetfiddle.net/上以运行它)

using System;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;

public class Program
{
    public static void Main()
    {
        string toEncrypt = "testtext";
        string key = "testkey";
        bool useHashing = true;
        byte[] keyArray;
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        System.Configuration.AppSettingsReader settingsReader =
                                                new AppSettingsReader();

        key = string.IsNullOrEmpty(key) ? (string)settingsReader.GetValue("SecurityKey", typeof(String)) : key;

        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));

            hashmd5.Clear();
        }
        else 
        {
            keyArray = UTF8Encoding.UTF8.GetBytes(key);
        }

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        key = Convert.ToBase64String(keyArray, 0, keyArray.Length);
        Console.WriteLine(key);
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateEncryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

        tdes.Clear();

        Console.Write(Convert.ToBase64String(resultArray, 0, resultArray.Length));
    }
}

输出:

Ihs2jX9fWXhn9SWXHyj/dQ== <- md5 secret key
wHL9J7vhm9LZI2W5DQJGKw== <- encrypt result

所以我在NodeJS中重写上面的代码以使用crypto

const crypto = require('crypto');
const md5 = text => {
  return crypto
    .createHash('md5')
    .update(text)
    .digest('base64');
}

const encrypt = (text, secretKey) => {
  secretKey = md5(secretKey);
  console.log(secretKey);

  const cipher = crypto.createCipher('des-ede3', secretKey);
  const encrypted = cipher.update(text, 'utf8', 'base64');

  return encrypted + cipher.final('base64');
};
const encrypted = encrypt('testtext', 'testkey');

console.log(encrypted);

输出:

Ihs2jX9fWXhn9SWXHyj/dQ== <- md5 secret key
VNa9fDYgPus5IMhUZRI+jQ== <- encrypt result

我认为问题在于使用3DES ECB的C#和NodeJS Crypto方法。知道如何在NodeJS中复制C#代码行为吗?

2 个答案:

答案 0 :(得分:2)

好的,只需使用https://www.npmjs.com/package/nod3des复制与C#相同的行为即可。如果你想知道它是如何工作的

https://github.com/4y0/nod3des/blob/master/index.js#L30

var CryptoJS = require('crypto-js');
var forge    = require('node-forge');
var utf8     = require('utf8');

...

_3DES.encrypt = function (key, text){

    key          = CryptoJS.MD5(utf8.encode(key)).toString(CryptoJS.enc.Latin1);
    key          = key + key.substring(0, 8); 
    var cipher   = forge.cipher.createCipher('3DES-ECB', forge.util.createBuffer(key));
    cipher.start({iv:''});
    cipher.update(forge.util.createBuffer(text, 'utf-8'));
    cipher.finish();
    var encrypted = cipher.output; 
    return ( forge.util.encode64(encrypted.getBytes()) );

}

答案 1 :(得分:0)

我有一个不同的要求(CBC),我想在这里添加它,以防它帮助任何寻求其他解决方案的人。下面是代码,但是如果需要有关上下文的更多详细信息,请检查以下要点:gist

import * as crypto from 'crypto';

/**
 * This class is an implementation to encrypt/decrypt 3DES encrypted from .NET
 */
export class TripleDESCryptoHelper {
  // Encryption algorithm
  private static readonly algorithm = 'des-ede-cbc';
  /**
   * Decrypts a value encrypted using 3DES Algorithm.
   *
   * @param encryptionKey Key used for encryption
   * @param encryptedValue Value to be decrypted
   * @returns string containing the value (ascii)
   */
  static decrypt(encryptionKey: string, encryptedValue: string): string {
    const keyHash = crypto
      .createHash('md5')
      .update(encryptionKey)
      .digest();
    const iv = keyHash.slice(0, 8);

    const encrypted = Buffer.from(encryptedValue, 'base64');
    const decipher = crypto.createDecipheriv(TripleDESCryptoHelper.algorithm, keyHash, iv);
    const decoded = decipher.update(encrypted, undefined, 'ascii') + decipher.final('ascii');

    return decoded;
  }

  /**
   * Encrypts a value using 3DES Algorithm.
   *
   * @param encryptionKey Key used for encryption
   * @param encryptedText The text to be encrypted
   */
  static encrypt(encryptionKey: string, encryptedText: string): string {
    const keyHash = crypto
      .createHash('md5')
      .update(encryptionKey)
      .digest();
    const iv = keyHash.slice(0, 8);

    const encrypted = Buffer.from(encryptedText);

    const cipher = crypto.createCipheriv(TripleDESCryptoHelper.algorithm, keyHash, iv);
    const encoded = Buffer.concat([cipher.update(encrypted), cipher.final()]);
    const encodedAsBase64 = encoded.toString('base64');

    return encodedAsBase64;
  }
}