Module: S7::S7File

Defined in:
lib/s7/s7_file.rb

Overview

s7 オリジナルのファイル形式で機密情報の読み書きを表現する。

Constant Summary collapse

MAGIC =

マジック。

"s7 file version 0\n"

Class Method Summary collapse

Class Method Details

.read(path, master_key) ⇒ Object

path で指定したファイルを読み込み、master_key で指定したマスター キーを使用して復号する。



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/s7/s7_file.rb', line 32

def read(path, master_key)
  File.open(path, "rb") do |f|
    f.flock(File::LOCK_EX)
    magic = f.gets
    if magic != MAGIC
      raise InvalidPassphrase
    end
    cipher_type = f.gets.chomp
    cipher = Cipher.create_instance(cipher_type,
                                    :passphrase => master_key)
    return cipher.decrypt(f)
  end
end

.write(path, master_key, cipher_type, data) ⇒ Object

data で指定したバイト列を暗号化して書き込む。



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/s7/s7_file.rb', line 15

def write(path, master_key, cipher_type, data)
  cipher = Cipher.create_instance(cipher_type, :passphrase => master_key)
  FileUtils.touch(path)
  File.open(path, "r+b") do |f|
    f.flock(File::LOCK_EX)
    data = [MAGIC,
            cipher_type + "\n",
            cipher.encrypt(StringIO.new(data))].join
    f.write(data)
    f.truncate(f.pos)
  end
  FileUtils.chmod(0600, path)
end