rubyzip/test/encryption_test.rb

69 lines
1.8 KiB
Ruby
Raw Permalink Normal View History

# frozen_string_literal: true
require 'test_helper'
class EncryptionTest < MiniTest::Test
ENCRYPT_ZIP_TEST_FILE = 'test/data/zipWithEncryption.zip'
INPUT_FILE1 = 'test/data/file1.txt'
2021-06-27 22:56:39 +08:00
INPUT_FILE2 = 'test/data/file2.txt'
def setup
Zip.default_compression = ::Zlib::DEFAULT_COMPRESSION
end
def teardown
Zip.reset!
end
def test_encrypt
content = File.read(INPUT_FILE1)
test_filename = 'top_secret_file.txt'
password = 'swordfish'
encrypted_zip = Zip::OutputStream.write_buffer(
2021-06-09 01:09:22 +08:00
::StringIO.new,
encrypter: Zip::TraditionalEncrypter.new(password)
) do |out|
out.put_next_entry(test_filename)
out.write content
end
2021-06-18 21:34:41 +08:00
Zip::InputStream.open(
encrypted_zip, decrypter: Zip::TraditionalDecrypter.new(password)
) do |zis|
entry = zis.get_next_entry
assert_equal test_filename, entry.name
2021-06-27 22:56:39 +08:00
assert_equal 1_327, entry.size
assert_equal content, zis.read
end
error = assert_raises(Zip::DecompressionError) do
2021-06-18 21:34:41 +08:00
Zip::InputStream.open(
encrypted_zip,
decrypter: Zip::TraditionalDecrypter.new("#{password}wrong")
) do |zis|
zis.get_next_entry
assert_equal content, zis.read
end
end
assert_match(/Zlib error \('.+'\) while inflating\./, error.message)
end
def test_decrypt
2021-06-18 21:34:41 +08:00
Zip::InputStream.open(
ENCRYPT_ZIP_TEST_FILE,
decrypter: Zip::TraditionalDecrypter.new('password')
) do |zis|
entry = zis.get_next_entry
assert_equal 'file1.txt', entry.name
2021-06-27 22:56:39 +08:00
assert_equal 1_327, entry.size
assert_equal ::File.read(INPUT_FILE1), zis.read
2021-06-27 22:56:39 +08:00
entry = zis.get_next_entry
assert_equal 'file2.txt', entry.name
assert_equal 41_234, entry.size
assert_equal ::File.read(INPUT_FILE2), zis.read
end
end
end