我使用以下CNG序列成功地生成了RSA密钥:
BCryptOpenAlgorithmProvider(.., BCRYPT_RSA_ALGORITHM, ...);
BCryptGenerateKeyPair(..., 2048/*Key size*/, ...);
BCryptFinalizeKeyPair(...);
BCryptExportKey(..., BCRYPT_RSAPRIVATE_BLOB, ...);
BCryptExportKey(..., BCRYPT_RSAPUBLIC_BLOB, ...);我很困惑,虽然生成的缓冲区的哪一部分应该被Base64编码以写出一个PEM文件?如果我Base64对现有有效的PEM文件所拥有的整个缓冲区进行编码,我将不会在缓冲区中看到'MIIE‘。
如有任何指导,将不胜感激。
发布于 2021-11-10 10:00:38
实际上不需要直接base64编码来自BCryptExportKey或NCryptExportKey的输出,而是执行额外的步骤:
BCRYPT_RSAPUBLIC_BLOB
BCRYPT_RSAFULLPRIVATE_BLOB (而不是BCRYPT_RSAPRIVATE_BLOB )一起使用BCryptExportKey (或NCryptExportKey),对于CNG_RSA_PRIVATE_KEY_BLOB或CNG_RSA_PUBLIC_KEY_BLOB使用BCryptExportKey生成的BCRYPT_RSAKEY_BLOB,在PKCS_PRIVATE_KEY_INFO
CryptBinaryToStringA
中使用BCryptExportKey CRYPT_PRIVATE_KEY_INFO
只有在此之后,缓冲区中才会出现“MIIE”。
HRESULT bthr(BOOL b)
{
return b ? S_OK : HRESULT_FROM_WIN32(GetLastError());
}
HRESULT ExportToPem(_In_ BCRYPT_KEY_HANDLE hKey, BOOL bPrivate, _Out_ PSTR* ppsz, _Out_ PULONG pcch)
{
HRESULT hr;
CRYPT_PRIVATE_KEY_INFO PrivateKeyInfo = { 0, {const_cast<PSTR>(szOID_RSA_RSA)} };
ULONG cbKey = 0;
PUCHAR pbKey = 0;//really PBCRYPT_RSAKEY_BLOB
PCWSTR pszBlobType;
PCSTR lpszStructType;
if (bPrivate)
{
pszBlobType = BCRYPT_RSAFULLPRIVATE_BLOB;
lpszStructType = CNG_RSA_PRIVATE_KEY_BLOB;
}
else
{
pszBlobType = BCRYPT_RSAPUBLIC_BLOB;
lpszStructType = CNG_RSA_PUBLIC_KEY_BLOB;
}
while (0 <= (hr = BCryptExportKey(hKey, 0, pszBlobType, pbKey, cbKey, &cbKey, 0)))
{
if (pbKey)
{
if (0 <= (hr = bthr(CryptEncodeObjectEx(X509_ASN_ENCODING,
lpszStructType, pbKey, CRYPT_ENCODE_ALLOC_FLAG, 0,
&PrivateKeyInfo.PrivateKey.pbData, &PrivateKeyInfo.PrivateKey.cbData))))
{
hr = bthr(CryptEncodeObjectEx(X509_ASN_ENCODING, PKCS_PRIVATE_KEY_INFO,
&PrivateKeyInfo, CRYPT_ENCODE_ALLOC_FLAG, 0,
&pbKey, &cbKey));
LocalFree(PrivateKeyInfo.PrivateKey.pbData);
if (0 <= hr)
{
PSTR psz = 0;
ULONG cch = 0;
while (0 <= (hr = bthr(CryptBinaryToStringA(
pbKey, cbKey, CRYPT_STRING_BASE64, psz, &cch))))
{
if (psz)
{
*ppsz = psz, *pcch = cch;
break;
}
if (!(psz = (PSTR)LocalAlloc(0, cch)))
{
hr = HRESULT_FROM_WIN32(GetLastError());
break;
}
}
LocalFree(pbKey);
}
}
break;
}
pbKey = (PUCHAR)alloca(cbKey);
}
return hr;
}并使用它:
PSTR psz;
ULONG cch;
if (0 <= ExportToPem(hKey, bPrivate, &psz, &cch))
{
PSTR pc = psz;
ULONG cb;
do
{
cb = min(cch, 0x100);
DbgPrint("%.*s", cb, pc);
} while (pc += cb, cch -= cb);
LocalFree(psz);
}https://stackoverflow.com/questions/69909118
复制相似问题