您好,是否有任何 native 函数(不安装其他 gem,或不从 shell 调用 openssl)来压缩字符串或加密字符串?
有点像 mysql 压缩。
"a very long and loose string".compress <br/>
output = "8d20\1l\201"
"8d20\1l\201".decompress<br/>
output = "a very long and loose string"?
同样要加密一些字符串?
最佳答案
来自 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"
关于ruby - 用于压缩/加密字符串的 native ruby 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4721423/