User Rating: 4 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Inactive
 

12/26/2021 Update:  A PowerBuilder 2021 sample app that includes all of the following code is available in CodeXchange at: https://community.appeon.com/index.php/codeexchange/powerbuilder/306-reading-a-smard-card-from-powerbuilder

We’re going to look at using the Smart Card SDK provided in more recent versions of Windows (XP and later).  Earlier versions of Windows had an ActiveX installed called CAPICOM which could be accessed from PowerBuilder through OLE Automation, but that control was removed as of Windows Vista because of security issues.

We’re going to look at a number of operations:

·         Communication with the card

·         Validating the user’s PIN

·         Reading the certificate Subject Name

·         Reading other certificate data

 
Note:  This post was updated on December 8th, 2021 to support 64 bit compilation.  Thanks to Jason Schultz for pointing out the problem and to John Fauss and others for pointing out the necessary changes.

 

Communicating with the card

The first step is establish a context for the API calls.  To do that, we need to declare the following local external function for SCardEstablishContext:

Function ulong SCardEstablishContext  ( &

  ulong dwScope, &

  longptr pvReserved1, &

  longptr pvReserved2, &

  REF longptr phContext &

  ) Library "winscard.dll"

 

And call it as follows:

ulong    rc

rc = scardestablishcontext( SCARD_SCOPE_USER, 0, 0, context )

IF rc = SCARD_S_SUCCESS THEN

    Return SUCCESS

ELSE

    Return FAILURE

END IF

 

Where the following are defined as constants.


CONSTANT LONG SCARD_S_SUCCESS            = 0

CONSTANT LONG SCARD_SCOPE_USER          = 0

 

Context (the last argument) should be defined as an instance variable because we will need to release it when we are done making API calls.  We will also be passing a reference to it in many of the API calls.


longptr        context

 

The second step is get a reference to the smart card reader(s) that the user’s machine is equipped with.  We do that by declaring the following local external function for the SCardListReaders method in the SDK:

Function ulong SCardListReaders  ( &

  longptr hContext, &

  Long mszGroups, &

  REF Blob mszReaders, &

  REF Long pcchReaders &

  ) Library "winscard.dll" Alias For "SCardListReadersW"

 

The API defines the second argument as a string.  However, we want to pass a null, and the way we do that with PowerBuilder is by declaring the argument as a long and then passing a zero.  That causes the method to return all readers, rather than just a subset.

 

Once we’ve declared that we can use the following PowerScript to get an array that contains the name of all smart card readers on the system.  The SDK returns the list as a null terminated array, so we parse the blob we get back and use the String function to pull the names out and put them in an array that PowerBuilder is more comfortable with.

 

ulong                    rc

long                    ll_bufflen = 32000

long                    ll_readerlen

string                    ls_reader = Space ( ll_bufflen )

blob                    buffer

buffer = Blob ( ls_reader )  // Preallocate space in the buffer or the call will fail

rc = SCardListReaders ( context, 0, buffer, ll_bufflen )

IF ll_bufflen > 0 THEN

    // BlobMid is messed up.  Len reports Unicode chars, BlobMid acts like ANSI chars

    // so we have to double the values we pass to it to get full Unicode characters

    //Truncate the buffer to what was actually returned

    buffer = BlobMid ( buffer, 1, ( ll_bufflen - 1 ) * 2 )

    //Read off the first value (string stops at the null terminator)

    ls_reader = String ( buffer )

    //Add it to the array

    readers[1] = ls_reader

    //See if we have any data left

    ll_readerlen = ( Len ( ls_reader ) * 2 ) + 3

    buffer = BlobMid ( buffer, ll_readerlen )

    ll_bufflen = Len ( buffer )

    //Loop through for the remaining data

    DO WHILE ll_bufflen > 0

        ls_reader = String ( buffer )

        readers[UpperBound(readers)+1] = ls_reader

        ll_readerlen = ( Len ( ls_reader ) * 2 ) + 3

        buffer = BlobMid ( buffer, ll_readerlen )

        ll_bufflen = Len ( buffer )

    LOOP

END IF

 

If there are no readers, there isn’t much further to go.  If there is only one, then you can proceed immediately to check if there is a smart card in it.  If there is more than one reader, you may need to check them all to see which have cards in them, and if more than one do then prompt the user to select the card they want to work with.

