Class: Saro::Dat::DatCrypto

Inherits:
Object
  • Object
show all
Defined in:
lib/saro/dat/crypto.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(algorithm, key_bytes, config = nil) ⇒ DatCrypto

Returns a new instance of DatCrypto.



32
33
34
35
36
# File 'lib/saro/dat/crypto.rb', line 32

def initialize(algorithm, key_bytes, config = nil)
  @config = config || Saro::Dat.get_crypto_config(algorithm)
  @algorithm = algorithm
  @key_bytes = key_bytes
end

Instance Attribute Details

#algorithmObject (readonly)

Returns the value of attribute algorithm.



30
31
32
# File 'lib/saro/dat/crypto.rb', line 30

def algorithm
  @algorithm
end

Class Method Details

.generate(algorithm) ⇒ Object



38
39
40
41
42
# File 'lib/saro/dat/crypto.rb', line 38

def self.generate(algorithm)
  config = Saro::Dat.get_crypto_config(algorithm)
  key_bytes = OpenSSL::Random.random_bytes(config[:length])
  new(algorithm, key_bytes, config)
end

.imports(algorithm, base64_str) ⇒ Object



44
45
46
47
# File 'lib/saro/dat/crypto.rb', line 44

def self.imports(algorithm, base64_str)
  key_bytes = Saro::Dat::Util.decode_base64_url(base64_str)
  new(algorithm, key_bytes)
end

Instance Method Details

#decrypt(data) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/saro/dat/crypto.rb', line 70

def decrypt(data)
  if data.is_a?(String) && data.encoding != Encoding::BINARY
    data = Saro::Dat::Util.decode_base64_url(data)
  end
  return "".b if data.nil? || data.empty?

  if data.length <= 12 + 16 # nonce(12) + tag(16)
    raise ArgumentError, "Invalid data length"
  end

  nonce = data[0, 12]
  tag = data[-16, 16]
  ciphertext = data[12...-16]

  cipher = OpenSSL::Cipher.new(@config[:name])
  cipher.decrypt
  cipher.key = @key_bytes
  cipher.iv_len = 12
  cipher.iv = nonce
  cipher.auth_tag = tag

  res = cipher.update(ciphertext) + cipher.final
  res.force_encoding('BINARY')
  res
end

#encrypt(data) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/saro/dat/crypto.rb', line 53

def encrypt(data)
  data = data.encode('utf-8') if data.is_a?(String) && data.encoding != Encoding::BINARY
  return "".b if data.nil? || data.empty?

  cipher = OpenSSL::Cipher.new(@config[:name])
  cipher.encrypt
  cipher.key = @key_bytes
  nonce = OpenSSL::Random.random_bytes(12)
  cipher.iv_len = 12
  cipher.iv = nonce
  
  ciphertext = cipher.update(data) + cipher.final
  tag = cipher.auth_tag

  nonce + ciphertext + tag
end

#exportsObject



49
50
51
# File 'lib/saro/dat/crypto.rb', line 49

def exports
  Saro::Dat::Util.encode_base64_url_str(@key_bytes)
end