Search code examples
c#.net-corepkcs#11pkcs#7softhsm

Why can't I verify signature with PKCS#11?


Consider, I have created PKCS#7 message:

ContentInfo contentInfo = new ContentInfo(someByteArrayToSign);
SignedCms signedCms = new SignedCms(contentInfo);

var certificateFromFile = new X509Certificate2("myCert.pfx");

var signer = new CmsSigner(certificateFromFile);
signer.DigestAlgorithm = new Oid("1.3.14.3.2.26");
signedCms.ComputeSignature(signer);

var myCmsMessage = signedCms.Encode();
SendBytesOverNetwork(myCmsMessage);

Now, I'd like to very signature. The following scenario works (using BounceCastle and PKCS11.Interop):

var signedPayloadCms = new CmsSignedData(GetBytesFromNetwork());

var data = (byte[])signedPayloadCms.SignedContent.GetContent();
byte[] signature = null;

foreach (SignerInformation signer in signedPayloadCms.GetSignerInfos().GetSigners())
{
    if (signature != null)
    {
        throw new NotSupportedException("Multiple signature");
    }

    signature = signer.GetSignature();
}

var algCkm = CKM.CKM_SHA1_RSA_PKCS;
var mechanism = new Mechanism(algCkm);
Session.Verify(mechanism, somePublicKey.Handle, data, signature, out var isValid)
//isValid  == true

But when I use CKM_RSA_PKCS and manually calculate HASH, something is wrong:

var algHash = CKM.CKM_SHA_1;
var dataHash = Session.Digest(new Mechanism(algHash), data);

var algCkm = CKM.CKM_RSA_PKCS;
var mechanism = new Mechanism(algCkm);
Session.Verify(mechanism, somePublicKey.Handle, dataHash, signature, out var isValid)
//isValid  == false

What I am missing? Why manually calculated hash is not valid?


Solution

  • It turned out, that hash needs to be wraped with DigestInfo structure. The simplest ways to do is to add prefix: (prefix valid only for SHA-1 hashes):

    var dataHash = Session.Digest(new Mechanism(algHash), data);
    dataHash = HexToByteArray("30 21 30 09 06 05 2B 0E 03 02 1A 05 00 04 14")
                 .Concat(dataHash).ToArray();
    
     var algCkm = CKM.CKM_RSA_PKCS
    ...
    

    Found in RF3447C: https://www.ietf.org/rfc/rfc3447.txt

    How to create DigestInfo by self: C# - How to calculate ASN.1 DER encoding of a particular hash algorithm?