ruby sha1withrsa

原创文章,转载请注明来源并保留原文链接

Step1: Generate private key using openssl

openssl genrsa -out rsa_pri.pem 1024

Step2: Generate public key using private.pem

openssl rsa -in rsa_pri.pem -out rsa_pub.pem -outform PEM -pubout
require "openssl"

pri = OpenSSL::PKey::RSA.new( File.read("rsa_pri.pem") )
sign = pri.sign( "sha1", "zires".force_encoding("utf-8") )

# if you want to send with hex string (high nibble first)
hex_sign = sign.unpack('H*').first

Verify it!

require "openssl"

pub = OpenSSL::PKey::RSA.new( File.read("rsa_pub.pem") )
pub.verify( "sha1", sign, "zires".force_encoding("utf-8") )
# or
pub.verify( "sha1", [hex_sign].pack("H*"), "zires".force_encoding("utf-8") )

Note: if you get public key (der format) form java like this:

308189028181009EEF0CDA83B2FF51C83EC2374BD7C0B6412AF6165471BDA22AEB99295D4549823968A4F3C31EF
1A9EBBF8B572360B53456E793A0B5A3A70CD6491EA844125D0DC349D1CE38F9A84EF1CDC0647E0B61491EEB8B47
C60FADA22BA22F03A50CC9977A9576AD26D1799F9436E819DF828A36FACFEA15AD6B59F4A2ACB2223682584B020
3010001

You need to pack it first!

File.open("rsa_pub.der", "w") {|f| f << [ File.read("rsa_pub.key") ].pack("H*") }

Thank you for this article [ https://wido.me/sunteya/java-and-ruby-use-sign-or-verify-data-by-rsa ], it helps me a lot!!

One thought on “ruby sha1withrsa

Leave a Reply

Your email address will not be published. Required fields are marked *