Method: Conceal.decrypt
- Defined in:
- lib/conceal.rb
.decrypt(data, opts = {}) ⇒ Object
Decrypts the given encrypted string.
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/conceal.rb', line 58 def decrypt(data, opts = {}) key = opts[:key] raise ArgumentError.new(':key option missing') if key.to_s.empty? ver, algorithm, iv64, salt64, hmac64, ciphertext64 = data.split(FIELD_SEPARATOR, 6) raise ArgumentError.new('ciphertext has unknown version') unless ver == FORMAT_VERSION.to_s iv = Base64.decode64(iv64) salt = Base64.decode64(salt64) hmac = Base64.decode64(hmac64) ciphertext = Base64.decode64(ciphertext64) # validate the hmac digest = OpenSSL::Digest.new('sha256') actual_hmac = OpenSSL::HMAC.digest(digest, key, ciphertext) raise ArgumentError.new('HMAC mismatch') unless actual_hmac == hmac # decrypt cipher = OpenSSL::Cipher::Cipher.new(algorithm) cipher.decrypt cipher.iv = iv cipher.key = OpenSSL::PKCS5.pbkdf2_hmac_sha1(key, salt, 2000, cipher.key_len) plaintext = cipher.update(ciphertext) plaintext << cipher.final plaintext end |