Read the X.509 certificates visible on a token and get the chosen certificate's CKA_ID. PKCS#11 uses this byte string to associate a certificate with its key on that token.
The user typically has to locate the PKCS#11 DLL supplied with their token's middleware. Its name and installation folder depend on the vendor. If the user does not know which file to choose, the vendor's middleware documentation or the administrator who installed it can identify the module. A Win32 application needs the 32-bit DLL even on 64-bit Windows. A Win64 application needs the 64-bit DLL.
Give the user a file picker in the application's token settings and save the full path they select. At startup, create one tPkcs11Library, pass that path to Load, then call Initialize and check for CKR_OK. Allow the user to select the DLL again if a middleware update moves it.
uses
System.Classes, System.SysUtils, stGC, stDERCoder, stDERUtils,
StreamSec.DSI.PkixCert, StreamSec.DSI.Pkcs11, StreamSec.DSI.Pkcs11Token;
type tTokenCertificate = record LabelText: string; Certificate: iCertificate; KeyID: TBytes; end;
Pass the initialized library to ListTokenCertificates. Keep it alive until all its token sessions have closed.
function ListTokenCertificates(aLibrary: tPkcs11Library; const aTokenName: string): TArray<tTokenCertificate>; var lToken: tPkcs11Token; begin if (aLibrary = nil) or (aLibrary.FuncList = nil) then raise EArgumentException.Create('Supply an initialized PKCS#11 library'); if Trim(aTokenName) = '' then raise EArgumentException.Create('Supply a token serial number or label'); lToken := tPkcs11Token.Create(aLibrary); try if not lToken.Open(aTokenName) then raise ePkcs11TokenError.CreateFmt('Could not open token "%s"', [aTokenName]); Result := ReadTokenCertificates(lToken); finally lToken.Free; end; end;
Pass the token serial number or a unique token label. Open uses the first case-insensitive match. Prefer the serial number when multiple tokens have the same label. Slot numbers can change when a token is reinserted.
The function opens a read-only session and supplies no PIN. The module decides which objects are visible. An empty array means this session found no readable X.509 certificate values. It does not establish whether the token holds a private key.
function ReadTokenCertificates(aToken: tPkcs11Token): TArray<tTokenCertificate>; var lClass: CK_OBJECT_CLASS; lType: CK_CERTIFICATE_TYPE; lFilter: array[0..1] of CK_ATTRIBUTE; lHandles: tCK_ObjectHandleArray; lHandle: CK_OBJECT_HANDLE; lDer, lLabel: TBytes; lStream: TBytesStream; lCount: Integer; begin if (aToken = nil) or not aToken.IsOpen then raise EArgumentException.Create('Supply an open token session'); lClass := CKO_CERTIFICATE; lType := CKC_X_509; lFilter[0]._type := CKA_CLASS; lFilter[0].pValue := @lClass; lFilter[0].ulValueLen := SizeOf(lClass); lFilter[1]._type := CKA_CERTIFICATE_TYPE; lFilter[1].pValue := @lType; lFilter[1].ulValueLen := SizeOf(lType); lHandles := aToken.FindObjects(lFilter); Result := nil; SetLength(Result, Length(lHandles)); lCount := 0; for lHandle in lHandles do begin if not aToken.GetAttribute(lHandle, CKA_VALUE, lDer) or (Length(lDer) = 0) then Continue; lStream := TBytesStream.Create(lDer); try Result[lCount].Certificate := tCertificate.Create(gcamFirstAssignment); Result[lCount].Certificate.GetStruct.LoadFromStream(lStream, fmtDER); Result[lCount].Certificate.GetStruct.ReadOnly := True; Result[lCount].Certificate.GetStruct.ExpandFull; finally lStream.Free; end; if aToken.GetAttribute(lHandle, CKA_LABEL, lLabel) then Result[lCount].LabelText := TEncoding.UTF8.GetString(lLabel); if not aToken.GetAttribute(lHandle, CKA_ID, Result[lCount].KeyID) then Result[lCount].KeyID := nil; Inc(lCount); end; SetLength(Result, lCount); end;
Each entry contains the decoded certificate, its optional display label, and its ID bytes. For a list on screen, display the subject and issuer from Certificate.tbsCertificate and use BytesToHex(KeyID, True) if you also want to show the ID. Preserve the original bytes for key lookup. An ID can contain zeros or bytes outside the text encoding. Some certificates have an absent or empty ID and can still be listed.
function ChooseTokenCertificate(const aEntries: array of tTokenCertificate; const aExpected: iCertificate; out aKeyID: TBytes): Boolean; var i, lMatch: Integer; lExpectedDer: TBytes; begin Result := False; aKeyID := nil; if aExpected = nil then Exit; lExpectedDer := aExpected.GetStruct.EncodedContents(tDERCoder.DefaultCoder, True); lMatch := -1; for i := 0 to High(aEntries) do if Assigned(aEntries[i].Certificate) and (CompareBytes(lExpectedDer, aEntries[i].Certificate.GetStruct.EncodedContents( tDERCoder.DefaultCoder, True)) = 0) then begin if lMatch >= 0 then Exit; lMatch := i; end; if lMatch < 0 then Exit; if Length(aEntries[lMatch].KeyID) = 0 then Exit; aKeyID := Copy(aEntries[lMatch].KeyID); Result := True; end;
Load the expected certificate from your trusted application configuration. Read a certificate file shows how. Pass the returned array, the expected certificate and an output byte array to ChooseTokenCertificate. It compares the complete certificates and returns the binary ID only for one matching entry with a usable ID.
To use the key from the same session, call ReadTokenCertificates with your open token and make the same selection before signing. Sign data with an RSA key on a PKCS#11 token shows how to match the private key and verify the resulting signature.
StreamSec.DSI.Pkcs11 · StreamSec.DSI.Pkcs11Token · StreamSec.DSI.PkixCert