How to use PKI (public/private key) encryption in Ruby? [duplicate]

时间秒杀一切 提交于 2019-12-08 07:55:07

问题


I want to encrypt a string such that the end user can verify it was encrypted by me, but such that they can't encrypt it themselves.

For example, I have a private key 'private', a public key 'public', a message 'hello world' and want to do something like:

private_key = 'private'
public_key = 'public'
message = 'hello world'

encrypted_value = Crypto.encrypt(message, private_key)
# encrypted_value is now 'd92a01df241a3'

is_verified = Crypto.verify(message, public_key)
# given just the public key and the message, is_verified will 
# be able to tell whether it's accurate

# note that the encrypted_value cannot be generated by just the public_key
# but it can be verified by the public_key

回答1:


You are looking for built-in Ruby OpenSSL wrapper. The documentation provides examples of how to do it.

NOTE: Using .sign method below to sign your data with a private key only generates a digital signature, it does not encrypt your data. From your question, it is not clear if you want to encrypt your data or just validate the message. If you want to encrypt the data, you will also have to use Cipher class. You need only a digital signature to verify that your data has not been tempered with and been signed by you!

Sign your message

require 'openssl'

# Load PRIVATE key
private_key = OpenSSL::PKey::RSA.new(File.read('private_key.pem'))

# Sign your data
signature = private_key.sign(OpenSSL::Digest::SHA256.new, message)

# Our message signature that ensures that our data is signed by our private key
puts signature    # => "\x04\xEC\xCC?\xDE\x8F\x91>G\xC2*M\xA7j\xA5\x16\..." 

Now, send your data & signature to the receiving end. Also, you may consider using PKCS#7 as a standard way to pack your data and signature.

Verify your message & signature

require 'openssl'

# Load PUBLIC key
public_key = OpenSSL::PKey::RSA.new(File.read('public_key.pem'))

# We have received the following data
message = "Hello World!"
signature = "\x04\xEC\xCC?\xDE\x8F\x91>G\..."    # Long signature

# Verify the message & its signature
if public_key.verify(OpenSSL::Digest::SHA256.new, signature, message)
    "VALID: Signed by pair private key"
else
    "NOT VALID: Data tampered or private-public key mismatch!"
end


来源:https://stackoverflow.com/questions/36819802/how-to-use-pki-public-private-key-encryption-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!