|
3 | 3 | require_relative "ooxml_crypt/version"
|
4 | 4 | require_relative "ooxml_crypt/ooxml_crypt"
|
5 | 5 |
|
| 6 | +require "tempfile" |
| 7 | + |
6 | 8 | module OoxmlCrypt
|
| 9 | + class Error < StandardError; end |
| 10 | + class FileNotFound < Error; end |
| 11 | + class EmptyPassword < Error; end |
| 12 | + |
| 13 | + ERRORS = { # should be kept in sync with msoc.h |
| 14 | + 1 => "not supported format", |
| 15 | + 2 => "already encrypted", |
| 16 | + 3 => "already decrypted", |
| 17 | + 4 => "bad password", |
| 18 | + 5 => "bad parameter", |
| 19 | + 6 => "small max size", |
| 20 | + 7 => "no memory", |
| 21 | + 8 => "internal exception", |
| 22 | + 9 => "too large file", |
| 23 | + 10 => "inFile is empty", |
| 24 | + 11 => "outFile is empty", |
| 25 | + 12 => "password is empty", |
| 26 | + } |
| 27 | + |
| 28 | + def self.encrypt_file(input, password, output) |
| 29 | + raise EmptyPassword if password.nil? || password.empty? |
| 30 | + raise FileNotFound, input unless File.exist?(input) |
| 31 | + |
| 32 | + result = OoxmlCryptNative.encrypt_file(input, password, output) |
| 33 | + raise Error, ERRORS[-result] if result != 0 |
| 34 | + end |
| 35 | + |
| 36 | + def self.decrypt_file(input, password, output) |
| 37 | + raise EmptyPassword if password.nil? || password.empty? |
| 38 | + raise FileNotFound, input unless File.exist?(input) |
| 39 | + |
| 40 | + result = OoxmlCryptNative.decrypt_file(input, password, output) |
| 41 | + raise Error, ERRORS[-result] if result != 0 |
| 42 | + end |
| 43 | + |
| 44 | + def self.encrypt(data, password) |
| 45 | + with_temp_files(data) do |input, output| |
| 46 | + encrypt_file(input, password, output) |
| 47 | + end |
| 48 | + end |
| 49 | + |
| 50 | + def self.decrypt(data, password) |
| 51 | + with_temp_files(data) do |input, output| |
| 52 | + decrypt_file(input, password, output) |
| 53 | + end |
| 54 | + end |
| 55 | + |
| 56 | + private |
| 57 | + |
| 58 | + def self.with_temp_files(data) |
| 59 | + input = Tempfile.new("ooxml_crypt_input", binmode: true) |
| 60 | + input.write(data) |
| 61 | + input.close |
| 62 | + |
| 63 | + output = Tempfile.new("ooxml_crypt_output", binmode: true) |
| 64 | + output.close |
| 65 | + |
| 66 | + yield input.path, output.path |
| 67 | + |
| 68 | + result = File.binread(output.path) |
| 69 | + |
| 70 | + input.unlink |
| 71 | + output.unlink |
| 72 | + |
| 73 | + result |
| 74 | + end |
7 | 75 | end
|
0 commit comments