【问题标题】:Ruby, how to convert a string to an RSA public keyRuby,如何将字符串转换为 RSA 公钥
【发布时间】:2018-06-11 10:53:27
【问题描述】:

我需要使用 RSA 加密来对消息进行编码。我将私钥和公钥存储在两个单独的文本文件中,但我只能对消息进行编码。我需要一种将字符串转换为 RSA 密钥的方法,以便解码消息。

到目前为止我的代码:

require 'openssl'
require 'base64'


if File.exist?("./pub_key.txt")

  #Keys are strings, I can encrypt but not decrypt a message
  pri = File.read("./pri_key.txt")
  pub = File.read("./pub_key.txt")

  puts pub

  string = 'Hello World!';

  rsa_public_key = OpenSSL::PKey::RSA.new(pub)
  encrypted_string = Base64.encode64(rsa_public_key.public_encrypt(string))

  puts encrypted_string 

  # This throws an error
  # Because 'pri' is a string, don't know how to cast it to the right type
  #my_string = pri.private_decrypt(Base64.decode64(encrypted_string))

  puts "The decoded message"
  #puts my_string


end

【问题讨论】:

    标签: ruby string encryption casting rsa


    【解决方案1】:

    我修复了代码

    原来我只需要这一行:

    rsa_private_key = OpenSSL::PKey::RSA.new(pri)
    

    完整的工作代码

    require 'openssl'
    require 'base64'
    
    
    if File.exist?("./pub_key.txt")
    
      #Keys are strings, I can encrypt but not decrypt a message
      pri = File.read("./pri_key.txt")
      pub = File.read("./pub_key.txt")
    
      puts pub
    
      string = 'Hello World!';
    
      rsa_public_key = OpenSSL::PKey::RSA.new(pub)
      rsa_private_key = OpenSSL::PKey::RSA.new(pri)
      encrypted_string = Base64.encode64(rsa_public_key.public_encrypt(string))
    
      puts encrypted_string 
    
      # This throws an error
      # Because 'pri' is a string, don't know how to cast it to the right type
      my_string = rsa_private_key .private_decrypt(Base64.decode64(encrypted_string))
    
      puts "The decoded message"
      puts my_string
    
    
    end
    

    感谢您的宝贵时间!橡皮鸭编程作品:)

    【讨论】:

      猜你喜欢
      • 2017-09-08
      • 1970-01-01
      • 2019-09-22
      • 2021-06-07
      • 2014-11-27
      • 2015-10-19
      • 2011-03-10
      • 1970-01-01
      • 2014-02-06
      相关资源
      最近更新 更多