Delphi DLL Requires Chilkat v11.0.0+
Delphi DLL
RSA Sign with PKCS8 Encrypted Key
See more RSA Examples
Demonstrates how to load a private key from an encrypted PKCS8 file and create an RSA digital signature (and then verify it).Chilkat Delphi DLL Downloads
var
success: Boolean;
privKey: HCkPrivateKey;
rsa: HCkRsa;
strData: PWideChar;
hexSig: PWideChar;
cert: HCkCert;
pubKey: HCkPublicKey;
rsa2: HCkRsa;
begin
success := False;
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
privKey := CkPrivateKey_Create();
// Load the private key from an RSA PEM file:
success := CkPrivateKey_LoadAnyFormatFile(privKey,'raul_privateKey.key','a0123456789');
if (success = False) then
begin
Memo1.Lines.Add(CkPrivateKey__lastErrorText(privKey));
Exit;
end;
rsa := CkRsa_Create();
// Import the private key into the RSA component:
success := CkRsa_UsePrivateKey(rsa,privKey);
if (success = False) then
begin
Memo1.Lines.Add(CkRsa__lastErrorText(rsa));
Exit;
end;
// This example will sign a string, and receive the signature
// in a hex-encoded string. Therefore, set the encoding mode
// to "hex":
CkRsa_putEncodingMode(rsa,'hex');
strData := 'This is the string to be signed.';
// Sign the string using the sha256 hash algorithm.
// Other valid choices are sha1, sha384, sha512 and others.
hexSig := CkRsa__signStringENC(rsa,strData,'sha256');
if (CkRsa_getLastMethodSuccess(rsa) = False) then
begin
Memo1.Lines.Add(CkRsa__lastErrorText(rsa));
Exit;
end;
Memo1.Lines.Add(hexSig);
// Now verify with the public key.
// This example shows how to use the public key from
// a digital certificate (.cer file)
cert := CkCert_Create();
success := CkCert_LoadFromFile(cert,'raul_publicKey.cer');
if (success = False) then
begin
Memo1.Lines.Add(CkCert__lastErrorText(cert));
Exit;
end;
pubKey := CkPublicKey_Create();
CkCert_GetPublicKey(cert,pubKey);
rsa2 := CkRsa_Create();
success := CkRsa_UsePublicKey(rsa2,pubKey);
if (success = False) then
begin
Memo1.Lines.Add(CkRsa__lastErrorText(rsa2));
Exit;
end;
// Verify the signature against the original data:
CkRsa_putEncodingMode(rsa2,'hex');
success := CkRsa_VerifyStringENC(rsa2,strData,'sha256',hexSig);
if (success = False) then
begin
Memo1.Lines.Add(CkRsa__lastErrorText(rsa2));
Exit;
end;
Memo1.Lines.Add('Signature verified!');
// Verify with incorrect data:
success := CkRsa_VerifyStringENC(rsa2,'something else','sha256',hexSig);
if (success <> True) then
begin
Memo1.Lines.Add('Signature not verified! (which was expected in this case)');
end
else
begin
Memo1.Lines.Add('Hmmm... that''s not right...');
end;
CkPrivateKey_Dispose(privKey);
CkRsa_Dispose(rsa);
CkCert_Dispose(cert);
CkPublicKey_Dispose(pubKey);
CkRsa_Dispose(rsa2);