Skip to content

Instantly share code, notes, and snippets.

@gustavohenrique
Created September 13, 2017 17:52
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save gustavohenrique/79cc95cc351d975a075f18a5c9f49319 to your computer and use it in GitHub Desktop.
Save gustavohenrique/79cc95cc351d975a075f18a5c9f49319 to your computer and use it in GitHub Desktop.
An example using Python3 and AES criptography
import sys
import base64
from Crypto.Cipher import AES
class AESCipher(object):
def __init__(self, key):
self.bs = 16
self.cipher = AES.new(key, AES.MODE_ECB)
def encrypt(self, raw):
raw = self._pad(raw)
encrypted = self.cipher.encrypt(raw)
encoded = base64.b64encode(encrypted)
return str(encoded, 'utf-8')
def decrypt(self, raw):
decoded = base64.b64decode(raw)
decrypted = self.cipher.decrypt(decoded)
return str(self._unpad(decrypted), 'utf-8')
def _pad(self, s):
return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
def _unpad(self, s):
return s[:-ord(s[len(s)-1:])]
if __name__ == '__main__':
key = '`?.F(fHbN6XK|j!t'
cipher = AESCipher(key)
plaintext = '542#1504891440039'
encrypted = cipher.encrypt(plaintext)
print('Encrypted: %s' % encrypted)
ciphertext = '5bgJqIqFuT8ACuvT1dz2Bj5kx9ZAIkODHWRzuLlfYV0='
assert encrypted == ciphertext
decrypted = cipher.decrypt(encrypted)
print('Decrypted: %s' % decrypted)
assert decrypted == plaintext
@NovaStreet
Copy link

alguien sabe que hace exactamente la funcion _pad?

@srinivasanvarun
Copy link

@NovaStreet The AES algorithm works on text with length in the multiples of 16 bytes. Hence, they are trying to pad digits to make it to a text of length of the nearest multiple of 16.

@durgeswar
Copy link

durgeswar commented Jul 27, 2019

@srinivasanvarun How to implement AES parallelly. Need inputs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment