Search code examples
c#x509certificatecode-signing

How to transfer the password (PIN) in the form at the signature by means of the certificate which is on a flash drive?


I need to sign a lot of documents and this code works. The problem is that every time I see the form for entering the password. How to transfer the password (PIN) in the form at the signature by means of the certificate which is on a flash drive?

INFO: can't export the private key from a flash drive (the key market is not exported)

static public byte[] SignToken(Byte[] tokenToSignBytes, X509Certificate2 signerCert)
{
    //  Place message in a ContentInfo object.
    //  This is required to build a SignedCms object.
    ContentInfo contentInfo = new ContentInfo(tokenToSignBytes);

    //  Instantiate SignedCms object with the ContentInfo above.
    //  Has default SubjectIdentifierType IssuerAndSerialNumber.
    //  Has default Detached property value false, so message is
    //  included in the encoded SignedCms.
    SignedCms signedCms = new SignedCms(contentInfo, true);

    //  Formulate a CmsSigner object for the signer.
    CmsSigner cmsSigner = new CmsSigner(signerCert);
    Console.WriteLine(cmsSigner);

    //  Sign the CMS/PKCS #7 message.
    Console.Write("Computing signature with signer subject name {0} ... ", signerCert.SubjectName.Name);
    signedCms.ComputeSignature(cmsSigner, false);
    //signedCms.ComputeSignature(cmsSigner, true); // it's not working
    Console.WriteLine("Done.");

    //  Encode the CMS/PKCS #7 message.
    return signedCms.Encode();
}

Solution

  • Instead of passing the PIN, I would refactor the code to define cmsSigner variable outside and only once. Then pass this parameter to SignToken method. Then you will be prompted for PIN only once when access the cmsSigner variable for the first time. Then you reuse the instance and no prompts should appear when you call SignToken method multiple times using same cmsSigner instance.