验证非分离的PKCS签名

时间:2017-10-26 08:36:59

标签: c# .net cryptography

逗人

请帮助我理解非分离签名验证过程。 我使用了SignedCms.ComputeSignature和CheckSignature文档中的示例代码(稍加修改)。 这是

[TestMethod]
public void CheckSignaturePlain()
{
    var x509 = new X509Helper(LogManager.GetLogger("x509"));
    X509Certificate2 certificate = x509.GetCertificate("XML_SIGN_TEST_CERT");
    var str = "quick brown fox jumps over lazy dog";
    var data = Encoding.ASCII.GetBytes(str);
    detached = false; // tests are passed for detached signatures only
    using (var sha256 = new SHA256CryptoServiceProvider()) // One thing though, Microsoft recommends that you avoid using any managed classes.  You should change SHA256Managed to SHA256CryptoServiceProvider. https://blogs.msdn.microsoft.com/winsdk/2015/11/14/using-sha256-with-the-signedxml-class/
    {
        var hash = sha256.ComputeHash(data);
        var signature = Sign(hash, certificate);
        SignCheck(hash, signature);

        try
        {
            data = data.Skip(1).ToArray(); // lets change the data to get broken signature

            var hash2 = sha256.ComputeHash(data);
            SignCheck(hash2, signature);
            Assert.Fail("signature verification should fail");
        }
        catch (CryptographicException ce)
        {
            TestContext.WriteLine(ce.Message);
        }
    }
}

byte[] Sign(byte[] hash, X509Certificate2 cert)
{
    ContentInfo contentInfo = new ContentInfo(hash);
    SignedCms signedCms = new SignedCms(contentInfo, detached);
    CmsSigner cmsSigner = new CmsSigner(cert);
    cmsSigner.IncludeOption = X509IncludeOption.WholeChain;

    signedCms.ComputeSignature(cmsSigner);

    byte[] cmsMessage = signedCms.Encode();
    return cmsMessage;
}

bool detached;

void SignCheck(byte[] hash, byte[] signature)
{
    var contentInfo2 = new ContentInfo(hash);
    var signedCms = new SignedCms(contentInfo2, detached);

    signedCms.Decode(signature);

    signedCms.CheckSignature(true);
}

然而,从我的观点来看,它只适用于分离的签名。 如果设置了detached = false,则签名验证不会因更改的数据而失败。 这是因为签名的数据包含在签名对象中,SignedCms.CheckSignature忽略了根据更改的数据计算的哈希值。

是否可以使用非分离签名并获取signedCms.CheckSignature以考虑根据更改的数据计算的哈希值? 或者我应该从非分离签名中提取签名数据,计算哈希数据并手动比较它们?

我想使用非分离签名。签名中的签名数据(实际哈希)应该用作抽象层上的消息标识符,不知道如何为不同类型的对象计算哈希值。

1 个答案:

答案 0 :(得分:1)

在非分离模式下,内容位于有效负载内,因此在Decode期间,您提供的ContentInfo将被丢弃,而有效负载内的if (!this.Detached) { Oid contentType = PkcsUtils.GetContentType(m_safeCryptMsgHandle); byte[] content = PkcsUtils.GetContent(m_safeCryptMsgHandle); m_contentInfo = new ContentInfo(contentType, content); } 则会被使用。

data

(来自SignedCms.Decode on referencesource

在分离签名模式下,SignedCms数据代表您必须提供的某些数据的签名(和元数据)。使用标准的加密签名行为,它接受输入数据,散列它,并对散列执行私钥操作以生成签名。

在嵌入式(非分离)签名模式中,SignedCms数据是一个包含数据以及签名(和元数据)的blob。因此,以非分离模式发送CMS对象会替换发送原始数据(因为现在嵌入了原始数据)。

除非您要传输的内容实际上只是哈希值,否则您应该为SignedCms提供实际的var str = '+923451234567'; console.log(str.replace(str.substring(4,11), "*******"));值,因为它会将其自身哈希作为计算签名的一部分。

相关问题