Sign/Verify using Certificate

This example demonstrates the various sign/verify options using certificates

Create a private/public key and certificate:


procedure TFrmMain.btnCreateCertClick(Sender: TObject);
var
  CertStore: IRwCertStore;
  Cert: IRwCertificate;
begin
  // Open a memory store
  CertStore := TRwNCrypt.OpenCertStore;

  // Create a self signed certicate
  Cert := CertStore.CreateSelfSignedCertificate(TRwDN.Create(memoSubject.Lines), dtValidFrom.DateTime, dtValidTo.DateTime, 1024);

  // Get the data in PEM format
  memoCertData.Text := Cert.ToPEM(expCert);
  memoPrivateKeyData.Text := Cert.ToPEM(expPrivateKey);
  memoPublicKeyData.Text := Cert.ToPEM(expPublicKey );
end;

Create a signed message:


procedure TFrmMain.btnCreateSignedMessageClick(Sender: TObject);
var
  CertStore: IRwCertStore;
  Cert: IRwCertificate;
begin
  // To Sign we will need the private key
  // So add the certificate inlcluding the private key to the store
  CertStore := TRwNCrypt.OpenCertStore;
  Cert := CertStore.AddCertificate(memoCertData.Text + #13#10 + memoPrivateKeyData.Text);

  memoSigned.Text := CertStore.SignMessage(TRwBytes.FromString(memoToSign.Text, True), Cert, calgSHA1, Sender = btnCreateDetachedSignature).Encode(beBase64);

  btnVerifyMessage.Enabled := Sender = btnCreateSignedMessage;
  btnVerifyDetachedSignature.Enabled := (Sender = btnCreateDetachedSignature);
  btnVerifySignature.Enabled := False;
end;

Verify the signed message:


procedure TFrmMain.btnVerifyMessageClick(Sender: TObject);
var
  CertList: TArray;
  CertStore: IRwCertStore;
  OrginalCert, MessageCert: IRwCertificate;
  Timestamp: TDateTime;
begin
  CertStore := TRwNCrypt.OpenCertStore;
  OrginalCert := CertStore.AddCertificate(memoCertData.Text);

  // get the original message + the certificates that were used to sign it
  memoVerified.Text := CertStore.VerifyMessage(TRwBytes.Decode(memoSigned.Text, beBase64), CertList).ToString(True);

  // Also get the timestamp
  Timestamp := CertStore.VerifyMessageTimeStamp(TRwBytes.Decode(memoSigned.Text, beBase64));

  // please note that a message can be signed by more than 1 certificate (private key)
  // in this example we just check the first
  MessageCert := CertList[0];

  if OrginalCert.ThumbPrint = MessageCert.ThumbPrint then
    RwMsgBoxInfo('Verified (Timestamp='+DateTimeToStr(Timestamp)+').')
  else
    RwMsgBoxWarning('The message was a signed message, but it was not signed by '+OrginalCert.Subject['CN']);
end;

This example also demonstrates how to create create and verify a detached signature and how to create and verify a signed hash.


Back to Examples