使用openssl命令行進行簽名和驗證


RSA簽名驗證的一般流程

發行者
  • 對被簽名文件(假設為App.txt)計算hash,一般用SHA256
  • 用RSA私鑰(假設為RSA.key)對hash值簽名,得到二進制簽名文件(假設為App.sig.bin),對其結果進行base64編碼,保存到簽名文件(假設為App.sig)
  • 將App.txt,公鑰文件(假設為App.pub),App.sig遞交給用戶
使用者
  • 對App.txt計算hash,需與簽名時使用的算法相同
  • 對App.sig進行base64解碼,得到二進制簽名(假設為App.sig.bin)
  • 使用hash,App.sig.bin,App.pub進行驗證

使用openssl命令行實現

發行者
  • 使用私鑰進行簽名
    openssl dgst -sha256 -sign RSA.key -out App.sig.bin App.txt
  • 對簽名文件進行base64編碼,便於查看對比和分發
    openssl base64 -in App.sig.bin -out App.sig
使用者
  • 對簽名文件進行base64解碼
    cat App.sig | base64 -d > App.sig.bin
  • 校驗
    openssl dgst -sha256 -verify App.pub -signature App.sig.bin App.txt
  • 校驗成功會返回“Verified OK”

注意事項

  • 如果公鑰為RSA PKCS#1格式,需要轉換為RSA PKCS#8格式
    openssl rsa -RSAPublicKey_in -in App.pub -pubout > App.pub8
  • PKCS#1格式的公鑰以-----BEGIN RSA PUBLIC KEY-----開頭
  • PKCS#8格式的公鑰以-----BEGIN PUBLIC KEY-----開頭

其他

  • 公鑰也可以保存在x509證書中(假設為RSA.pem),從x509證書提取公鑰使用如下命令:
    openssl x509 -inform PEM -in RSA.pem -outform PEM -pubkey -out RSA.pub8
  • PKCS#8格式公鑰轉 PKCS#1格式
    openssl rsa -in RSA.pub8 -pubin -RSAPublicKey_out -out RSA.pub1
  • 另一種使用x509證書簽名和驗證的方法
    使用私鑰和證書進行簽名,生成的簽名文件為PKCS#7格式。
    openssl smime -sign -binary -in App.txt -signer RSA.pem -inkey RSA.key -outform PEM -out App.sig7
    使用證書進行簽名驗證,如果是windows下將/dev/null換成nul即可。
    openssl smime -verify -binary -inform PEM -in App.sig7 -content App.txt -certfile RSA.pem -nointern -noverify > /dev/null


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM