Class: Dotenvcrypt::Encryptor
- Inherits:
-
Object
- Object
- Dotenvcrypt::Encryptor
- Defined in:
- lib/dotenvcrypt/encryptor.rb
Instance Method Summary collapse
-
#decrypt(encoded_data) ⇒ Object
Decrypt file.
-
#encrypt(data) ⇒ Object
Encrypt file.
-
#initialize(encryption_key) ⇒ Encryptor
constructor
A new instance of Encryptor.
Constructor Details
#initialize(encryption_key) ⇒ Encryptor
Returns a new instance of Encryptor.
3 4 5 |
# File 'lib/dotenvcrypt/encryptor.rb', line 3 def initialize(encryption_key) @encryption_key = encryption_key end |
Instance Method Details
#decrypt(encoded_data) ⇒ Object
Decrypt file
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/dotenvcrypt/encryptor.rb', line 30 def decrypt(encoded_data) begin data = Base64.strict_decode64(encoded_data) rescue ArgumentError puts "❌ Decryption failed. File is not in valid base64 format." exit(1) end # For GCM mode: # - IV is 12 bytes # - Auth tag is 16 bytes iv_size = 12 auth_tag_size = 16 # Extract the components iv = data[0...iv_size] auth_tag = data[iv_size...(iv_size + auth_tag_size)] encrypted_data = data[(iv_size + auth_tag_size)..-1] cipher = OpenSSL::Cipher::AES256.new(:GCM) cipher.decrypt cipher.key = OpenSSL::Digest::SHA256.digest(encryption_key) cipher.iv = iv cipher.auth_tag = auth_tag cipher.update(encrypted_data) + cipher.final rescue OpenSSL::Cipher::CipherError puts "❌ Decryption failed. Invalid key, corrupted file, or tampering detected." exit(1) end |
#encrypt(data) ⇒ Object
Encrypt file
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/dotenvcrypt/encryptor.rb', line 8 def encrypt(data) cipher = OpenSSL::Cipher::AES256.new(:GCM) cipher.encrypt key = OpenSSL::Digest::SHA256.digest(encryption_key) cipher.key = key # Generate a secure random IV (12 bytes is recommended for GCM) iv = cipher.random_iv encrypted = cipher.update(data) + cipher.final # Get the authentication tag (16 bytes) auth_tag = cipher.auth_tag # Combine IV, encrypted data, and auth tag combined = iv + auth_tag + encrypted # Convert to base64 for readability Base64.strict_encode64(combined) end |