Class: Encrypth::Cipher

Inherits:
Object
  • Object
show all
Defined in:
lib/encrypth/cipher.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Cipher

Returns a new instance of Cipher.



7
8
9
10
# File 'lib/encrypth/cipher.rb', line 7

def initialize(key)
  @key = key
  validate_key!
end

Class Method Details

.from_password(password, salt = nil) ⇒ Object

Создает ключ из пароля (с солью)



44
45
46
47
48
# File 'lib/encrypth/cipher.rb', line 44

def self.from_password(password, salt = nil)
  salt ||= SecureRandom.random_bytes(16)
  key = OpenSSL::PKCS5.pbkdf2_hmac(password, salt, 20000, 32, "SHA256")
  { key: key, salt: salt }
end

.generate_keyObject

Генерирует случайный ключ (32 байта)



39
40
41
# File 'lib/encrypth/cipher.rb', line 39

def self.generate_key
  SecureRandom.random_bytes(32)
end

Instance Method Details

#decrypt(string) ⇒ Object

Дешифрует данные из строки, созданной методом encrypt



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/encrypth/cipher.rb', line 26

def decrypt(string)
  iv, encrypted, auth_tag = unpack(string)
  
  cipher = OpenSSL::Cipher.new("aes-256-gcm")
  cipher.decrypt
  cipher.key = @key
  cipher.iv = iv
  cipher.auth_tag = auth_tag
  
  cipher.update(encrypted) + cipher.final
end

#encrypt(data) ⇒ Object

Шифрует данные и возвращает строку для хранения



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/encrypth/cipher.rb', line 13

def encrypt(data)
  cipher = OpenSSL::Cipher.new("aes-256-gcm")
  cipher.encrypt
  cipher.key = @key
  
  iv = cipher.random_iv
  encrypted = cipher.update(data) + cipher.final
  auth_tag = cipher.auth_tag

  package(iv, encrypted, auth_tag)
end