Ruby RSA 如何分段加密

zhangtenghai · 2016年02月16日 · 最后由 llwang 回复于 2016年09月27日 · 3688 次阅读

创建的 key 长度为 1024 用公钥加密比较长的字符串时会异常。 如何对长文本进行分段加密?

message = "long long text"
pkey = OpenSSL::PKey::RSA.new 1024
pkey.public_encrypt(message)

时隔多日回来追加答案

  MAX_ENCRYPT_LENGTH = 117
  MAX_DECRYPT_LENGTH = 128

#分段加密
  def encrypt_msg(key, message)
    bytes_array = message.unpack("C*")
    input_length = bytes_array.length

    encryt_str, offset, i = "", 0, 0
    begin
      encryt_bytes = bytes_array[offset, MAX_ENCRYPT_LENGTH]
      encryt_str << key.public_encrypt(encryt_bytes.pack("C*")) #加密
      offset = (i += 1) * MAX_ENCRYPT_LENGTH
    end while input_length - offset > 0

    Base64::strict_encode64(encryt_str)
  end

  #分段解密
  def decrypt_msg(key, message)
    bytes_array = Base64::decode64 message
    input_length = bytes_array.length

    decryt_str, offset, i = "", 0, 0
    begin
      decryt_bytes = bytes_array[offset, MAX_DECRYPT_LENGTH]
      decryt_str << key.private_decrypt(decryt_bytes) #解密
      offset = (i += 1) * MAX_DECRYPT_LENGTH
    end while input_length - offset > 0

    decryt_str
  end
共收到 3 条回复

An RSA key can only encrypt data of a certain size, related to the key size. What you want to do is not what you are doing. RSA is rarely used to encrypt data directly. Instead, a symmetric key (AES, 3DES, or other secure algorithm) is used to encrypt the data using a randomly generated key, and then that key is encrypted with RSA.

From https://groups.google.com/forum/#! topic/rubyonrails-talk/K8nzLZhOOMo

你这个很有用,我找到了类似的.

#!/usr/bin/env ruby

require 'openssl'

key = "1234567890123456"
alg = "AES-128-CBC"
iv = "6543210987654321"

aes = OpenSSL::Cipher::Cipher.new(alg)
aes.encrypt
aes.key = key
aes.iv = iv

File.open("foo.enc",'w') do |enc|

  File.open("foo") do |f|
    loop do
      r = f.read(4096)
      break unless r
      cipher = aes.update(r)
      enc << cipher
    end
  end

  enc << aes.final
end

key.private_decrypt(decryt_bytes) 的参数是要求的 string 类型,但是 decryt_bytes 是 byte 类型的,这个解密方法我在使用中报错啊

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册