Contents · Forum Home · StreamSec Tools 4.1.5.364 documentation

Create a key and a certificate signing request

To get a certificate from a CA you send it a certificate signing request (CSR): your public key and the names the certificate is for, signed with the private key. The private key never leaves your machine; you keep it in a password-protected file until the certificate arrives, and after.

The components on this page are normally placed on a form or a data module at design time and set up in the Object Inspector. The sample creates them in code instead, because code shows at a glance which properties are changed from their default values.

The units

uses
  System.SysUtils, System.Classes,
  stOIDs,                          // prime256v1
  stSecUtils,                      // iSecretKey, ProtectClear
  stRandom, stDrbgAesCtr,          // the random generator: new keys
  stAESNI, stAESCT,                // the AES the random generator runs on
  stASN1Base, stPEMCoder,          // SaveToFile, fmtPEM
  StreamSec.DSI.Arith, StreamSec.DSI.ECArith, StreamSec.DSI.ECC,
  StreamSec.DSI.ECC.NISTCurves,
  StreamSec.DSI.ArithComp,         // TstECDSAKey
  StreamSec.DSI.CustomKeyFormat,   // eKeyFormatError
  StreamSec.DSI.Pkcs8Format,       // the PKCS #8 key-file formats
  StreamSec.DSI.Pkcs10,            // iCertificationRequest
  StreamSec.DSI.Pkcs10Generator;   // BuildCertificationRequest

A new key comes from the random generator, which runs on AES: Generate random bytes and keys says which AES units to link and why.

The password

type
  { Hands the key file's password to the key component through OnPassword,
    encoded in the code page aCodePage - UTF-8 unless another is given.
    Owned by the key component, so it lives as long as the key does. }
  tKeyPassword = class(TComponent)
  private
    fPassword: string;
    fCodePage: Integer;
    procedure Supply(Sender: TObject; aPassword: iSecretKey);
  public
    constructor Create(aKey: TstECDSAKey; const aPassword: string;
                       aCodePage: Integer = CP_UTF8); reintroduce;
  end;

The sample hands the password to the key component as UTF-8, through OnPassword, so the key file opens on any computer, whatever its locale. PrivateKeyPassword is the simpler way for files that stay with users of one locale; Choose the encoding of a key file's password describes both.

Open the key file, or create it

function OpenOrCreateKey(const aKeyFile, aPassword: string): TstECDSAKey;
begin
  Result := TstECDSAKey.Create(nil);
  try
    { Encrypted PKCS #8 in PEM - the format ECDSA keys are listed under. }
    Result.PrivateKeyFormat.SelectedOptionNames := 'PKCS8-Encrypted-PEM-DSS';
    { The password through OnPassword, as UTF-8, which does not depend on
      the locale: the file opens on any computer. PrivateKeyPassword would
      encode it in the code page of this computer's locale. }
    tKeyPassword.Create(Result, aPassword);
    { The file name BEFORE a key is generated: assigning it discards any key
      the component holds, because the key then lives in that file. }
    Result.PrivateKeyFileName := aKeyFile;
    if not FileExists(aKeyFile) then begin
      Result.GenerateNewKeys(prime256v1, False);   // a new P-256 key pair
      Result.SavePrivateKey;
    end;
    { Enabled MUST be set to True here, before the key is passed on: it is
      what reads the key from the file, and what takes the key component as
      TComponent - BuildCertificationRequest, the ACME client - cannot set it.
      A wrong password raises nothing; Enabled then reads False. }
    Result.Enabled := True;
    if not Result.Enabled then
      raise eKeyFormatError.CreateFmt('%s did not open: wrong password?', [aKeyFile]);
  except
    Result.Free;
    raise;
  end;
end;

Three things in an order that matters:

Write the request

procedure WriteCsr(aKey: TstECDSAKey; const aCommonName: string;
  const aDnsNames: array of string; const aCsrFile: string);
var
  lNames: TStringList;
  lName: string;
  lRequest: iCertificationRequest;
begin
  lNames := TStringList.Create;
  try
    { Every DNS name becomes a subjectAltName entry - what a CA issues for.
      An empty common name is allowed, and is what ACME CAs prefer. }
    for lName in aDnsNames do
      lNames.Add(lName);
    lRequest := BuildCertificationRequest(aKey, lNames, aCommonName);
  finally
    lNames.Free;
  end;
  lRequest.GetStruct.SaveToFile(aCsrFile, fmtPEM);
end;
procedure MakeServerCsr(const aDir, aPassword: string);
var
  lKey: TstECDSAKey;
begin
  lKey := OpenOrCreateKey(TPath.Combine(aDir, 'www.key'), aPassword);
  try
    WriteCsr(lKey, '', ['www.example.com', 'example.com'],
             TPath.Combine(aDir, 'www.csr'));
  finally
    lKey.Free;
  end;
end;

The .csr file is what the CA asks you to upload. When the certificate comes back, it belongs with this key: a TLS server reads the two together from a PFX file, as in Serve HTTPS from a PFX file.

For a CA that speaks ACME - Let's Encrypt among them - the whole exchange is automatic: see Get a certificate from Let's Encrypt.

Reference

TstECDSAKey · StreamSec.DSI.ArithComp · StreamSec.DSI.Pkcs10Generator

Related tasks