Created
March 8, 2017 16:15
-
-
Save tcaddy/c2282fb795581d560fb7a42ff1f5e8d6 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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