6

Hi is there any native function (not install other gem, or not calling openssl from shell) to compress string or encrypt a string?

sort of like mysql compress.

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

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

and likewise to encrypt some string?

c2h2
  • 11,911
  • 13
  • 48
  • 60

2 Answers2

14

From 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

Encryption from 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"
Steve Wilhelm
  • 6,200
  • 2
  • 32
  • 36
  • According to the Zlib docs, `Zlib::Deflate.deflate(string[, level])` and `Zlib::Inflate.inflate(string[, level])` are "almost equivalent" to the above deflate/inflate methods. – Benjamin Sullivan Apr 24 '14 at 04:47
5

OpenSSL and Zlib. There’s an example of OpenSSL usage in this question.

Community
  • 1
  • 1
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
  • 2
    Not that you really imply any order of operation but one gets better compression rate if the text is first compressed and then encrypted. – Jonas Elfström Jan 18 '11 at 07:53
  • You should get virtually no compression if the file is first encrypted. Read this: https://blog.appcanary.com/2016/encrypt-or-compress.html – JLB Mar 10 '17 at 14:28