Tuyenp
Tuyenp

Reputation: 81

Pkcs#11 exception: Token with serial and label was not found

I have tried to sign pdf document by using Pkcs11Interop and Pkcs11Interop.PDF extension by @jariq (here). Sometime (not for always), I received an exception with message: Token with serial and label was not found, and retry again, no exception thrown. Please show me why. My device is SafeNet Luna Network HSM, and here is my code:

        Using pkcs11 As Pkcs11RsaSignature = New Pkcs11RsaSignature(LIBRARY_PATH, partitionSerial, partitionAlias, pin, privateKeyAlias, Nothing, Net.Pkcs11Interop.PDF.HashAlgorithm.SHA256)
            Dim signingCertificate As Byte() = pkcs11.GetSigningCertificate()
            Dim otherCertificates As List(Of Byte()) = pkcs11.GetAllCertificates()
            Dim certPath As ICollection(Of Org.BouncyCastle.X509.X509Certificate) = CertUtils.BuildCertPath(signingCertificate, otherCertificates)

            Using reader As New PdfReader(tempFile)
                Using os As New FileStream(absolutePath, FileMode.Create)
                    Using stamper = PdfStamper.CreateSignature(reader, os, ControlChars.NullChar)
                        appearance = stamper.SignatureAppearance
                        appearance.SignDate = IIf(signDate = Nothing, DateTime.Now, signDate)
                        appearance.SetVisibleSignature(New iTextSharp.text.Rectangle(380, 60, 560, 120), reader.NumberOfPages, "sign_name")
                        appearance.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED
                        Dim bf As BaseFont = BaseFont.CreateFont("C:\Windows\Fonts\times.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED)
                        appearance.Layer2Font = New iTextSharp.text.Font(bf, 9, Font.NORMAL, iTextSharp.text.BaseColor.RED)
                        MakeSignature.SignDetached(appearance, pkcs11, certPath, Nothing, Nothing, Nothing, 0, CryptoStandard.CADES)
                    End Using
                End Using
            End Using
        End Using

Upvotes: 1

Views: 1197

Answers (1)

jariq
jariq

Reputation: 12108

Pkcs11Interop requests list of slots/tokens from unmanaged PKCS#11 library provided by your HSM vendor. It then searches through that list and looks for slot/token that matches provided serial/label criteria. If it says that such token was not found, then unmanaged PKCS#11 library most likely did not return such slot and you need to ask your HSM vendor for help.

If you want to check whether this is the case you need to log all PKCS#11 calls/responses of your PKCS#11 library. Exact steps needed to enable such logging should be present in the documentation provided by the PKCS#11 library vendor. Alternatively you can use PKCS11-LOGGER.

Upvotes: 3

Related Questions