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?

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

1 Comment

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.
5

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

2 Comments

Not that you really imply any order of operation but one gets better compression rate if the text is first compressed and then encrypted.
You should get virtually no compression if the file is first encrypted. Read this: blog.appcanary.com/2016/encrypt-or-compress.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.