This is the first post!
While studying Python, I want to do password encryption! I thought about it. It seems that pycrypto is famous as an encryption package, and it could be installed in Anaconda, so this time I will use pycrypto to summarize AES encryption of strings.
The links I referred to when learning AES encryption are as follows. https://blanktar.jp/blog/2013/04/python-crypto-aes.html https://ujise.com/2019/08/23/post-1869/ https://ja.wikipedia.org/wiki/Advanced_Encryption_Standard
Now, the actual code. The code below passes the text of the password and encrypts and decrypts it. The encrypted data is stored as password_data_file.
pycrypto.py
from Crypto.Cipher import AES
#Key setting function
def create_key(KeyWord):
key_size = 32
KeySizeFill = KeyWord.zfill(key_size)
Key = KeySizeFill[:key_size].encode('utf-8')
return Key
#Password encryption function
def encryptOn(PassWord, KeyWord):
iv = "1234567890123456" #Initialization vector setting
Key = create_key(KeyWord) #Key setting
obj = AES.new(Key, AES.MODE_CFB, iv)
ret_bytes = obj.encrypt(IPassWord) #Password encryption
#Output of encrypted file
OFileName = "password_data_file"
with open(OFileName, mode='wb') as f:
f.write(ret_bytes)
#Password compounding function
def encryptOff(KeyWord):
#Read password file
PassFile = "password_data_file"
with open(PassFile, 'rb') as f:
EnPass = f.read() #Encrypted password
iv = "1234567890123456" #Initialization vector setting
key = create_key(KeyWord) #Key setting
obj = AES.new(key, AES.MODE_CFB, iv)
OPassword = obj.decrypt(Pass).decode('utf-8') #Password compounding
return OPassword
if __name__ == '__main__':
IPassWord = "modelPass"
KeyWord = "login_file"
#Cryptographic function call
encryptOn(IPassWord, KeyWord)
#Complex function call
OPassWord = encryptOff(KeyWord)
print(OPassWord)
When you first look at the reference code, it's complicated ~ do you understand? I thought, but it's unexpectedly simple logic. Since the key and vector are simply written directly, it must be changed for each encryption.