证书签名请求中手动创建的签名与 openssl 请求生成的签名不匹配

Manually created signature in certificate signing request is not matching with the openssl req generated signature

$ openssl genrsa -out test.key 2048
$ openssl req -new -key test.key -subj "/CN=foo" -out foo.csr
$ openssl rsautl -encrypt -in hash_manual -inkey test.key -out manual_signature

你有两个问题:

  • 您需要使用 sign 而不是 encrypt。对于 RSA,encrypt 是使用 public 密钥加密,但 sign 是使用私钥加密
  • rsautl 的输出格式错误

第一个很容易修复,只需使用-sign

第二个有点烦人,它不仅仅是 sha256 输出被签名,它是一个 ASN.1 结构,看起来像这样:

    0:d=0  hl=2 l=  49 cons: SEQUENCE          
    2:d=1  hl=2 l=  13 cons:  SEQUENCE          
    4:d=2  hl=2 l=   9 prim:   OBJECT            :sha256
   15:d=2  hl=2 l=   0 prim:   NULL              
   17:d=1  hl=2 l=  32 prim:  OCTET STRING      
      0000 - dc 31 c9 99 51 ce 03 a2-aa 14 13 f1 c4 f6 3e ea   .1..Q.........>.
      0010 - 4f 87 a2 56 37 de 7f a7-c1 87 49 f0 43 c9 ba bb   O..V7.....I.C...

最后的 OCTET STRING 字段是原始 sha256 哈希值。

生成它的最简单方法是使用 openssl dgst 结合散列和签名:

# Hash and sign the certificationRequestInfo
$ openssl dgst -sha256 -sign test.key info.der > manual_signature

# Compare to extracted sig.raw (no output means no diff)
$ diff manual_signature  sig.raw

# Verify both the extracted sig.raw and the manual_signature using the public key
$ openssl rsautl -verify -pubin -inkey pub.pem -in sig.raw -asn1parse
    0:d=0  hl=2 l=  49 cons: SEQUENCE          
    2:d=1  hl=2 l=  13 cons:  SEQUENCE          
    4:d=2  hl=2 l=   9 prim:   OBJECT            :sha256
   15:d=2  hl=2 l=   0 prim:   NULL              
   17:d=1  hl=2 l=  32 prim:  OCTET STRING      
      0000 - dc 31 c9 99 51 ce 03 a2-aa 14 13 f1 c4 f6 3e ea   .1..Q.........>.
      0010 - 4f 87 a2 56 37 de 7f a7-c1 87 49 f0 43 c9 ba bb   O..V7.....I.C...

$ openssl rsautl -verify -pubin -inkey pub.pem -in manual_signature -asn1parse
    0:d=0  hl=2 l=  49 cons: SEQUENCE          
    2:d=1  hl=2 l=  13 cons:  SEQUENCE          
    4:d=2  hl=2 l=   9 prim:   OBJECT            :sha256
   15:d=2  hl=2 l=   0 prim:   NULL              
   17:d=1  hl=2 l=  32 prim:  OCTET STRING      
      0000 - dc 31 c9 99 51 ce 03 a2-aa 14 13 f1 c4 f6 3e ea   .1..Q.........>.
      0010 - 4f 87 a2 56 37 de 7f a7-c1 87 49 f0 43 c9 ba bb   O..V7.....I.C...