There is a function in the SDK that can do some of this work for you (SCardUIDlgSelectCard).  It determines what cards are available and prompts the user to select the one they want to work with.  It does require working with an OPENCARDNAME_EX structure though, which is a bit tricky from PowerBuilder.  For a number of reasons, we found that method didn’t serve our needs.  As a result, this sample does all of the work without using that method.

The third step is to attempt to open a connection to any card(s) in the card reader(s) we’ve found.  We do that by first declaring the following local external function for the SCardConnect method in the SDK.

Function ulong SCardConnect  ( &

    Longptr hContext, &

    String szReader, &

    Long dwShareMode, &

    Long dwPreferredProtocols, &

    REF longptr phCard, &

    REF ulong pdwActiveProtocol &

    ) Library "winscard.dll" Alias For "SCardConnectW"

 

And then call it in PowerScript as follows:

 ulong    rc

rc = SCardConnect ( context, &

                             reader, &

                             SCARD_SHARE_SHARED, &

                             SCARD_PROTOCOL_Tx, &

                             card, &

                             protocol )

 

Where “reader” is the name of the smart card reader we obtained from the previous step.  The next two arguments are defined constants as follow (along with some other values you might use instead):

CONSTANT LONG SCARD_SHARE_EXCLUSIVE    = 1

CONSTANT LONG SCARD_SHARE_SHARED        = 2

CONSTANT LONG SCARD_SHARE_DIRECT        = 3

CONSTANT LONG SCARD_PROTOCOL_T0         = 1

CONSTANT LONG SCARD_PROTOCOL_T1         = 2

CONSTANT LONG SCARD_PROTOCOL_Tx         = 3

 

Once again, you’ll want to save “card” and “protocol” off as instance variables, because you’ll need to use them later.

 

protected longptr        card

protected ulong        protocol

 

The fourth step (assuming we found a card) is to get the card status to ensure that it’s ready for us to communicate with it.  We do that using the SCardStatus API function:

 Function ulong SCardStatus  ( &

    longptr hCard, &

    REF String szReaderName, &

    REF Long pcchReaderLen, &

    REF Long pdwState, &

    REF Long pdwProtocol, &

    REF byte pbAtr[], &

    REF Long pcbAtrLen &

    ) Library "winscard.dll" Alias For "SCardStatusW"

 

Which we then call via the following PowerScript:

integer    i

ulong    rc

long    pcchReaderLen = 32000

string    szReaderName = Space ( pcchReaderLen )

long    pdwState

long    pdwProtocol

byte     pbAtr[]

long    pcbAtrLen = 32

FOR i = 1 TO pcbAtrLen

    pbAtr[i] = Byte ( Space(1) ) // Prepad the buffer

NEXT

rc = SCardStatus( card, &

    szReaderName, &

    pcchReaderLen, &

    pdwState, &

    pdwProtocol, &

    pbAtr, &

    pcbAtrLen )

IF rc = SCARD_S_SUCCESS THEN

    CHOOSE CASE pdwState

        CASE SCARD_UNKNOWN

            status = 'Unknown'

        CASE SCARD_ABSENT

            status= 'Absent'

        CASE SCARD_PRESENT

            status= 'Present'

        CASE SCARD_SWALLOWED

            status= 'Swallowed'

        CASE SCARD_POWERED

            status= 'Powered'

        CASE SCARD_NEGOTIABLE

            status= 'Negotiable'

        CASE SCARD_SPECIFIC

            status= 'Specific'

        CASE ELSE

            status= 'Not Known'

    END CHOOSE

    atrbytes = pbAtr

    atr = ""

    FOR i = 1 TO pcbAtrLen

        atr += of_bytetohex ( pbAtr[i] )

    NEXT

END IF

 

Once again, you may want to save off the “status” and the “atr” (Answer to Reset) value.  For ease in using them from PowerBuilder, I’ve converted them to strings (the ATR being a hex encoded string).

The constants for the various possible state values are:

CONSTANT LONG SCARD_UNKNOWN               = 0

CONSTANT LONG SCARD_ABSENT                = 1

CONSTANT LONG SCARD_PRESENT               = 2

CONSTANT LONG SCARD_SWALLOWED             = 3

