【问题标题】:Validate signature from public key, automatically detect algorithm in BouncyCastle从公钥验证签名,在 BouncyCastle 中自动检测算法
【发布时间】:2019-03-18 14:41:28
【问题描述】:

我的问题是:如何编写我的签名验证函数以与公钥算法无关?

我正在使用 .Net 的 BouncyCastle 库 (v1.8.4)。我试图在事先不知道算法的情况下验证签名(但它的标识将嵌入公钥中)。

我需要验证字节流的签名,并且我有 PEM 格式的公钥:

-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE7t7Uo4NB7kjqPGMzdXbBI66gy8rz
oYvRatFPTGsdS9lCru6imfdMclcr/hCkxHgfgz0ewmKqEjWK8EjZczUCEA==
-----END PUBLIC KEY-----

我希望它能够通知 ASN.1 流中的算法,在此示例中解析如下:

$ openssl asn1parse -i -in pubkey.pem
    0:d=0  hl=2 l=  89 cons: SEQUENCE
    2:d=1  hl=2 l=  19 cons:  SEQUENCE
    4:d=2  hl=2 l=   7 prim:   OBJECT            :id-ecPublicKey
   13:d=2  hl=2 l=   8 prim:   OBJECT            :prime256v1
   23:d=1  hl=2 l=  66 prim:  BIT STRING

算法在这种情况下是 prime256v1(secp256k1 等),但我不会提前知道它是什么。目前,我的代码如下所示:

Private Function SignatureChecks(data() as Byte, pubkey as String, signature as String) As Boolean

    Dim keypars As Org.BouncyCastle.Crypto.AsymmetricKeyParameter 'impements ICipherParameters

    'Read and parse the PEM file into the proper object
    Dim pubkeybytes = Encoding.ASCII.GetBytes(pubkey)
    Using pubkeystream = New MemoryStream(pubkeybytes)
        Using reader = New StreamReader(pubkeystream)
            Dim pemrd = New PemReader(reader)
            'Now this is the decoded PEM for the public key
            keypars = pemrd.ReadObject()
        End Using
    End Using

    Dim signer As ISigner

    '*************************************************************
    'Currently this is hardwired: how can I make this intelligent?
    '*************************************************************
    signer = SignerUtilities.GetSigner("SHA-256withECDSA")

    'Init the signer with the public key
    signer.Init(False, keypars)
    'Appends the data to be verified in the SHA block buffer
    signer.BlockUpdate(data, 0, data.Length)

    'Get the bytes from the signature
    Dim sigbytes = Convert.FromBase64String(signature)

    Return signer.VerifySignature(sigbytes)

End Function

只要使用 secp256k1 算法生成签名,此代码就可以正常工作,但情况可能并非如此。我尝试从 AsymmetricKeyParameter 对象(实际上是一个 ECPublicKeyParameters)中提取信息,但它的公共成员很少。但是,相关信息确实显示在使用调试器的对象内部:诸如 publicKeyParamSet=1.2.840.10045.3.1.7、algorithm="EC" 等值。

提前致谢

【问题讨论】:

    标签: .net digital-signature bouncycastle public-key-encryption asn.1


    【解决方案1】:

    公钥中告知的prime256v1算法只是加密算法(应该是),而公钥中没有指定散列算法或签名。为了验证签名,必须使用其他方式在参与者之间商定哈希函数(在本例中为 SHA-256)。一个例子是 CMS 编码(以前的 PKCS#7),它是一种容器方法,可以嵌入检查签名有效性所需的所有信息。从公钥中获取加密算法不足以执行任务。

    【讨论】:

      猜你喜欢
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      • 2012-07-26
      • 1970-01-01
      相关资源
      最近更新 更多