Sample code for 30+ languages & platforms
SQL Server

ScMinidriver - Change Smart Card PIN (or USB token PIN)

See more ScMinidriver Examples

Demonstrates how to change the PIN for a smart card or USB token.

Chilkat SQL Server Downloads

SQL Server
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    -- Important: Do not use nvarchar(max).  See the warning about using nvarchar(max).
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    -- This example requires the Chilkat API to have been previously unlocked.
    -- See Global Unlock Sample for sample code.

    DECLARE @scmd int
    EXEC @hr = sp_OACreate 'Chilkat.ScMinidriver', @scmd OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    -- Reader names (smart card readers or USB tokens) can be discovered
    -- via List Readers or Find Smart Cards
    DECLARE @readerName nvarchar(4000)
    SELECT @readerName = 'Alcor Micro USB Smart Card Reader 0'
    EXEC sp_OAMethod @scmd, 'AcquireContext', @success OUT, @readerName
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @scmd, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @scmd
        RETURN
      END

    -- If successful, the name of the currently inserted smart card is available:

    EXEC sp_OAGetProperty @scmd, 'CardName', @sTmp0 OUT
    PRINT 'Card name: ' + @sTmp0

    -- Change the "user" PIN.  (Typically, you'll always be using the "user" PIN.)
    DECLARE @currentPin nvarchar(4000)
    SELECT @currentPin = '0000'
    DECLARE @newPin nvarchar(4000)
    SELECT @newPin = '1234'
    DECLARE @retval int
    EXEC sp_OAMethod @scmd, 'PinChange', @retval OUT, 'user', @currentPin, @newPin
    IF @retval = -1
      BEGIN

        PRINT 'The PIN is already blocked.'
        EXEC @hr = sp_OADestroy @scmd
        RETURN
      END
    IF @retval = -2
      BEGIN

        PRINT 'The PinChange function failed for some unanticipated reason'
        EXEC sp_OAGetProperty @scmd, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @scmd
        RETURN
      END
    IF @retval = 0
      BEGIN

        PRINT 'PIN successfully changed.'
      END
    ELSE
      BEGIN

        PRINT 'Current PIN is incorrect.'

        PRINT 'Number of attempts remaining = ' + @retval
      END

    EXEC sp_OAMethod @scmd, 'DeleteContext', @success OUT

    EXEC @hr = sp_OADestroy @scmd


END
GO