CONSTANT LONG SCARD_POWERED               = 4

CONSTANT LONG SCARD_NEGOTIABLE            = 5

CONSTANT LONG SCARD_SPECIFIC              = 6

 

 

And the of_bytetohex function was borrowed from PFC.

string    ls_hex=''

char    lch_hex[0 to 15] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', &

                            'A', 'B', 'C', 'D', 'E', 'F'}

Do

    ls_hex = lch_hex[mod (abyte, 16)] + ls_hex

    abyte /= 16

Loop Until abyte = 0

IF Len ( ls_hex ) = 1 THEN

    ls_hex = '0' + ls_hex

END IF

Return ls_hex

 

Now that we’re connected to the card, the fifth step is to connect to the specific applet on the smart card we want to work with.  For this, you’ll need to have information from the card manufacturer as to the applet IDs you need to communicate with and the specific APDU command syntax they require.  If you are working with US DoD Common Access Cards, a great deal of that information can be obtained from Common Access Card (CAC): Home, particularly Common Access Card (CAC) Security.  The “Test Materials” section contains links for instructions on obtaining test cards and the form to do so.  Also of particular interest on that page are DoD Implementation Guide for CAC Next Generation (NG) and Technical Bulletin: CAC Data Model Change in 144K Dual Interface 

Cards

 

We’ll need to declare the SCardTransmit API call to send commands to the applet:

Function ulong SCardTransmit( &

      longptr hCard, &

      Long pioSendPci, &

     byte pbSendBuffer[], &

      Long cbSendLength, &

      Long pioRecvPci, &

      REF byte pbRecvBuffer[], &

      REF long pcbRecvLength &

    ) Library "winscard.dll"

 

The API documentation indicates that the second argument is a SCARD_IO_REQUEST structure, but we’re going to use a pointer to that structure that we obtain from the SDK.  The API documentation indicates that the fifth argument is a similar structure, but we’re going to declare it as a long and pass 0 to indicate that we’re passing null for that value.

We create a wrapper function because we’re going to be sending a number of commands to the card.  The function takes a byte array as an argument and returns a string with status info.

 integer    i

ulong        rc

byte        sendBuffer[]

long        pioSendPci

byte         pbRecvBuffer[]

long         pcbRecvLength

long        cbSendLength

byte        getdata[5]

string        respSW1

string        respSW2

cbSendLength = UpperBound ( apdu )

FOR i = 1 TO cbSendLength

    sendBuffer[i] = of_hextobyte ( apdu[i] )

NEXT

pcbRecvLength = 2

FOR i = 1 TO pcbRecvLength

    pbRecvBuffer[i] = 0 ;

NEXT

pioSendPci = of_getpci()

rc = SCardTransmit ( card, &

      pioSendPci, &

    sendBuffer, &

      cbSendLength, &

      0, &

      pbRecvBuffer, &

     pcbRecvLength )

IF rc <> scard_s_success THEN return ""

respSW1 = of_bytetohex ( pbRecvBuffer[1] )

respSW2 = of_bytetohex ( pbRecvBuffer[2] )

//This means there is more data to come

IF respSW1 = "61" THEN

    getdata[1] = of_hextobyte ( "00" )

    getdata[2] = of_hextobyte ( "C0" )

    getdata[3] = of_hextobyte ( "00" )

    getdata[4] = of_hextobyte ( "00" )

    getdata[5] = pbRecvBuffer[2]

    cbSendLength = 5

    pcbRecvLength = pbRecvBuffer[2] + 2 // We need two extra bytes for the status bits

    FOR i = 1 TO pcbRecvLength

        pbRecvBuffer[i] = 0 ;

    NEXT

    rc = SCardTransmit ( card, &

        pioSendPci, &

        getdata, &

        cbSendLength, &

        0, &

        pbRecvBuffer, &

        pcbRecvLength )

    IF rc <> SCARD_S_SUCCESS THEN Return ""

    respSW1 = of_bytetohex ( pbRecvBuffer[pcbRecvLength - 1] )

    respSW2 = of_bytetohex ( pbRecvBuffer[pcbRecvLength] )

END IF

Return respSW1 + respSW2

 

The script uses another method borrowed from PFC (of_hextobyte)  to convert a hex value to a byte:

 char        lch_char[]

integer    li_byte

