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