Sample code for 30+ languages & platforms
Xbase++ Requires Chilkat v10.1.2+

RSA Sign String using Private Key of Certificate Type A3 (smart card / token)

See more RSA Examples

Demonstrates RSA signing a string using the private key of a certificate type A3 (smart card, token).

Note: This is a Windows-only example.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oCertStore
LOCAL cThumbprint
LOCAL nBReadOnly
LOCAL oJson
LOCAL oCert
LOCAL oRsa
LOCAL nBUsePrivateKey
LOCAL cSigBase64

nSuccess := 0

//  First get the A3 certificate that was installed on the Windows system.
oCertStore := CreateObject("Chilkat.CertStore")

cThumbprint := "12c1dd8015f3f03f7b1fa619dc24e2493ca8b4b2"

//  This is specific to Windows because it is opening the Windows Current-User certificate store.
nBReadOnly := 1
nSuccess := oCertStore:OpenCurrentUserStore(nBReadOnly)
IF (nSuccess != 1)
    ? oCertStore:LastErrorText
    oCertStore:destroy()
    RETURN
ENDIF

//  Find the certificate with the desired thumbprint
//  (There are many ways to locate a certificate.  This example chooses to find by thumbprint.)
oJson := CreateObject("Chilkat.JsonObject")
oJson:UpdateString("thumbprint", cThumbprint)

oCert := CreateObject("Chilkat.Cert")
nSuccess := oCertStore:FindCert(oJson, oCert)
IF (nSuccess == 0)
    ? "Failed to find the certificate."
    oCertStore:destroy()
    oJson:destroy()
    oCert:destroy()
    RETURN
ENDIF

? "Found: " + oCert:SubjectCN

oRsa := CreateObject("Chilkat.Rsa")

//  Provide the cert's private key
nBUsePrivateKey := 1
nSuccess := oRsa:SetX509Cert(oCert, nBUsePrivateKey)
IF (nSuccess != 1)
    ? oRsa:LastErrorText
    oCertStore:destroy()
    oJson:destroy()
    oCert:destroy()
    oRsa:destroy()
    RETURN
ENDIF

//  Return the RSA signature in base64 encoded form.
oRsa:EncodingMode := "base64"

//  Sign the utf-8 byte representation of the string.
oRsa:Charset := "utf-8"

//  You can also choose other hash algorithms, such as SHA-1.
cSigBase64 := oRsa:SignStringENC("text to sign", "SHA-256")
IF (oRsa:LastMethodSuccess != 1)
    ? oRsa:LastErrorText
    oCertStore:destroy()
    oJson:destroy()
    oCert:destroy()
    oRsa:destroy()
    RETURN
ENDIF

? "Base64 signature: " + cSigBase64

oCertStore:destroy()
oJson:destroy()
oCert:destroy()
oRsa:destroy()