Class: Heya::License::Encryptor
- Inherits:
-
Object
- Object
- Heya::License::Encryptor
- Defined in:
- lib/heya/license/encryptor.rb
Defined Under Namespace
Classes: DecryptionError, Error, KeyError
Instance Attribute Summary collapse
-
#key ⇒ Object
Returns the value of attribute key.
Instance Method Summary collapse
- #decrypt(data) ⇒ Object
- #encrypt(data) ⇒ Object
-
#initialize(key) ⇒ Encryptor
constructor
A new instance of Encryptor.
Constructor Details
Instance Attribute Details
#key ⇒ Object
Returns the value of attribute key.
32 33 34 |
# File 'lib/heya/license/encryptor.rb', line 32 def key @key end |
Instance Method Details
#decrypt(data) ⇒ Object
68 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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
# File 'lib/heya/license/encryptor.rb', line 68 def decrypt(data) unless key.public? raise KeyError, "Provided key is not a public key." end json_data = Base64.decode64(data.chomp) begin encryption_data = JSON.parse(json_data) rescue JSON::ParserError raise DecryptionError, "Encryption data is invalid JSON." end unless %w[data key iv].all? { |key| encryption_data[key] } raise DecryptionError, "Required field missing from encryption data." end encrypted_data = Base64.decode64(encryption_data["data"]) encrypted_key = Base64.decode64(encryption_data["key"]) aes_iv = Base64.decode64(encryption_data["iv"]) begin # Decrypt the AES key using asymmetric RSA encryption. aes_key = self.key.public_decrypt(encrypted_key) rescue OpenSSL::PKey::RSAError raise DecryptionError, "AES encryption key could not be decrypted." end # Decrypt the data using symmetric AES encryption. cipher = OpenSSL::Cipher::AES128.new(:CBC) cipher.decrypt begin cipher.key = aes_key rescue OpenSSL::Cipher::CipherError raise DecryptionError, "AES encryption key is invalid." end begin cipher.iv = aes_iv rescue OpenSSL::Cipher::CipherError raise DecryptionError, "AES IV is invalid." end begin data = cipher.update(encrypted_data) + cipher.final rescue OpenSSL::Cipher::CipherError raise DecryptionError, "Data could not be decrypted." end data end |
#encrypt(data) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/heya/license/encryptor.rb', line 42 def encrypt(data) unless key.private? raise KeyError, "Provided key is not a private key." end # Encrypt the data using symmetric AES encryption. cipher = OpenSSL::Cipher::AES128.new(:CBC) cipher.encrypt aes_key = cipher.random_key aes_iv = cipher.random_iv encrypted_data = cipher.update(data) + cipher.final # Encrypt the AES key using asymmetric RSA encryption. encrypted_key = key.private_encrypt(aes_key) encryption_data = { "data" => Base64.encode64(encrypted_data), "key" => Base64.encode64(encrypted_key), "iv" => Base64.encode64(aes_iv) } json_data = JSON.dump(encryption_data) Base64.encode64(json_data) end |