将Crypto API调用转换为.NET

时间:2012-04-18 05:05:04

标签: c# .net cryptography cryptoapi

我在C ++中有这个代码(AnsiString是char * buffer的包装器):

BOOL HashIt(AnsiString &pw,BYTE *buf,BYTE &len)
{
   HCRYPTPROV cp;
   CryptAcquireContext(&cp,NULL,NULL,PROV_RSA_AES,CRYPT_VERIFYCONTEXT);

   HCRYPTHASH ch;
   CryptCreateHash(cp,CALG_MD5,0,0,&ch);

   CryptHashData(ch,(BYTE*)pw.c_str(),pw.Length(),0);

   HCRYPTKEY kc;
   CryptDeriveKey(cp,CALG_3DES,ch,CRYPT_EXPORTABLE,&kc);
   CryptExportKey(kc,NULL,PLAINTEXTKEYBLOB,0,buf,&dwLen);

   len = (BYTE) dwLen;
}

到目前为止,我已将此转换为.NET:

    public static byte[] HashItB(string text)
    {
        byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(text);
        System.Security.Cryptography.MD5CryptoServiceProvider sp = new System.Security.Cryptography.MD5CryptoServiceProvider();

        byte[] hashBytes = sp.ComputeHash(textBytes);
        System.Security.Cryptography.PasswordDeriveBytes pdb = new System.Security.Cryptography.PasswordDeriveBytes(hashBytes, new byte[0]);
        hashBytes = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, hashBytes);

        // Need to export key as plain text blob here, CryptExportKey

        return (hashBytes);
    }

假设上面的代码是正确的,我的最后一步是将CryptExportKey函数转换为.NET。有人能指出我的功能还是样品?我不能改变C ++方法,我需要我的.NET代码来匹配遗留应用程序。或者我应该放弃.NET方法并创建一个C ++ DLL并调用它(由于使用我的小应用程序运送另一个DLL的额外大小而不是那么疯狂),或者调用所有加密函数?

3 个答案:

答案 0 :(得分:3)

.NET方法PasswordDeriveBytes.CryptDeriveKey()相当于使用Win32 CryptoAPI方法来散列密码,调用CryptDeriveKey并最终通过调用CryptExportKey导出密钥。

您的C ++代码相当于:

byte[] textBytes = System.Text.Encoding.Default.GetBytes(text); // Default is the ANSI-code-page
System.Security.Cryptography.PasswordDeriveBytes pdb = new System.Security.Cryptography.PasswordDeriveBytes(textBytes, new byte[0]);
byte[] hashBytes = pdb.CryptDeriveKey("TripleDES", "MD5", 0, new byte[8]);

除了.NET代码从导出的密钥(PLAINTEXTKEYBLOB标头)中删除一些标头数据。对于192位3DES密钥,这是"08 02 00 00 03 66 00 00 18 00 00 00"。如果需要,可以在.NET代码中添加它。

答案 1 :(得分:1)

PasswordDeriveBytes.CryptDeriveKey方法已经返回派生密钥,因此无需像在C ++代码中那样导出密钥。

答案 2 :(得分:1)

感谢您的帮助,并且任何人都希望以后阅读这篇文章,这是我最终的结果。我确信字节数组的构建可能会更好,但在我的情况下,这段代码不需要很快,所以我只是选择了易于阅读的内容:

    public static byte[] HashIt(string text)
    {
        byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(text);
        System.Security.Cryptography.PasswordDeriveBytes pdb = new System.Security.Cryptography.PasswordDeriveBytes(textBytes, new byte[0]);
        byte[] hashBytes = pdb.CryptDeriveKey("TripleDES", "MD5", 0, new byte[8]);
        byte[] head = new byte[] { 0x08,0x02, 0x00, 0x00, 0x03, 0x66, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00 };
        byte[] hashBytesWithHead = new byte[hashBytes.Length + head.Length];
        head.CopyTo(hashBytesWithHead,0);
        hashBytes.CopyTo(hashBytesWithHead,head.Length);
        return (hashBytesWithHead);
    }