int li_dec[48 to 70], li_i, li_len

//Get the decimal code for hexadecimal value of '0' to 'F'

// Whose ASC Value are from 48 to 57 and 65 to 70

For li_i = 48 To 57

    li_dec[li_i] = li_i - 48

Next

For li_i = 65 To 70

    li_dec[li_i] = li_i - 55

Next

as_hex = upper(as_hex)

lch_char = as_hex

li_len = len (as_hex)

//Convert Hexadecimal data into decimal

For li_i = 1 to li_len

    //Make sure only 0's through f's are present

    Choose Case lch_char[li_i]

        Case '0' to '9', 'A' to 'F'

            li_byte = li_byte * 16 + li_dec[asc(lch_char[li_i])]

        Case Else

            Return li_byte

    End Choose

Next

Return li_byte

 

The of_getpci method is the one that gets a pointer to a LPCSARD_IO_REQUEST structure from the winscard DLL:

longptr dllhandle

ulong pci

dllhandle = LoadLibrary ( "WinSCard.dll" )

pci = GetProcAddress ( dllhandle, "g_rgSCardT0Pci" )

FreeLibrary(dllhandle)

return pci

 

That method in turn relies on external function declarations for three Windows API functions:

 Function longptr LoadLibrary ( &

    string fileName&

    ) Library "kernel32.dll" Alias For "LoadLibraryW"

SubRoutine FreeLibrary ( &

    longptr dllhandle &

    ) Library "kernel32.dll"

Function longptr GetProcAddress ( &

    longptr dllhandle, &

    string procName &

    ) Library "kernel32.dll" Alias For "GetProcAddress;Ansi"

 

The return value from the SCardTransmit is “9000” if it works.  If the first two characters are “61”, it means that the call returns more data than could be returned in the original request.  If that is the case, a second call is made to the function to retrieve the rest of the data. 

Ok, now we’re ready to select the applet.  This is the card specific process, so the following example will only work for US DoD CAC cards.  You will need to consult information from the manufacturer of the card for specific details on how to deal with it.

There are two versions of the US DoD CAC card, one in which you need to access an applet ID of 790101 (the first version).  If that fails, we attempt to connect to a container applet ID of 790100 and, if that works, an applet within it through it’s object ID of 0101. 

string    apdu[]

string    respSW

string    emptyarray[]

apdu[1] = "00"

apdu[2] = "A4" // Select

apdu[3] = "04" // By id

apdu[4] = "00" // first record

apdu[5] = "07" // Lenth of data

apdu[6] = "A0" // Applet ID to bit 11

apdu[7] = "00"

apdu[8] = "00"

apdu[9] = "00"

apdu[10] = "79"

apdu[11] = "01"

apdu[12] = "01"

respSW = of_sendapdu ( apdu )

// If we got OK, then it's an old card and we're already good

IF respSW =  SWRESPOK THEN

  version = '1'

ELSE

    //Otherwise, try using the new card method

    //Select the master applet

    apdu[12] = "00"

    respSW = of_sendapdu ( apdu )

    IF respSW <> SWRESPOK THEN

        //We don't know what it is

        Return FAILURE

    END IF

    //Reset the array

    apdu = emptyarray

    apdu[1] = "00" // CLA

    apdu[2] = "A4" // INS - select object

    apdu[3] = "02" // P1

    apdu[4] = "00" // P2 -

    apdu[5] = "02" // Lc - length of data

    apdu[6] = "01" // file id

    apdu[7] = "01"

    respSW = of_sendapdu ( apdu )

    IF respSW = SWRESPOK THEN

        version = '2'

    ELSE

        //We couldn't select the applet

        version = 'Unknown'

        Return FAILURE

    END IF

END IF

Return SUCCESS

 

Before we go into specific operations, let’s see what we need to do to clean up after ourselves when we’re done.  So, for our sixth step we need to disconnect from the card.  To do that, we declare a local external function for the SCardDisconnect method in the SDK:

Function ulong SCardDisconnect ( &

    longptr hCard, &

    long dwDisposition &

    ) Library "winscard.dll"

 

And call it with the following PowerScript:

ulong    rc

rc = scarddisconnect( card, SCARD_LEAVE_CARD )

SetNull ( card )

IF rc = SCARD_S_SUCCESS THEN

    Return SUCCESS

