1
我设法使用Crypto API加密本地代码中的数据,并使用RC2算法和SHA创建密钥在.NET(C#)代码中对其进行解密。CryptAPI本地互操作与.NET代码
这是本机代码(德尔福在这种情况下):
// Get handle to CSP
If Not CryptAcquireContext(hCryptProv, nil, nil, PROV_RSA_FULL, 0) Then
If Not CryptAcquireContext(hCryptProv, nil, nil, PROV_RSA_FULL, CRYPT_NEWKEYSET) Then
ShowMessage('CryptAcquireContext '+IntToStr(GetLastError()));
// Create a hash object
If Not CryptCreateHash(hCryptProv, CALG_SHA, 0, 0, hHash) Then
ShowMessage('CryptCreateHash '+IntToStr(GetLastError()));
// Hash the password
If Not CryptHashData(hHash,PByte(as_password), Length(as_password), 0) Then
ShowMessage('CryptHashData '+IntToStr(GetLastError()));
// Derive a session key from the hash object
If Not CryptDeriveKey(hCryptProv, CALG_RC2, hHash, CRYPT_EXPORTABLE, hKey) Then
ShowMessage('CryptDeriveKey '+IntToStr(GetLastError()));
// allocate buffer space
lul_datalen := Length(ablob_data);
lblob_buffer := ablob_data + ' ';
lul_buflen := Length(lblob_buffer);
If ab_encrypt Then
// Encrypt data
If CryptEncrypt(hKey, 0, True, 0, PByte(lblob_buffer), lul_datalen, lul_buflen) Then
lblob_value := Copy(lblob_buffer, 1, lul_datalen)
else
ShowMessage('CryptEncrypt '+IntToStr(GetLastError()))
Else
// Decrypt data
If CryptDecrypt(hKey, 0, True, 0, PByte(lblob_buffer), lul_datalen) Then
lblob_value := Copy(lblob_buffer, 1, lul_datalen)
Else
ShowMessage('CryptDecrypt '+IntToStr(GetLastError()));
// Destroy session key
If hKey > 0 Then
CryptDestroyKey(hKey);
// Destroy hash object
If hHash > 0 Then
CryptDestroyHash(hHash);
// Release CSP handle
If hCryptProv > 0 Then
CryptReleaseContext(hCryptProv, 0);
Result := lblob_value;
这在.NET代码:
CspParameters cspParams = new CspParameters(1);
PasswordDeriveBytes deriveBytes = new PasswordDeriveBytes(aPassword, null, "SHA-1", 1, cspParams);
byte[] rgbIV = new byte[8];
byte[] key = deriveBytes.CryptDeriveKey("RC2", "SHA1", 0, rgbIV);
var provider = new RC2CryptoServiceProvider();
provider.Key = key;
provider.IV = rgbIV;
ICryptoTransform transform = provider.CreateDecryptor();
byte[] decyptedBlob = transform.TransformFinalBlock(arData, 0, arData.Length);
现在我想用想用更新更好的AES加密,所以在本机代码中我想用PROV_RSA_AES
代替PROV_RSA_FULL
,CALG_SHA_256
而不是CALG_SHA
和CALG_AES_256
而不是CALG_RC2
。在原生网站上工作正常。
但我不能让它在.NET网站上工作。当然,我需要将RC2CryptoServiceProvider更改为AESCryptoServiceProvider,并且CspParameters必须使用24而不是1进行初始化。我的问题是如何获取PasswordDerivedBytes的工作方式,需要什么确切的参数值?
感谢您的任何提示。
您是否曾经找到过有关如何使用AES工作的解决方案?顺便说一句,谢谢你的代码示例。我在Delphi XE和VS 2010 w/RC2中为我工作。 (尽管使用AES会很喜欢这个。) – Troy 2012-02-14 19:34:34
没关系。我想到了。我在这里发布了我的兼容C#和Delphi示例:http://stackoverflow.com/questions/9188045/how-to-aes-128-encrypt-a-string-using-a-password-in-delphi-and-decrypt- in-c – Troy 2012-02-15 18:11:55