2011-01-18 2 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

OpenSSLZlib. this 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에서 당신은 정말 작업의 순서를 의미하지 않는 것이하지만 텍스트가 먼저 압축 한 후 암호화 된 경우 하나의 더 나은 압축률을 가져옵니다. –

+0

파일을 처음 암호화 할 경우 압축을 거의받지 않아야합니다. 읽기 : https://blog.appcanary.com/2016/encrypt-or-compress.html – JLB

관련 문제