2

我已经设法使用 Crypto API 在本机代码中加密数据,并在 .NET (C#) 代码中对其进行解密,使用 RC2 算法和 SHA 来创建密钥。

这是本机代码(在本例中为 Delphi):

// 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_FULLCALG_SHA_256而不是CALG_SHACALG_AES_256而不是CALG_RC2。这在本机站点上运行良好。

但我无法让它在 .NET 网站上运行。当然,我需要将 RC2CryptoServiceProvider 更改为 AESCryptoServiceProvider,并且 CspParameters 必须用 24 而不是 1 初始化。我的问题是如何使用 PasswordDerivedBytes,需要的确切参数值是多少?

感谢您的任何提示。

4

0 回答 0