Skip to content

Instantly share code, notes, and snippets.

@itkq
Created February 2, 2025 04:54
Show Gist options
  • Save itkq/ad2623d1385450b1fae7792c1bd3ebd2 to your computer and use it in GitHub Desktop.
Save itkq/ad2623d1385450b1fae7792c1bd3ebd2 to your computer and use it in GitHub Desktop.
require 'openssl'
require 'base64'
require 'digest'
plaintext = "sample"
pass = "pass"
key = Digest::SHA256.digest(pass)
cipher = OpenSSL::Cipher.new('aes-256-gcm')
cipher.encrypt
cipher.key = key
# should randomize
iv = "\x00" * 12
cipher.iv = iv
ciphertext = cipher.update(plaintext) + cipher.final
tag = cipher.auth_tag
encrypted = Base64.strict_encode64(iv + tag + ciphertext)
puts encrypted
decoded = Base64.decode64(encrypted)
extracted_iv = decoded[0, 12]
extracted_tag = decoded[12, 16]
extracted_ciphertext = decoded[28..-1]
decipher = OpenSSL::Cipher.new('aes-256-gcm')
decipher.decrypt
decipher.key = key
decipher.iv = extracted_iv
decipher.auth_tag = extracted_tag
decrypted = decipher.update(extracted_ciphertext) + decipher.final
puts decrypted
AAAAAAAAAAAAAAAA+gZt3i+0EOi82KwzS1QaTt6b3FPTlOztsbwvVqCPy5ZPdiQcS/Vaft2cgSJStRD1PAPFVpQ+YKsm57RTkfxGlGFGWbXx26lHCvBJyotoGPugAB58GLCWLSlUp2I2Mzx8xBuOmA==
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment