procedure TForm3.MPrint(const Msg: String);
begin
Memo1.Lines.Add(Msg);
end;
procedure TForm3.MPrint(const Msg: String; const Args: array of Const);
begin
Memo1.Lines.Add(Format(Msg, Args));
end;
procedure TForm3.Button4Click(Sender: TObject);
Var
ihCryptProv: HCRYPTPROV; //
Handle for the cryptographic provider context.
hKey: HCRYPTKEY; // Public/private key
handle.
pszContainerName: String;
e: HRESULT;
procedure ErrorGLE(const Msg: String);
var
n: Cardinal;
begin
n := GetLastError();
MPrint('Error: %s (%s)', [Msg, SysErrorMessage(n)]);
Abort;
end;
begin
hKey := 0;
ihCryptProv := 0;
// The name of the container.
pszContainerName := 'My Sample Key Container';
try
//---------------------------------------------------------------
// Begin processing. Attempt to acquire a context by using the
// specified key container.
if CryptAcquireContext(ihCryptProv, @pszContainerName[1], NIL, PROV_RSA_FULL, 0) Then
begin
MPrint('CryptAcquireContext - A crypto context with ''%s'' key container has been acquired.', [pszContainerName]);
end
else
begin
//-----------------------------------------------------------
// Some sort of error occurred in acquiring the context.
// This is most likely due to the specified container
// not existing. Create a new key container.
e := GetLastError;
if e = NTE_BAD_KEYSET Then
begin
if CryptAcquireContext(ihCryptProv, @pszContainerName[1], NIL, PROV_RSA_FULL, CRYPT_NEWKEYSET) then
begin
MPrint('A new key container has been created.');
end
else
begin
MPrint('Could not create a new key container.');
end;
end
else
ErrorGLE('CryptAcquireContext failed!');
end;
//---------------------------------------------------------------
// A context with a key container is available.
// Attempt to get the
handle to the signature key.
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv Liefert ERROR_ACCESS_DENIED
if CryptGetUserKey(ihCryptProv, AT_SIGNATURE, hKey) then
begin
MPrint('A signature key is available.');
end
else
begin
MPrint('No signature key is available.');
e := GetLastError;
if e = NTE_NO_KEY then
begin
//-------------------------------------------------------
// The error was that there is a container but no key.
// Create a signature key pair.
MPrint('The signature key does not exist.');
MPrint('Create a signature key pair.');
if CryptGenKey(ihCryptProv, AT_SIGNATURE, 0, hKey) then
begin
MPrint('Created a signature key pair.');
end
else
begin
MPrint('Error occurred creating a signature key.');
end;
End
else
ErrorGLE('CryptGenKey - Could not get Signature key!');
end;
finally
end;
end;