【问题标题】:How to use PKI (public/private key) encryption in Ruby? [duplicate]如何在 Ruby 中使用 PKI(公钥/私钥)加密? [复制]
【发布时间】:2016-08-17 14:49:58
【问题描述】:

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

例如,我有一个私钥“private”,一个公钥“public”,一条消息“hello world”,并且想要执行以下操作:

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

【问题讨论】:

  • 你的意思可能是is_verified = Crypto.verify(encrypted_value, public_key)

标签: ruby ssl encryption cryptography pki


【解决方案1】:

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

注意:使用下面的.sign 方法使用私钥对您的数据进行签名只会生成数字签名,它不会加密您的数据。从您的问题来看,尚不清楚您是要加密数据还是仅验证消息。如果要加密数据,还必须使用Cipher 类。您只需要一个数字签名来验证您的数据没有被您篡改和签名!

签署您的信息

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 作为打包数据和签名的标准方式。

验证您的消息和签名

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

【讨论】:

  • 你能举个例子吗?
猜你喜欢
  • 1970-01-01
  • 2012-04-11
  • 2015-07-29
  • 1970-01-01
  • 2018-02-27
  • 2013-05-07
  • 1970-01-01
  • 2014-03-09
  • 1970-01-01
相关资源
最近更新 更多