如何在Ruby中使用PKI(公钥/私钥)加密? [英] How to use PKI (public/private key) encryption in Ruby?

查看:202
本文介绍了如何在Ruby中使用PKI(公钥/私钥)加密?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想加密一个字符串,以便最终用户可以验证它是否被我加密,但是它们不能自己加密。

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.

例如我有一个私钥'私人',一个公共密钥'public',一个消息'hello world',并且想要做一些类似的事情:

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


推荐答案

您正在寻找内置 Ruby OpenSSL包装器。该文档提供了如何执行此操作的示例。

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

注意:使用下面的 .sign 方法向您的数据签名私钥只生成数字签名,不会对您的数据进行加密。从您的问题,您不清楚您是要加密数据还是验证消息。如果要加密数据,您还必须使用 密码 类。您只需要一个数字签名来验证您的数据是否已被调整并已被您签名!

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!

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\..." 

现在,发送你的数据&签收到接收端。另外,您可以考虑使用 PKCS#7 作为标准的数据和签名方式。

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.

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

这篇关于如何在Ruby中使用PKI(公钥/私钥)加密?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