2011-01-18 26 views
6

こんにちは、任意のネイティブ関数(他の宝石をインストールしないで、またはシェルからopensslを呼び出さない)文字列を圧縮するか、文字列を暗号化するには?文字列を圧縮/暗号化するためのネイティブルビメソッド?

mysqlのような種類の圧縮。いくつかの文字列を暗号化する

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

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

と同様に?

答えて

14

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" 
+0

Zlibドキュメントによると、 'Zlib :: Deflate.deflate(string [、level])'と 'Zlib :: Inflate .inflate(string [、level]) 'は、上記のdeflate/inflateメソッドと「ほぼ同等」です。 –

5

OpenSSLおよびZlibthis questionにOpenSSLの使用例があります。

+2

から暗号化

# 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://ruby-doc.org/stdlib/libdoc/zlib/rdoc/classes/Zlib.htmlからは、あなたが本当に任意の動作順序を示すものではありませいることが、テキストが最初に圧縮され、暗号化されている場合は、1つは、より高い圧縮率を取得します。 –

+0

ファイルが最初に暗号化されている場合は、ほとんど圧縮されません。これを読む:https://blog.appcanary.com/2016/encrypt-or-compress.html – JLB

関連する問題