I think it's okay to copy and use it, but I can't guarantee that the code is correct because I don't fully understand AES. If you have any vulnerabilities, please let us know in the comments.
Installation is
$ pip install pycrypto
get_encrypt_data.py
from Crypto.Cipher import AES
import hashlib
import base64
def get_encrypt_data(raw_data, key, iv):
raw_data_base64 = base64.b64encode(raw_data)
# 16byte
if len(raw_data_base64) % 16 != 0:
raw_data_base64_16byte = raw_data_base64
for i in range(16 - (len(raw_data_base64) % 16)):
raw_data_base64_16byte += "_"
else:
raw_data_base64_16byte = raw_data_base64
secret_key = hashlib.sha256(key).digest()
iv = hashlib.md5(iv).digest()
crypto = AES.new(secret_key, AES.MODE_CBC, iv)
cipher_data = crypto.encrypt(raw_data_base64_16byte)
cipher_data_base64 = base64.b64encode(cipher_data)
return cipher_data_base64
Plaintext data as an argument. key. vector. First of all, change to base64 (to make double-byte characters and images ok) Then the encrypted statement must be a multiple of 16 bits, so Basically, "_" that is not used in base64 is complemented with a ketsu and converted to a multiple of 16 bits. If it is a multiple of 16 bytes, it is as it is Change the key to 32 bit length with sha256. Change the vector to 16-bit length with MD5. Encrypt it, convert it to base64 for easy transmission, and return it.
get_decrypt_data.py
from Crypto.Cipher import AES
import hashlib
import base64
def get_decrypt_data(cipher_data_base64, key, iv):
cipher_data = base64.b64decode(cipher_data_base64)
secret_key = hashlib.sha256(key).digest()
iv = hashlib.md5(iv).digest()
crypto = AES.new(secret_key, AES.MODE_CBC, iv)
raw_data_base64_16byte = crypto.decrypt(cipher_data)
raw_data_base64 = raw_data_base64_16byte.split("_")[0]
raw_data = base64.b64decode(raw_data_base64)
return raw_data
Cryptographic data converted to base64 as an argument. key. vector. First, convert the encrypted data converted to base64 into encrypted data. Then change the key to 32 bits with sha256. Decrypt and extract only valid base64 with split ("_") [0] and return it as a converted return.
main.py
if __name__ == "__main__":
message = "114514"
password = "This is password"
iv = "hoge"
encrypt_data = get_encrypt_data(message, password, iv)
print encrypt_data
decrypt_data = get_decrypt_data(encrypt_data, password, iv)
print decrypt_data
cmd.sh
$ r64FMFs04APfNQo2d6uFpQ==
$ 114514
Recommended Posts