OpenSSL新手自学:如何生成RSA私钥并用于数字签名

参考: https://paulyang.cn/2016/11/28/rsa-padding.html 作者: 杨洋
https://infohunter.github.io/2016/11/28/rsa-padding.html

openssl 更新工具包, 使用pkeyutl取代rsautl之后才开始支持使用PSS padding scheme进行数字签名校验。(如果不指定 rsa_padding_mode 选项,openssl 默认仍使用最早的 PKCS1_v1.5 填充方案)

# 创建一个RSA密钥对
openssl genpkey -algorithm RSA -out rsakeypair.pem
# 从密钥对中拆分出公钥
openssl rsa -in rsakeypair.pem -pubout -out pubkey.pem

# 随便写一个文件用于测试数字签名
echo "Hello world!" > 文件名.txt


######################################################
# 方法一: 直接使用openssl dgst -sign和openssl dgst -verify完成数字签名
# 使用RSA私钥进行签名, 其中: 选项-sigopt rsa_padding_mode:pss指定padding scheme
openssl dgst -sha256 -sign rsakeypair.pem -sigopt rsa_padding_mode:pss -out sig.bin 文件名.txt

# 使用RSA公钥校验刚才的签名
openssl dgst -sha256 -verify pubkey.pem -sigopt rsa_padding_mode:pss -signature sig.bin 文件名.txt

屏幕输出 Verified OK 代表数字签名校验成功


################################################
# 方法2: 先使用 openssl dgst -binary 输出哈希校验和, 再使用 pkeyutl 进行数字签名和校验
openssl dgst -sha256 -binary -out sha256sum.bin 文件名.txt
openssl pkeyutl \
        -inkey rsakeypair.pem -pkeyopt rsa_padding_mode:pss -pkeyopt digest:sha256 \
        -sign -in sha256sum.bin -out sig2.bin

openssl pkeyutl \
        -pkeyopt rsa_padding_mode:pss -pkeyopt digest:sha256 \
        -pubin -inkey pubkey.pem \
        -verify -in sha256sum.bin -sigfile sig2.bin
屏幕输出 Signature Verified Successfully 代表数字签名校验成功
# pkeyutl的具体用法
# 我查询了一下Unix manual page
man pkeyutl

RSA ALGORITHM
       The RSA algorithm supports encrypt, decrypt, sign, verify and
       verifyrecover operations in general. Some padding modes only support
       some of these operations however.

       rsa_padding_mode:mode
           This sets the RSA padding mode. Acceptable values for mode are
           pkcs1 for PKCS#1 padding, sslv23 for SSLv23 padding, none for no
           padding, oaep for OAEP mode, x931 for X9.31 mode and pss for PSS.

           In PKCS#1 padding if the message digest is not set then the
           supplied data is signed or verified directly instead of using a
           DigestInfo structure. If a digest is set then the a DigestInfo
           structure is used and its the length must correspond to the digest
           type.

           For oeap mode only encryption and decryption is supported.

           For x931 if the digest type is set it is used to format the block
           data otherwise the first byte is used to specify the X9.31 digest
           ID. Sign, verify and verifyrecover are can be performed in this
           mode.

           For pss mode only sign and verify are supported and the digest type
           must be specified.


参考博客文章:
密码学原语(Cryptographic Primitive)和密码体制(Cryptographic Scheme)
https://www.paulyang.cn/2016/11/28/rsa-padding.html
作者:Paul Yang

更正原文一处错误: 应该使用RSA公钥加密, 私钥解密. 作者写反了.


你可能感兴趣的:(OpenSSL新手自学:如何生成RSA私钥并用于数字签名)