Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Sign data with an RSA key on a PKCS#11 token

Use a provisioned RSA key to sign message bytes with SHA-256 and PKCS #1 v1.5. The token performs the private-key operation. The result is a raw RSA signature that recipients can verify using the public certificate.

Select the token and certificate

uses
  System.SysUtils, stSecUtils, stSHA256, StreamSec.DSI.Arith,
  StreamSec.DSI.IFC, StreamSec.DSI.PKTypes, StreamSec.DSI.PkixCert,
  StreamSec.DSI.Pkcs11, StreamSec.DSI.Pkcs11Token,
  StreamSec.DSI.Pkcs11ExtKey, TaskTokenCertificate;

Supply an initialized PKCS#11 library, the token's serial number and the RSA certificate your application expects to use. Validate the certificate under your application's signing policy. On Windows, ask the user to select the vendor's installed PKCS#11 DLL when configuring the token. Load the saved path for the application's bitness. Find a certificate on a PKCS#11 token covers locating the DLL, selecting the certificate and reading its binary CKA_ID. The example expects the certificate to be visible before login.

Sign in and match the private key

procedure LoginForSigning(aToken: tPkcs11Token; const aPassphrase: string);
var
  lResult: CK_RV;
begin
  if aToken.PinLocked or aToken.PinFinalTry then
    raise ePkcs11TokenError.Create('The PIN is locked or has only one attempt left');
  if aPassphrase = '' then
    raise EArgumentException.Create('Supply the token user credential');
  lResult := aToken.Login(aPassphrase);
  if lResult <> CKR_OK then
    raise ePkcs11TokenError.Create('Token login failed: ' + CKRToStr(lResult));
end;

Pass the user credential as entered. The example makes one login attempt and stops when the token reports a locked PIN or a last remaining attempt. It assumes the application supplies the credential. A token with a PIN pad can use a protected authentication path instead.

function MatchingRSAKey(aToken: tPkcs11Token; const aID: TBytes;
  const aPublicKey: iIFPublicKey): iIFPrivateKey;
var
  lClass: CK_OBJECT_CLASS;
  lType: CK_KEY_TYPE;
  lTemplate: array[0..2] of CK_ATTRIBUTE;
  lKeys: tCK_ObjectHandleArray;
begin
  if Length(aID) = 0 then
    raise EArgumentException.Create('The certificate has no key identifier');
  lClass := CKO_PRIVATE_KEY;
  lType := CKK_RSA;
  lTemplate[0]._type := CKA_CLASS;
  lTemplate[0].pValue := @lClass;
  lTemplate[0].ulValueLen := SizeOf(lClass);
  lTemplate[1]._type := CKA_KEY_TYPE;
  lTemplate[1].pValue := @lType;
  lTemplate[1].ulValueLen := SizeOf(lType);
  lTemplate[2]._type := CKA_ID;
  lTemplate[2].pValue := @aID[0];
  lTemplate[2].ulValueLen := Length(aID);
  lKeys := aToken.FindObjects(lTemplate);
  if Length(lKeys) <> 1 then
    raise ePkcs11TokenError.Create('Expected one RSA private key with the certificate ID');
  Result := NewPkcs11PrivateKey(aToken, lKeys[0]);
  if not Assigned(Result.ExternalKey) or not Result.ExternalKey.Validate(aPublicKey) then
    raise ePkcs11TokenError.Create('The token key does not match the certificate modulus');
end;

The search combines the private-key object class, RSA key type and the certificate's exact ID bytes. It must return one key. The external-key adapter checks the public modulus against the certificate before signing. The token must allow that public attribute to be read.

Sign and verify the same message bytes

function VerifyTokenMessage(const aCertificate: iCertificate;
  const aMessage, aSignature: TBytes): Boolean;
var
  lPublicKey: iIFPublicKey;
begin
  Result := False;
  if (aCertificate = nil) or (Length(aSignature) = 0) then Exit;
  if not Supports(aCertificate.subjectPublicKeyInfo, iIFPublicKey, lPublicKey) then Exit;
  Result := MustGetDSIIF.SSASignatureVerification(lPublicKey, aMessage, 0,
    Length(aMessage), aSignature, 0, Length(aSignature), haSHA256, haSHA256, 0, seEMSA3);
end;
function SignTokenMessage(aLibrary: tPkcs11Library; const aSerial, aPassphrase: string;
  const aExpected: iCertificate; const aMessage: TBytes): TBytes;
var
  lToken: tPkcs11Token;
  lID, lSignature: TBytes;
  lPrivateKey: iIFPrivateKey;
  lPublicKey: iIFPublicKey;
  lMechanism: tPkcs11SignMech;
  lLength: Integer;
begin
  if (aLibrary = nil) or (aLibrary.FuncList = nil) or (Trim(aSerial) = '') then
    raise EArgumentException.Create('Supply the initialized module and the token serial');
  if (aExpected = nil) or not Supports(aExpected.subjectPublicKeyInfo, iIFPublicKey, lPublicKey) then
    raise EArgumentException.Create('Supply the expected RSA certificate');
  lToken := tPkcs11Token.Create(aLibrary);
  try
    if not lToken.Open(aSerial) or not SameText(lToken.Serial, aSerial) then
      raise ePkcs11TokenError.Create('The selected token serial is unavailable');
    if not ChooseTokenCertificate(ReadTokenCertificates(lToken), aExpected, lID) then
      raise ePkcs11TokenError.Create('Expected signing certificate and ID not found');
    if not lToken.ResolveSign(haSHA256, seEMSA3, [pskMessage, pskDigestInfo], lMechanism) then
      raise ePkcs11TokenError.Create('The token does not advertise SHA-256 RSA PKCS#1 signing');
    LoginForSigning(lToken, aPassphrase);
    lPrivateKey := MatchingRSAKey(lToken, lID, lPublicKey);
    lLength := MustGetDSIIF.SSASignatureGeneration(lPrivateKey, aMessage, 0,
      Length(aMessage), haSHA256, haSHA256, 0, seEMSA3, lSignature);
    if lLength <= 0 then
      raise ePkcs11TokenError.Create('The token did not produce a signature');
    SetLength(lSignature, lLength);
    if not VerifyTokenMessage(aExpected, aMessage, lSignature) then
      raise ePkcs11TokenError.Create('The signature did not verify with the expected certificate');
    Result := lSignature;
  finally
    lPrivateKey := nil;
    lToken.Free;
  end;
end;

Call SignTokenMessage with the original bytes. Save or send the returned bytes alongside the message. The sample checks the signature with the expected certificate before returning it. A recipient can call VerifyTokenMessage with the same byte sequence and a trusted copy of that certificate. Text encoding and line endings are part of those bytes.

This example owns its session and closes it after releasing the key adapter. Coordinate login and logout if your application shares a token across sessions. Keep the library initialized until all its sessions have closed. For a file signature that carries CMS metadata, see Sign a file and verify its detached CMS signature.

Reference

StreamSec.DSI.Pkcs11 · StreamSec.DSI.Pkcs11Token · StreamSec.DSI.Pkcs11ExtKey · StreamSec.DSI.PKTypes · StreamSec.DSI.PkixCert

Related tasks