Page 1 of 1

TScCryptoApiStorage and the Windows Certificate Store

Posted: Thu 08 Feb 2018 21:09
by wheathoff
Having some trouble setting up a TScSSLClient object, using a certificate from the certificate store.

With the following code,

Code: Select all

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    FCert:      TScCertificate;
    FKey:       TScKey;
    FStorage:   TScCryptoAPIStorage;
    FClient: TScSSLClient;
  public
    { Public declarations }

  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  FStorage := TScCryptoAPIStorage.Create(nil);

  // point CryptoAPIStorage to the CurrentUser certificate store.
  // (The default CertStoreName is 'MY', which we use, here.)
  // (This method does not find any certificates
  // -- even though 'cert1' is visible in the MMC Snap-In,
  // under Current User/Personal/Certificates.)

  FStorage.CertLocation := clCurrentUser;

  FClient := TScSSLClient.Create(nil);

  FClient.Storage  := FStorage;
  FClient.HostName := 'somehost.com';
  FClient.Port     := 443;
  FClient.IsSecure := True;
  FClient.CertName := 'cert1'; // this certificate exists

  FClient.Connect;

end;

When FClient.Connect is called and we hit the following section of TScSSLClient.DoConnect, where we attempt to assign ClientCertificate, Storage.Certificates.Count is 0 and so ClientCertificate always ens up as nil.

Code: Select all

  if CertName <> '' then begin
    ClientCertificate := Storage.Certificates.FindCertificate(CertName);
    if ClientCertificate <> nil then begin
      ClientCertificate.Ready := True;

      if not ClientCertificate.Key.IsPrivate then
        raise EScError.Create(seCertificateMustBePrivate);
    end;
  end;

So, I am wondering if I am accessing the certificate store correctly. If not, where have I gone wrong?

Also, I found that setting `FStorage.CertLocation := clLocalMachine` causes an "Access Denied (error code 5)" exception, when TScSSLClient.DoConnect attempts to run Storage.Certificates.FindCertificate(CertName). Any idea why that happens?

Thank you!

Re: TScCryptoApiStorage and the Windows Certificate Store

Posted: Fri 09 Feb 2018 14:39
by ViktorV
Please check whether the issue will be reproduced if you run the program under administrator account.

Re: TScCryptoApiStorage and the Windows Certificate Store

Posted: Mon 12 Feb 2018 14:23
by wheathoff
ViktorV wrote:Please check whether the issue will be reproduced if you run the program under administrator account.
Yes, this does resolve the Access Denied exception and Storage.Certificates.Count is no longer zero.

Thanks.

Re: TScCryptoApiStorage and the Windows Certificate Store

Posted: Mon 12 Feb 2018 14:45
by ViktorV
It is good to see that the problem has been solved.
Feel free to contact us if you have any further questions about our products.