Class: EasyCrypto::Crypto
- Inherits:
-
Object
- Object
- EasyCrypto::Crypto
- Defined in:
- lib/easycrypto/crypto.rb
Constant Summary collapse
- KEY_BITS =
256- AES_MODE =
:GCM- IV_LEN =
12- AUTH_TAG_LEN =
16
Instance Method Summary collapse
- #decrypt(password, ciphertext) ⇒ Object
- #decrypt_with_key(key, ciphertext) ⇒ Object
- #encrypt(password, plaintext) ⇒ Object
- #encrypt_with_key(key, plaintext) ⇒ Object
-
#initialize(salt_length = DEFAULT_SALT_LENGTH) ⇒ Crypto
constructor
A new instance of Crypto.
Constructor Details
#initialize(salt_length = DEFAULT_SALT_LENGTH) ⇒ Crypto
Returns a new instance of Crypto.
12 13 14 |
# File 'lib/easycrypto/crypto.rb', line 12 def initialize(salt_length = DEFAULT_SALT_LENGTH) @salt_length = salt_length end |
Instance Method Details
#decrypt(password, ciphertext) ⇒ Object
34 35 36 37 38 39 |
# File 'lib/easycrypto/crypto.rb', line 34 def decrypt(password, ciphertext) salt = get_salt_from_ciphertext(ciphertext) key = EasyCrypto::Key.generate_with_salt(password, salt) decrypt_with_key(key, ciphertext) end |
#decrypt_with_key(key, ciphertext) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/easycrypto/crypto.rb', line 41 def decrypt_with_key(key, ciphertext) validate_key_type(key) raw_ciphertext = Base64.strict_decode64(ciphertext) iv = raw_ciphertext[key.salt.length, IV_LEN] encrypted = raw_ciphertext[(key.salt.length + IV_LEN)..-(AUTH_TAG_LEN + 1)] auth_tag = raw_ciphertext[-AUTH_TAG_LEN..-1] decipher = create_decipher(key, iv, auth_tag) decipher.update(encrypted) + decipher.final end |
#encrypt(password, plaintext) ⇒ Object
16 17 18 19 20 |
# File 'lib/easycrypto/crypto.rb', line 16 def encrypt(password, plaintext) key = EasyCrypto::Key.generate(password, @salt_length) encrypt_with_key(key, plaintext) end |
#encrypt_with_key(key, plaintext) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/easycrypto/crypto.rb', line 22 def encrypt_with_key(key, plaintext) validate_key_type(key) validate_plaintext(plaintext) iv = OpenSSL::Random.random_bytes(Crypto::IV_LEN) cipher = create_cipher(key, iv) encrypted = cipher.update(plaintext) + cipher.final Base64.strict_encode64(key.salt + iv + encrypted + cipher.auth_tag) end |