我需要使用X.509证书提供的公钥使用RSA加密某些内容。证书是有序的(在Windows资源管理器中检查显示公钥,RSA 20148位。)
我尝试执行第一个基本步骤,导入公钥失败 - 我在标记的源代码行上获得了一个EOSError异常“ASN1标记错误值”(由Win32Check抛出)。我该如何解决这个问题?
我正在使用:
源代码:
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;