Python3密码等文本加密
涉及到用户密码有时需要加密存储,很多种加密方法都能被暴力破解,本文介绍的是AES加密,也就是https中所用到的加密方法。
-
首先需要安装pycryptodome,里面包含AES
-
准备加密密钥,aes需要加密密钥,同时也是使用加密密钥来获取原文本
-
密钥需要时16位或者64位等,这里选择使用16位,当密钥不够的时候后面补0
代码如下:
#pip install pycryptodome
import base64
from Crypto.Cipher import AES
def
get16(s):
while
len(s) % 16 != 0:
s += ‘\0‘
return
str.encode(s)
#加密密匙
key = ‘shaynerain’
aes = AES.new(get16(key), AES.MODE_ECB)
#加密
def
encrypted(password):
return
str(base64.encodebytes(aes.encrypt(get16(password))), encoding=‘utf8’).replace(‘\n‘, ”)
#解密
def
decrypted(encrypted):
return
str(aes.decrypt(base64.decodebytes(bytes(encrypted, encoding=‘utf8’))).rstrip(b‘\0‘).decode(“utf8”))
闻道有先后
术业有专攻
From: shaynerain.com
By: Shaynerain