Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

native ruby methods for compressing/encrypt strings?

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?

like image 946
c2h2 Avatar asked Jan 18 '11 07:01

c2h2


1 Answers

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"
like image 170
Steve Wilhelm Avatar answered Sep 21 '22 14:09

Steve Wilhelm