Last active
October 18, 2016 15:37
-
-
Save teitei-tk/75ddab6f254c5ab0397a to your computer and use it in GitHub Desktop.
Pythonで暗号化と復号化 ref: http://qiita.com/teitei_tk/items/0b8bae99a8700452b718
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
import base64 | |
from Crypto import Random | |
from Crypto.Cipher import AES | |
class AESCipher(object): | |
def __init__(self, key, block_size=32): | |
self.bs = block_size | |
if len(key) >= len(str(block_size)): | |
self.key = key[:block_size] | |
else: | |
self.key = self._pad(key) | |
def encrypt(self, raw): | |
raw = self._pad(raw) | |
iv = Random.new().read(AES.block_size) | |
cipher = AES.new(self.key, AES.MODE_CBC, iv) | |
return base64.b64encode(iv + cipher.encrypt(raw)) | |
def decrypt(self, enc): | |
enc = base64.b64decode(enc) | |
iv = enc[:AES.block_size] | |
cipher = AES.new(self.key, AES.MODE_CBC, iv) | |
return self._unpad(cipher.decrypt(enc[AES.block_size:])) | |
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:])] |
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
$ pip install pycrypto |
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
$ python -c "import string, random; print(''.join([random.choice(string.ascii_letters + string.digits) for i in range(50)]))" | |
>>> PkDv17c6xxiqXPrvG2cUiq90VIrERfthHuViKapv6E1F7E0IgP |
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
cipher = AESCipher("PkDv17c6xxiqXPrvG2cUiq90VIrERfthHuViKapv6E1F7E0IgP") | |
# 暗号化 | |
password = cipher.encrypt("hogefuga") | |
print(password) # -> H/LfZg82FOdHhnructCHzfYnVgCOvjgEUGXXDFpjiYLBHw4Zflk/m2N9zEVwz6eC | |
#復号化 | |
print(cipher.decrypt(password)) # -> hogefuga |
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
$ pip install Simple-AES-Cipher |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment