python实现加密

1、md5加密

hashlib 库中包括如SHA1、SHA224、SHA256、SHA384、SHA512和MD5算法等

>>> import hashlib
>>> hashlib.md5('123'.encode('utf-8')).hexdigest()
'202cb962ac59075b964b07152d234b70'

  

2、base64

import base64

str = 'hello world'.encode(encoding='utf-8')

#加密
encodestr = base64.b64encode(str)
print(encodestr) #b'aGVsbG8gd29ybGQ='
print(encodestr.decode()) #aGVsbG8gd29ybGQ= #解密 decodestr = base64.b64decode(encodestr)
print(decodestr) #b'hello world'
print(decodestr.decode()) #hello world

  

3、AES

#AES-demo

import base64
from Crypto.Cipher import AES '''
采用AES对称加密算法
'''
# str不是16的倍数那就补足为16的倍数
def add_to_16(value):
while len(value) % 16 != 0:
value += '\0'
return str.encode(value) # 返回bytes
#加密方法
def encrypt_oracle():
# 秘钥
key = ''
# 待加密文本
text = 'abc123def456'
# 初始化加密器
aes = AES.new(add_to_16(key), AES.MODE_ECB)
#先进行aes加密
encrypt_aes = aes.encrypt(add_to_16(text))
#用base64转成字符串形式
encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8') # 执行加密并转码返回bytes
print(encrypted_text)
#解密方法
def decrypt_oralce():
# 秘钥
key = ''
# 密文
text = 'qR/TQk4INsWeXdMSbCDDdA=='
# 初始化加密器
aes = AES.new(add_to_16(key), AES.MODE_ECB)
#优先逆向解密base64成bytes
base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
#
decrypted_text = str(aes.decrypt(base64_decrypted),encoding='utf-8') # 执行解密密并转码返回str
print(decrypted_text) if __name__ == '__main__':
# encrypt_oracle()
decrypt_oralce()

4、RSA

pip install rsa  //安装rsa模块

 import rsa
key = rsa.newkeys(3000)#生成随机秘钥
privateKey = key[1]#私钥
publicKey = key[0]#公钥
message ='sanxi Now is better than never.'
print('Before encrypted:',message)
message = message.encode()
cryptedMessage = rsa.encrypt(message, publicKey)
print('After encrypted:\n',cryptedMessage)
message = rsa.decrypt(cryptedMessage, privateKey)
message = message.decode()
print('After decrypted:',message)
上一篇:ThinkPHP中的pathinfo模式和URL重写


下一篇:执行sudo时报错:effective uid is not 0