为什么我不能用PKCS#11验证签名?

时间:2018-03-08 15:08:48

标签: c# .net-core pkcs#11 pkcs#7 softhsm

考虑一下,我创建了PKCS#7消息:

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);

现在,我想签名。以下方案有效(使用BounceCastlePKCS11.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

但是当我使用CKM_RSA_PKCS并手动计算HASH时,出了点问题:

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

我缺少什么?为什么手动计算的哈希无效?

1 个答案:

答案 0 :(得分:0)

事实证明,哈希需要用 DigestInfo 结构进行包装。最简单的方法是添加前缀:(前缀仅对SHA-1哈希有效):

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
...

在RF3447C中找到:https://www.ietf.org/rfc/rfc3447.txt

如何通过自我创建DigestInfoC# - How to calculate ASN.1 DER encoding of a particular hash algorithm?