ELSE

    Return FAILURE

END IF

 

Where SCARD_LEAVE_CARD (and other values you might need to use) are defined as:

CONSTANT LONG SCARD_LEAVE_CARD            = 0

CONSTANT LONG SCARD_RESET_CARD            = 1

CONSTANT LONG SCARD_UNPOWER_CARD      = 2

 

Finally, in our seventh step, we need to release the context that we established in the first step.  We need the SCardReleaseContext SDK method for that:

Function ulong SCardReleaseContext( &

    ulong hContext &

    ) Library "winscard.dll"

 

And then use the following PowerScript to call it: 


ulong rc

rc = scardreleasecontext( context )

IF rc = SCARD_S_SUCCESS THEN

    Return SUCCESS

ELSE

    Return FAILURE

END IF

 

Validate the user’s pin

Now that we know how to connect to the card, we’ll look at some specific operations that we might want to perform using it.  One is to have the user validate their PIN so we know that the user is actually the holder of the card.  To do that, we need to send a specific APDU command to the card while we’re connected to it.  For US DoD CAC cards, the value is 00 20 00 followed by the length of the PIN buffer ( “08” ) and then the hex encoded PIN right padded to the length of the PIN buffer with FF values. 

In the following sample, w_pin is a window that is presented to the user into which they enter their PIN.  The return code from the APDU call, if the PIN is invalid, indicates the number of additional attempts the user is allowed to make before the card is automatically locked and the user will need to go to a RAPIDS site to have the card unlocked.

int        i

int        chances

int        pinlen

string apdu[]

string    ls_pin

string    respSW

Open ( w_pin )

ls_pin = message.StringParm

// User hit cancel

IF ls_pin = "" THEN Return NO_ACTION

pinlen = Len ( ls_pin )

apdu[1] = "00" // CLA

apdu[2] = "20"  // Verify PIN

apdu[3] = "00" // Not used

apdu[4] = "00" // Not used

apdu[5] = "08" // Indicate length of data, fixed at 8

// Add the PIN to the APDU

FOR i = 1 TO pinlen

    apdu[5 + i] = of_bytetohex ( Asc ( Mid ( ls_pin, i, 1 ) ) )

NEXT

// Pad out the rest of the APDU with 0xFF

FOR i = pinlen + 6 TO 13

    apdu[i] = "FF"

NEXT

respSW = of_sendapdu ( apdu )

CHOOSE CASE respSW

    CASE SWRESPOK

        // PIN Verified

        Return SUCCESS

    CASE PINLOCKED

        Return PIN_LOCKED

    CASE CACLOCKED

        Return CAC_LOCKED

    CASE INVALIDDATA

        Return INVALID_DATA

    CASE PINUNDEFINED

        Return PIN_UNDEFINED

    CASE ELSE

        IF Left ( respSW, 2 ) = PININVALID THEN

            chances = Integer ( Right ( respSW, 1 ) )

            Return -chances

        End If

END CHOOSE

 

The possible status codes returned from the APDU call are defined as: 

CONSTANT STRING PININVALID         = "63"

CONSTANT STRING PINLOCKED        = "63C0"

CONSTANT STRING CACLOCKED       = "6983"

CONSTANT STRING INVALIDDATA      = "6984"

CONSTANT STRING PINUNDEFINED   = "6A88"

 

Reading the certificate Subject Name 

The other thing we may want to do, once we’ve verified that the user knows the CAC PIN, is determine who the CAC card says the user is.  To do that, we’re going to read the certificate off the card and then determine what the CN value of the Subject Name is. The US DoD stores the user’s name and EDI/PI number in the CN value in the following format:  CN=LastName.FirstName.MiddleName.EDI/PI

The first step to access the certificate is to establish a cryptography context using the Windows API CryptAcquireContext method: 


Function ulong CryptAcquireContext ( &

    REF longptr hProv, &

    ulong pszContainer, &

    string pProviderName, &

    long dwProvType, &

    long dwFlags &

    ) Library "advapi32.dll" Alias For "CryptAcquireContextW"

 

And call it using this PowerScript: 


ulong    rc

rc = CryptAcquireContext ( &

    prov, &

    0, &

    providername, &

    PROV_RSA_FULL, &

    0 )

 

