Class: Saro::Dat::DatCryptoKey

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) ⇒ DatCryptoKey

Returns a new instance of DatCryptoKey.



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, raw) ⇒ Object



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

def self.imports(algorithm, raw)
  new(algorithm, raw)
end

Instance Method Details

#decrypt(data) ⇒ Object



69
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
95
96
97
# File 'lib/saro/dat/crypto.rb', line 69

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

  begin
    res = cipher.update(ciphertext) + cipher.final
    res.force_encoding('BINARY')
    res
  rescue OpenSSL::Cipher::CipherError => e
    raise ArgumentError, "Decryption failed: #{e.message}"
  end
end

#encrypt(data) ⇒ Object



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

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



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

def exports
  @key_bytes
end