Adj*_*jam 0 ruby encryption rsa public-key private-key
我已经成功创建了私钥和公钥,并对消息进行了编码,但是在解码消息时,我抛出了错误
到目前为止,我的代码是:
require 'openssl'
require 'base64'
key = OpenSSL::PKey::RSA.generate(2048)
pri_key = key
pub_key = key.public_key
string = 'Hello World!';
rsa_public_key = OpenSSL::PKey::RSA.new(pub_key)
encrypted_string = Base64.encode64(rsa_public_key.public_encrypt(string))
puts "Encrypted Message:"
puts encrypted_string
# This creates an error
my_string = pri_key.private_decrypt(encrypted_string)
puts "The decoded message"
puts my_string
Run Code Online (Sandbox Code Playgroud)
打印编码后的消息后抛出此错误
Example Decrypt.txt:25:in `private_decrypt': data greater than mod len (OpenSSL::PKey::RSAError)
from Example Decrypt.txt:25:in `<main>'
Run Code Online (Sandbox Code Playgroud)
您以64为基础对加密的字符串进行编码,但在解密之前不对其进行解码。由于基数为64的编码字符串长于加密字符串,且长于模数,因此会出现错误。
在加密之前尝试base 64解码:
my_string = pri_key.private_decrypt(Base64.decode64(encrypted_string))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
512 次 |
| 最近记录: |