“prov” is a pointer to the cryptography context that is passed by reference returned to us as a result of the call, defined as: 


longptr        prov

 

We declared pszContainer as a ulong rather than a string (as in the SDK) because we’re passing 0 indicating a null value.  “providername” is also passed by reference as is defined as follows.  However, we don’t use the value. 


string        providername

 

And PROV_RSA_FULL is defined as: 


CONSTANT LONG PROV_RSA_FULL                = 1

 

The second step, once we have the context, we need to call CryptGetUserKey in the Windows API to get a handle to the certificate:

 Protected Function ulong CryptGetUserKey ( &

    longptr hProv, &

    long dwKeySpec, &

      REF ulong phUserKey &

    ) Library "advapi32.dll"

 

And call it as follows: 


ulong        rc

rc = CryptGetUserKey ( &

  prov, &

  AT_KEYEXCHANGE, &

  userkey )

 

Where AT_KEYEXCHANGE is defined as: 


LONG AT_KEYEXCHANGE   = 1

 

And “userkey” is passed by referenced and returned to us by the method, defined as: 


ulong        userkey

 

The third step is to call CryptGetKeyParam in the Windows API, declared as follows, to get the actual certificate: 


Function ulong CryptGetKeyParam ( &

    ulong hKey, &

    long dwParam, &

    REF byte pbData[], &

    REF long pdwDataLen, &

    long dwFlags &

    ) Library "advapi32.dll"

 

And call it as follows:

 
integer    i

ulong        rc

long        certlen

byte        temp[]

//Call it with 0 first to get the size

certlen = 0

rc =  CryptGetKeyParam ( &

        userkey, &

        KP_CERTIFICATE, &

        temp, &

        certlen, &

        0 )

//Now setup the buffer and call again for that size

FOR i = 1 TO certlen

    temp[i] = 0

NEXT

rc =  CryptGetKeyParam ( &

        userkey, &

        KP_CERTIFICATE, &

        temp, &

        certlen, &

        0 )

certbytes = temp

 

Where KP_CERTIFICATE is defined as: 


CONSTANT LONG KP_CERTIFICATE                    = 26

 

As indicated in the code comments, we call the function once with certlen set to 0 and the function returns the size of the certificate to use.  We then call it a second time with a byte buffer populated to that size to get the certificate data. 

The fourth step once we have the certificate data is to convert it to a certificate.  To do that, we first have to establish a certificate context using CertCreateCertificateContext in the Windows API: 


Protected Function longptr CertCreateCertificateContext ( &

    long dwCertEncodingType, &

    byte pbCertEncoded[], &

    long cbCertEncoded &

    ) Library "crypt32.dll"

 

And call it as follows: 


long    certlen

long    encoding = X509_ASN_ENCODING + PKCS_7_ASN_ENCODING

certlen = UpperBound ( certbytes )

certContextPointer = CertCreateCertificateContext ( &

    encoding, &

    certbytes, &

    certlen )

 

Where X509_ASN_ENCODING and PKCS_7_ASN_ENCODING are defined as: 


CONSTANT LONG PKCS_7_ASN_ENCODING       = 65536 // 0x00010000

CONSTANT LONG X509_ASN_ENCODING            = 1

 

And certContextPointer is defined as: 


longptr    certcontextpointer

 

The fifth step is to get the Subject Name off the certificate using the CertGetNameString method in the Windows API: 


Function ulong CertGetNameString ( &

    longptr pCertContext, &

    long dwType, &

    long dwFlags, &

    long pvTypePara, &

    REF string pszNameString, &

    REF long cchNameString &

    ) Library "crypt32.dll" Alias For "CertGetNameStringW"

 

And call it as follows: 


ulong        rc

long        subjectlen

string        ls_subject

subjectlen = 256

ls_subject = Space ( subjectlen )

rc = CertGetNameString ( &

    certContextPointer, &

    CERT_NAME_SIMPLE_DISPLAY_TYPE, &

    0, &

    0, &

    ls_subject, &

    subjectlen )

 

Where CERT_NAME_SIMPLE_DISPLAY_TYPE is defined as: 


CONSTANT LONG CERT_NAME_SIMPLE_DISPLAY_TYPE = 4

 

Now that we have the subject name, we need to release the certificate context.  We do that with the CertFreeCertificateContext Windows API function. 


