Created
July 11, 2016 08:10
-
-
Save silegon/d0bf0c4468a3a117efd96f382a1ea1d6 to your computer and use it in GitHub Desktop.
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
# -*- coding: utf-8 -*- | |
import base64 | |
from Crypto.Cipher import AES | |
from Crypto import Random | |
class AESCipher: | |
block_size = 32 | |
def __init__(self, key): | |
key_length = 43 | |
token = "RainClassroom" | |
if len(key) >= key_length: | |
self.key = key[:key_length] | |
else: | |
padNum = key_length - len(key) | |
self.key = key + token[padNum % len(token)] * padNum | |
self.key = base64.b64decode(self.key + "=") | |
self.mode = AES.MODE_CBC | |
def encode(self, text): | |
text_length = len(text) | |
amount_to_pad = self.block_size = (text_length % self.block_size) | |
if amount_to_pad == 0: | |
amount_to_pad = self.block_size | |
# 获得补位所用的字符 | |
pad = chr(amount_to_pad) | |
return text + pad * amount_to_pad | |
def decode(self, decrypted): | |
pad = ord(decrypted[-1]) | |
if pad<1 or pad >32: | |
pad = 0 | |
return decrypted[:-pad] | |
def encrypt(self, raw): | |
text = self.encode(raw) | |
cryptor = AES.new(self.key,self.mode,self.key[:16]) | |
ciphertext = cryptor.encrypt(text) | |
try: | |
ciphertext = cryptor.encrypt(text) | |
return True, base64.b64encode(ciphertext) | |
except Exception, e: | |
return False, None | |
def decrypt(self, enc): | |
try: | |
cryptor = AES.new(self.key,self.mode,self.key[:16]) | |
plain_text = cryptor.decrypt(base64.b64decode(enc)) | |
return True, self.decode(plain_text) | |
except Exception, e: | |
return False, None | |
if __name__ == "__main__": | |
key = "RainID39" | |
message = "0c2441ca-885d-488f-bf8b-cc6a423d67771468233499" | |
aes = AESCipher(key) | |
encrypt_message = aes.encrypt(message) | |
print key | |
print message | |
print encrypt_message | |
print aes.decrypt(encrypt_message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment