Python---加密解密(hashlib、rsa)

hashlib模块加密

import hashlib

new_md5 = hashlib.md5()       # 创建hashlib的md5对象
new_md5.update("python")      # 将字符串载入到md5对象中,获得md5算法加密。
result = new_md5.hexdigest()  # 通过hexdigest()方法,获得new_md5对象的16进制md5显示。
print result      # 结果:23eeeb4347bdd26bfc6b7ee9a3b755dd


# 可以创建的加密算法有:md5, sha1, sha224, sha256, sha384, sha512
# new_md5 = hashlib.md5()   
# new_sha1 = hashlib.sha1()  
# new_sha256 = hashlib.sha256()
import hashlib,time

new_md5 = hashlib.new('md5', b'python').hexdigest()
print new_md5      # 结果:23eeeb4347bdd26bfc6b7ee9a3b755dd
new_md5 = hashlib.md5("python".encode('utf-8')).hexdigest()
print new_md5      # 结果:23eeeb4347bdd26bfc6b7ee9a3b755dd
import hashlib

# yan = "!任#意%字^符@"  #定义加盐字符串
yan = "salt"
pwd = "python"
md5_pwd = hashlib.md5()
md5_pwd.update((pwd+yan).encode('utf-8'))  #加盐
pwd = md5_pwd.hexdigest()
print pwd
#pwd = hashlib.new('md5',(pwd+yan).encode('UTF-8')).hexdigest()   #也可以这样简写哦。

# 参考:https://www.cnblogs.com/sly27/p/8716626.html
# -*- coding:utf-8 -*-
import hashlib

def hashStr(strInfo):
    h = hashlib.sha1()
    h.update(strInfo.encode("utf-8"))
    return h.hexdigest()

result = hashStr("hello word")
print result

RSA加密/解密,签名/验证

# -*- coding:utf-8 -*-
import rsa

# 生成密钥:生成RSA公钥和秘钥
(pubkey, privkey) = rsa.newkeys(1024)

# 保存密钥(一个公钥一个私钥)
with open('public.pem', 'w+') as f:
    f.write(pubkey.save_pkcs1().decode())
with open('private.pem', 'w+') as f:
    f.write(privkey.save_pkcs1().decode())

# 导入密钥
with open('public.pem', 'r') as f:
    pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())
with open('private.pem', 'r') as f:
    privkey = rsa.PrivateKey.load_pkcs1(f.read().encode())

# 明文
message = "python"

# 公钥对明文加密,得到密文
crypto = rsa.encrypt(message.encode(), pubkey)

# 私钥对密文解密,得到明文
message = rsa.decrypt(crypto, privkey).decode()
print message


message = "这是服务器发的消息!"
# 私钥签名
signature = rsa.sign(message.encode("utf-8"), privkey, 'SHA-1')
# 公钥验证:同时收到指令明文、密文,然后用公钥验证,进行身份确认
result = rsa.verify(message.encode("utf-8"), signature, pubkey)
print result

# 参考:https://www.cnblogs.com/hhh5460/p/5243410.html
# 参考:https://blog.csdn.net/u013421629/article/details/83895861

注册时密码加密与登陆时密码验证

# -*- coding:utf-8 -*-
from passlib.hash import pbkdf2_sha512

# 对love字符串进行加密,love是明文,password_hash是密文。
password_hash = pbkdf2_sha512.encrypt("love")
print password_hash      # 结果:$pbkdf2-sha512$25000$wnjvvdf6XytFyHlPyVkLAQ$2kL4UztPbWoQmblT4TRxOUoCiDNYvSwGd1EYOWcqhrYUpH9MXHfzaFFw3fGyRsfIZy8SDlXD1HP2U4AlIsdBTA

# 对love字符串进行验证,love是明文,password_hash是密文。
result = pbkdf2_sha512.verify("love", password_hash)
print result      # 结果:True

 

你可能感兴趣的:(Python基础)