使用Chilkat 3DES提供程序进行加密,使用标准.NET提供程序进行相同的结果

时间:2015-11-30 20:40:54

标签: c# .net encryption 3des chilkat

这是一个问题。有一个知名的图书馆&Chilkat Crypt'。它包含3des加密方法。

 public static void ChilkatEncryption(String cc, string tdesKey, string tdesIV)
    {
        Crypt2 crypt = new Chilkat.Crypt2();

        bool success = crypt.UnlockComponent("Anything for 30-day trial");
        if (success != true)
        {
            Console.WriteLine(crypt.LastErrorText);
            return;
        }

        //  Specify 3DES for the encryption algorithm:
        crypt.CryptAlgorithm = "3des";

        //  CipherMode may be "ecb" or "cbc"
        crypt.CipherMode = "cbc";

        //  KeyLength must be 192.  3DES is technically 168-bits;
        //  the most-significant bit of each key byte is a parity bit,
        //  so we must indicate a KeyLength of 192, which includes
        //  the parity bits.
        crypt.KeyLength = 192;

        //  The padding scheme determines the contents of the bytes
        //  that are added to pad the result to a multiple of the
        //  encryption algorithm's block size.  3DES has a block
        //  size of 8 bytes, so encrypted output is always
        //  a multiple of 8.
        crypt.PaddingScheme = 0;

        //  EncodingMode specifies the encoding of the output for
        //  encryption, and the input for decryption.
        //  It may be "hex", "url", "base64", or "quoted-printable".
        crypt.EncodingMode = "hex";

        //  An initialization vector is required if using CBC or CFB modes.
        //  ECB mode does not use an IV.
        //  The length of the IV is equal to the algorithm's block size.
        //  It is NOT equal to the length of the key.
        string ivHex = tdesIV;
        crypt.SetEncodedIV(ivHex, "hex");

        //  The secret key must equal the size of the key.  For
        //  3DES, the key must be 24 bytes (i.e. 192-bits).
        string keyHex = tdesKey;
        crypt.SetEncodedKey(keyHex, "hex");

        //  Encrypt a string...
        //  The input string is 44 ANSI characters (i.e. 44 bytes), so
        //  the output should be 48 bytes (a multiple of 8).
        //  Because the output is a hex string, it should
        //  be 96 characters long (2 chars per byte).
        string encStr = crypt.EncryptStringENC(cc);
        Console.WriteLine(encStr);

        //  Now decrypt:
        string decStr = crypt.DecryptStringENC(encStr);
        Console.WriteLine(decStr);
    }

当我试图在没有使用标准提供商的第三方库的情况下做同样的事情时,结果却截然不同:

    private static string EncryptData(String cc, byte[] tdesKey, byte[] tdesIV)
    {
        //Create the file streams to handle the input and output files.
        MemoryStream fin = new MemoryStream();
        MemoryStream fout = new MemoryStream();
        StreamWriter sw = new StreamWriter(fin);
        sw.Write(cc);
        sw.Flush();
        fin.Position = 0;
        fout.SetLength(0);

        //Create variables to help with read and write.
        byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
        long rdlen = 0;              //This is the total number of bytes written.
        long totlen = fin.Length;    //This is the total length of the input file.
        int len;                     //This is the number of bytes to be written at a time.

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Mode=CipherMode.CBC;
        tdes.Padding = PaddingMode.None;
        CryptoStream encStream = new CryptoStream(fout, tdes.CreateEncryptor(tdesKey, tdesIV), CryptoStreamMode.Write);

        Console.WriteLine("Encrypting...");

        //Read from the input file, then encrypt and write to the output file.
        while (rdlen < totlen)
        {
            len = fin.Read(bin, 0, 100);
            encStream.Write(bin, 0, len);
            rdlen = rdlen + len;
            Console.WriteLine("{0} bytes processed", rdlen);
        }

        byte[] encBytes = fout.ToArray();

        return BitConverter.ToString(encBytes);


    }

有谁知道,标准.NET加密的参数集应该是什么才能获得相同的3DES结果?

谢谢!

1 个答案:

答案 0 :(得分:1)

填充不正确

根据Chilkat文档herePaddingScheme值为0表示库将使用PKCS#5填充。 PKCS#5基本上只是PKCS#7的特例,它仅针对大小为8字节的块密码指定,例如Triple DES。使用.NET提供程序,您应该如上所述指定PaddingMode.PKCS7而不是PaddingMode.None

此外,您需要确保明确关闭CryptoStream,以便它知道您已完成写入,以便它可以加密最终(填充)块:

encStream.Close();
byte[] encBytes = fout.ToArray();

编码错误

可能会或可能不会给您带来问题的另一个问题是两个不同的示例使用不同的文本编码。 Chilkat库看起来默认使用“ANSI”编码。但是,在第二个示例中,您没有在StreamWriter构造函数中明确指定编码,因此它默认为UTF-8。

根据您正在加密的数据,这可能会或可能不会给您带来问题,但基本上如果您有任何超出普通旧ASCII范围的字符,您将在两个函数之间得到不一致的结果,因为您不会实际上是加密相同的东西。

快速解决方法是在StreamWriter构造函数中指定编码:

StreamWriter sw = new StreamWriter(fin, Encoding.Default);

这将为您提供StreamWriter,它将根据您系统的默认ANSI代码页从字符串中写入字节。这个问题的一大问题是,无论系统上的“ANSI”意味着什么,都不一定与其他人的系统相同(详细解释见this question),如果需要,这可能会导致问题互操作。

出于这个原因,我强烈建议您指定更具体的编码,例如UTF-8。

对于Chilkat库,您可以这样做:

crypt.Charset = "utf-8";    

对于.NET提供程序示例,您可以在StreamWriter构造函数中明确指定编码:

StreamWriter sw = new StreamWriter(fin, Encoding.UTF8);

您也可以省略该参数,因为UTF-8是StreamWriter类使用的默认编码。

<小时/> 顺便说一下,不是使用StreamWriter在开始时将输入字符串编码/写入内存流fin,然后再将其读回以一次写入CryptoStream 100个字节,你可以直接编码到一个字节数组并立即写入CryptoStream

var buffer = Encoding.UTF8.GetBytes(cc);
encStream.Write(buffer, 0, buffer.Length);