gpt4 book ai didi

c++ - C++ 中的 AES/Rijndael Microsoft CryptoAPI

转载 作者:搜寻专家 更新时间:2023-10-31 01:43:12 24 4
gpt4 key购买 nike

如何使用 Microsoft CryptoAPI(CryptDeriveKey、BCrypt[...] 函数、CryptAcquireContext 等)将以下加密代码 (VB.NET 4.0) 转换为等效的 C++ 代码? (我还没有在 Internet 上找到一篇描述使用 Microsoft CryptoAPI 的 AES 的文章...)

Dim Key(31) As Byte
Dim IV(15) As Byte

Array.Copy(SomeByteArray, IV, 16)
Array.Copy((New SHA512Managed).ComputeHash(SomeByteArray), Key, 32)

Using AESEncr As New RijndaelManaged() With {.Padding = PaddingMode.ISO10126}

FinalEncrypted = AESEncr.CreateEncryptor(Key, IV).TransformFinalBlock(AnotherByteArray, 0, AnotherByteArray.GetLength(0))

End Using

和解密的:

Dim Key(31) As Byte
Dim IV(15) As Byte

Array.Copy(SomeByteArray, IV, 16)
Array.Copy((New SHA512Managed).ComputeHash(SomeByteArray), Key, 32)

Using AESEncr As New RijndaelManaged() With {.Padding = PaddingMode.ISO10126}

FinalDecrypted = AESEncr.CreateDecryptor(Key, IV).TransformFinalBlock(FinalEncrypted, 0, FinalEncrypted.GetLength(0))

End Using

(注意:我已经有了关于 SHA-512 方法的 C++ 代码,所以不要再费心了。)

最佳答案

因此,我为 AES-256 加密/解密编写的代码如下:(它以 BYTE* DataBYTE* IV 作为参数)

    BYTE *hash, *res;
HCRYPTPROV hCrypt = NULL;
HCRYPTKEY hKey = NULL;

struct {
BLOBHEADER hdr;
DWORD len;
BYTE key[32];
} key_blob;

key_blob.hdr.bType = PLAINTEXTKEYBLOB;
key_blob.hdr.bVersion = CUR_BLOB_VERSION;
key_blob.hdr.reserved = 0;
key_blob.hdr.aiKeyAlg = CALG_AES_256;
key_blob.len = 32;

hash = ComputeSHA512Hash(IV);
copy(hash, hash + 32, key_blob.key);

res = new BYTE[16];
copy(Data, Data + 15, res);
res[15] = 0;

// Get the Microsoft Enhanced RSA and AES Cryptographic Service Provider

if (!CryptAcquireContext(&hCrypt, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
throw E_FAIL;

// Import our key blob

if (!CryptImportKey(hCrypt, (BYTE *)&key_blob, sizeof(key_blob), NULL, 0, &hKey))
throw E_FAIL;

// Set the mode to Cipher Block Chaining

DWORD dwMode = CRYPT_MODE_CBC;

if (!CryptSetKeyParam(hKey, KP_MODE, (BYTE *)&dwMode, 0))
throw E_FAIL;

// Set the Initialization Vector to ours

if (!CryptSetKeyParam(hKey, KP_IV, IV, 0))
throw E_FAIL;

// Do the main encryption

DWORD pdwDataLen = 15;

if (!CryptEncrypt(hKey, NULL, TRUE, 0, res, &pdwDataLen, 16))
throw E_FAIL;

// Do the main decryption

pdwDataLen = 16;

if (!CryptDecrypt(hKey, NULL, TRUE, 0, res, &pdwDataLen))
throw E_FAIL;

// Destroy whatever was created before (free memory)

delete hash;

delete res;

if (hKey)
CryptDestroyKey(hKey);

if (hCrypt)
CryptReleaseContext(hCrypt, 0);

正如我之前所说,我已经有了 ComputeSHA512Hash() 函数的代码,因此我的代码已完成我的用途。我希望这段代码对每个想要编写 AES-256 代码的人都有用。

关于c++ - C++ 中的 AES/Rijndael Microsoft CryptoAPI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25609064/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com