Skip to content

Instantly share code, notes, and snippets.

@3014zhangshuo
Forked from tcaddy/aes-128-ecb.rb
Created April 14, 2021 06:51
Show Gist options
  • Save 3014zhangshuo/eb36171c6b5417a713178966f1b61285 to your computer and use it in GitHub Desktop.
Save 3014zhangshuo/eb36171c6b5417a713178966f1b61285 to your computer and use it in GitHub Desktop.
Ruby AES-128-ECB encryption / decryption example. This was written to interface with a 3rd party that required string parameters to be encrypted the following way: Rinndael cipher, Electronic Code Block mode (ECB), no padding, encrypted buffer should be padded with spaces such that its length is divisible by 32.
# setup some input parameters
encrypted_decrypted = 'some string to encrypt or decrypt'
action = :encrypt # set to :encrypt or :decrypt
secret_key = 'abc123' # define shared secret key here
# encryption / decryption code...
cipher = OpenSSL::Cipher.new('AES-128-ECB')
if action == :decrypt
cipher.key = [secret_key].pack('H*')
cipher.padding = 0
cipher.decrypt
plaintext = cipher.update [encrypted_decrypted].pack('H*')
plaintext += cipher.final
plaintext.strip
else
# see: https://bugs.ruby-lang.org/issues/8720#note-1
cipher.encrypt # this needs to be called first to make encryption work for AES-128-ECB
cipher.key = [secret_key].pack('H*')
cipher.padding = 0
if encrypted_decrypted.size % 32 != 0
# size of string must be divisible by 32
encrypted_decrypted += ' ' * (32 - (encrypted_decrypted.size % 32))
end
encrypted = cipher.update encrypted_decrypted
encrypted += cipher.final
encrypted.unpack('H*').first
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment