-
-
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.
This file contains hidden or 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