Function ulong CertFreeCertificateContext (&

    longptr pCertContext &

    ) Library "crypt32.dll"

 

 

 

Which we call as follows:


ulong    rc

rc = CertFreeCertificateContext ( certcontextpointer )

 

After which we need to release the cryptography context as well using the CryptReleaseContext Windows API function: 


Function ulong CryptReleaseContext ( &

    longptr hProv, &

    long dwFlags &

    ) Library "advapi32.dll"

 

And call as follows: 


ulong rc

rc = CryptReleaseContext ( &

    prov, &

    0 )

 

Reading other Certificate Data 

Once we have a pointer to a CERT_CONTEXT structure, one member of which is a CERT_INFO structure, we can actually access the certificate.  The first thing we need to do is create a PowerBuilder structure we can copy the data into. 


global type cert_context from structure

  long dwcertencodingtype

  unsignedlong pbcertencoded

  long cbcertencoded

  unsignedlong pcertinfo

  unsignedlong hcertstore

end type

 

Then declare the following which we can use to perform the copy: 


Protected Subroutine CopyCERT_CONTEXT ( &

  ref CERT_CONTEXT dest, &

  ulong source, &

  long buffsize &

  ) Library "kernel32" Alias For "RtlMoveMemory"

 

And we call it as follows: 


cert_context lstr_cert_context

CONSTANT LONG CERT_CONTEXT_SIZE = 20

long buffersize =

CopyCERT_CONTEXT ( lstr_cert_context, certcontextpointer, CERT_CONTEXT_SIZE )

 

Now we’re going to declare a PowerBuilder structure to hold the certificate information: 


 

global type cert_info from structure

     long          dwversion

     crypt_integer_blob          serialnumber

     crypt_algorithm_identifier          signaturealgorithm

     cert_name_blob          issuer

     filetime          notbefore

     filetime          notafter

     cert_name_blob          subject

     cert_public_key_info          subjectpublickeyinfo

     crypt_bit_blob          issueruniqueid

     crypt_bit_blob          subjectuniqueid

     long          cextension

     unsignedlong          rgextension

end type

 

The crypt_integer_blob structure referenced above is defined as: 


global type crypt_integer_blob from structure

     long          cbdata

     long          pbdata

end type

 

The crypt_algorithm_identifier structure referenced above is defined as: 


global type crypt_algorithm_identifier from structure

     long          pszobjid

     crypt_objid_blob          parameters

end type

 

The crypt_objid_blob structure referenced here is defined as: 


global type crypt_objid_blob from structure

     long          cbdata

     long          pbdata

end type

 

The cert_name_blob structure referenced above is defined as: 


global type cert_name_blob from structure

     long          cbdata

     long          pbdata

end type

 

The filetime structure referenced above is defined as: 


global type filetime from structure

     long          lowdatetime

     long          highdatetime

end type

 

The cert_public_key_info structure referenced above is defined as:

 
global type cert_public_key_info from structure

     crypt_algorithm_identifier          algorithm

     crypt_bit_blob          publickey

end type

 

 

The crypt_algorithim_identifier structure is defined above.  The crypt_bit_blob structure is defined as:

 


global type crypt_bit_blob from structure

     long          cbdata

     long          pbdata

     long          cUnusedBits

end type

 

Then declare the following in order to copy the information from the cert_into portion of the cert_context into the PowerBuilder structure: 


Protected Subroutine CopyCERT_INFO ( &

  ref CERT_INFO dest, &

  ulong source, &

  long buffsize &

  ) Library "kernel32" Alias For "RtlMoveMemory"

 

And then call it as follows:

 


cert_info               lstr_cert_info

CONSTANT LONG CERT_INFO_SIZE                    = 112

long buffsize = CERT_INFO_SIZE

CopyCERT_INFO ( lstr_cert_info, lstr_cert_context.pcertinfo, buffsize )

 

Now let’s access some of the certification information.  We’re going to need the following function declared so we can convert the start and end dates of the certificate’s valid lifetime. 


Protected Function ulong FileTimeToSystemTime ( &

  filetime lpFileTime, &

  REF systemtime lpSystemTime &

  ) Library "kernel32.dll"

 

We’re going to need to define a PowerBuilder structure to pass for the systemtime. 

