我需要使用 X.509 证书提供的公钥使用 RSA 加密某些内容。证书是有序的(在 Windows 资源管理器中检查显示公钥,RSA 20148 位。)
我尝试执行第一个基本步骤(导入公钥)失败 - 我在标记的源行(由 Win32Check 抛出)上收到 EOSError 异常“ASN1 tag bad value”。我该如何解决这个问题?
我在用:
- Rudy Velthuis 的 WinCrypt(最后修改于 2008 年 3 月 7 日)
- 德尔福 (XE2)
源代码:
try
CertPath := 'c:\somefolder\data';
pubCert := TFileStream.Create(CertPath + '\zpr_prod_public_cert.cer', fmOpenRead or fmShareDenyNone);
try
SetLength(Buffer, pubCert.Size);
BufLen := pubCert.read(Pointer(Buffer)^, pubCert.Size);
finally
pubCert.Free;
end;
except
RaiseLastOSError;
Exit;
end;
if Length(Buffer) > 1 then
begin
try
DataLen := 0;
// !!! the following line should actually do the trick, but it doesn't...
// Certcontext remains empty and the errormessage is "ASN1 tag bad value met"
CertContext := CertCreateCertificateContext(X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, @Buffer[0], BufLen);
if CertContext = nil then // Then I'll try another way which results in the same error :(
Win32Check(CryptDecodeObjectEx(X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, X509_PUBLIC_KEY_INFO, @Buffer[0], BufLen, CRYPT_ENCODE_ALLOC_FLAG, nil, @PublicKeyInfo, DataLen))
else
begin // this is actually never reached...so may be ignored
hCProv := __CryptAcquireContext(PROV_RSA_FULL);
if Win32Check(CryptImportPublicKeyInfo(hCProv, X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, @certcontext.pCertInfo.SubjectPublicKeyInfo, hKey)) then
begin
DataLen := Length(einKey);
BufLen := DataLen;
Win32Check(CryptEncrypt(hkey, 0, True, 0, @EinKey[0], DataLen, BufLen));
SetLength(einKey, DataLen);
end;
end;
finally
Win32Check(CryptReleaseContext(hCProv, 0));
end;
end;
- 我是否正确阅读了证书文件?我应该使用其他东西吗?
- 我使用 API 方法对吗?
- 这个错误的原因是什么(“ASN1 tag bad value”)?