压缩/加密字符串的本地 Ruby 方法?

6

你好,有没有本地函数(不是安装其他gem,也不是从shell调用openssl)来压缩字符串或加密字符串?类似于mysql的压缩。

"a very long and loose string".compress
输出 = "8d20\1l\201"

"8d20\1l\201".decompress
输出 = "a very long and loose string"?

同样地,要加密一些字符串吗?

2个回答

14

来源于http://ruby-doc.org/stdlib/libdoc/zlib/rdoc/classes/Zlib.html

  # aka compress
  def deflate(string, level)
    z = Zlib::Deflate.new(level)
    dst = z.deflate(string, Zlib::FINISH)
    z.close
    dst
  end

  # aka decompress
  def inflate(string)
    zstream = Zlib::Inflate.new
    buf = zstream.inflate(string)
    zstream.finish
    zstream.close
    buf
  end

来自http://snippets.dzone.com/posts/show/991的加密内容

require 'openssl'
require 'digest/sha1'
c = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
c.encrypt
# your pass is what is used to encrypt/decrypt
c.key = key = Digest::SHA1.hexdigest("yourpass")
c.iv = iv = c.random_iv
e = c.update("crypt this")
e << c.final
puts "encrypted: #{e}\n"
c = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
c.decrypt
c.key = key
c.iv = iv
d = c.update(e)
d << c.final
puts "decrypted: #{d}\n"

根据Zlib文档,Zlib::Deflate.deflate(string[, level])Zlib::Inflate.inflate(string[, level])与上述的deflate/inflate方法“几乎等效”。 - Benjamin Sullivan

5

2
并不是说你真的需要按照某种操作顺序,但如果先压缩文本再加密,可以获得更好的压缩率。 - Jonas Elfström
如果文件首先进行加密,则几乎不会出现压缩。请阅读此文:https://blog.appcanary.com/2016/encrypt-or-compress.html - JLB

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接