global type systemtime from structure

     uint          wYear

     uint          wMonth

     uint          wDayOfWeek

     uint          wDay

     uint          wHour

     uint          wMinute

     uint          wSecond

     uint          wMilliseconds

end type

 

And then call it as follows: 


systemtime          lstr_notbefore

systemtime          lstr_notafter

ulong                    rc

rc = FileTimeToSystemTime( lstr_cert_info.notbefore, lstr_notbefore )

rc = FileTimeToSystemTime( lstr_cert_info.notafter, lstr_notafter )

 

The following will convert the systemtime structures to a PowerBuilder datetime variables

 
datetime notbefore

datetime notafter

notbefore = DateTime ( Date ( lstr_notbefore.wyear, lstr_notbefore.wmonth, lstr_notbefore.wday ), &

  Time ( lstr_notbefore.whour, lstr_notbefore.wminute, lstr_notbefore.wsecond, lstr_notbefore.wMilliseconds ) )

notafter = DateTime ( Date ( lstr_notafter.wyear, lstr_notafter.wmonth, lstr_notafter.wday ), &

  Time ( lstr_notafter.whour, lstr_notafter.wminute, lstr_notafter.wsecond, lstr_notafter.wMilliseconds ) )

 

Finally we’re going to grab the public certificate both as a byte array and as a hex string.  We’re going to need one more function declaration: 


Protected Subroutine CopyCertEncoded ( &

  ref byte dest[], &

  ulong source, &

  long buffsize &

  ) Library "kernel32" Alias For "RtlMoveMemory"

 

And then call it as follows: 

byte                    encodedcert[]

string                    ls_cert

buffsize = lstr_cert_info.subjectpublickeyinfo.publickey.cbdata

FOR i = 1 TO buffsize

     encodedcert[i] = 0

NEXT

CopyCertEncoded ( encodedcert, lstr_cert_info.subjectpublickeyinfo.publickey.pbdata, buffsize )

FOR i = 1 TO buffsize

     ls_cert += of_bytetohex ( encodedcert[i] )

NEXT

 

Comments (3)

  1. Jason Schultz

Bruce,

Thanks so much for putting this together, very useful.

In my case, I was trying to use this against a more recent DoD CAC card (Gemalto TOP DL V2.1 144K FIPS). I noticed the PIN Verification wasn't working (returning a value of 6A 88 - referenced data not found - PIN_UNDEFINED). Within n_cst_winscard.of_verifypin(), I needed to change apdu[4] from '00' to '80'. Then it worked fine.

Another issue I'm running into is how to incorporate the sample code into an existing 64-bit application. I can only get the sample code to work as a 32-bit application, or run within the PB IDE. Any advice on how to make this functionality compatible with 64-bit? Is it a winscard.dll issue?

Thanks,
Jason

  Attachments
Your account does not have privileges to view attachments in the comment
 
  1. Bruce Armstrong

Would have to know about where it's failing. Most 64 bit Windows API calls are pretty much the same as the 32 bit version. The biggest issue is those functions that take a structure and also take a parameter in which you need to pass the size of the structure. The size will vary between the 32 and 64 bit versions, so you need to know what the updated size is when migrating to 64 bit. I scanned over the example and it doesn't appear that any of the functions I used there are of that type though.

  Attachments
Your account does not have privileges to view attachments in the comment
 
  1. Jason Schultz

When running a 64-bit .exe of the sample app, Im getting a return value of 6 (invalid handle error) when calling SCardConnect().
The root cause appears to be the of_establishcontext(). In both 32 and 64 bit mode, the return value is 0 (success). However, in 32-bit, the context value is 3439394816. In 64-bit, the context value is 0. This context value is too large to fit in a long data type, but should be ok for a ulong.

Within instance variables of n_cst_winscard, we have protected ulong context
Within local external functions, on the SCardConnect() function (pointing to winscard.dll / SCardConnectW), the context parameter is of type long. I tried making this ulong data type instead, but same results.

Not sure if I should be referencing anything as LongPTR of LongLong data types instead? I also tried that, but still getting a return of 6 on SCardConnect().
I appreciate any input into what I might be doing wrong.

Thanks,
Jason

  Attachments
Your account does not have privileges to view attachments in the comment
 
There are no comments posted here yet