Python常见的加密模块(hashlib,盐值混淆hashlib,hmac)

1,hashlib

2,hmac

hashlib模块

python提供了一个hashlib模块,可以对传递的值进行hash算法的加密

>>> dir(hashlib)
['__all__', '__builtin_constructor_cache', '__builtins__', '__cached__', '__doc__', '__file__', '__get_builtin_constructor', '__loader__', '__name__', '__package__', '__spec__', '_hashlib', 'algorithms_available', 'algorithms_guaranteed', 'blake2b', 'blake2s', 'md5', 'new', 'pbkdf2_hmac', 'scrypt', 'sha1', 'sha224', 'sha256', 'sha384', 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512', 'sha512', 'shake_128', 'shake_256']
>>>

>>> help(hashlib.md5)
Help on built-in function openssl_md5 in module _hashlib:

openssl_md5(...)
    Returns a md5 hash object; optionally initialized with a string

>>>

模块_hashlib中的内置函数openssl_md5的帮助:

openssl_md5(...)返回md5哈希对象;

可以选择用字符串

>>>

其中我们只利用md5算法进行加密的演示:

基础的MD5加密:

import hashlib   #导入模块

passwd = "redhat"   #密码字符
md5passwd = hashlib.md5()        #初始化MD5  
md5passwd.update(passwd.encode('utf-8'))      #hashlib只能接受比特b数据,这里先转码#输出散列值

print(md5passwd.hexdigest())        #输出散列值,也就是转换成16进制字符串

带有盐值混淆的MD5加密:

import hashlib   #导入模块

passwd = "redhat"   #密码字符
salt = "^*F&DB#@%&)(*%$#@"

md5passwd = hashlib.md5()
md5passwd.update(passwd.encode('utf-8'))
md5passwd.update(salt.encode('utf-8'))     #对原MD5值进行二次加密(盐值混淆)

print(md5passwd.hexdigest())    #输出散列值,也就是转换成16进制字符串

hmac模块

>>> import hmac
>>> dir(hmac)
['HMAC', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_hashlib', '_hashopenssl', '_openssl_md_meths', '_warnings', 'compare_digest', 'digest', 'digest_size', 'new', 'trans_36', 'trans_5C']
>>>

这里我们只学习一个 new 方法

new方法的hmac加密

>>> help(hmac.new)
Help on function new in module hmac:

new(key, msg=None, digestmod=None)
    Create a new hashing object and return it.

    key: The starting key for the hash.
    msg: if available, will immediately be hashed into the object's starting
    state.

    You can now feed arbitrary strings into the object using its update()
    method, and can ask for the hash value at any time by calling its digest()
    method.

>>>

>>> help(hmac.new)

关于hmac模块中新功能的帮助

new(key,msg = None,digestmod = “默认MD5”)创建一个新的哈希对象并返回它。

key:哈希的开始键。

msg:如果可用,将立即哈希为对象的起始状态。

现在,您可以使用其update()方法将任意字符串输入对象,并可以随时通过调用其digest()方法来请求哈希值。

>>>

import hmac     #导入模块
 
passwd = b"redhat"              #密码字符         
passwd2 = b"^*F&DB#@%&)(*%$#@"  #混淆参数 

hmacpasswd = hmac.new(passwd,passwd2,digestmod = 'MD5')  
#方法后必须加上默认使用的加密方式,这里的hmac是一个较为复杂的混合加码方法,安全系数相较于hashlib有很大的提升

print(hmacpasswd.hexdigest())    #输出散列值,也就是十六进制字符串

发布了35 篇原创文章 · 获赞 36 · 访问量 6092

猜你喜欢

转载自blog.csdn.net/Alexz__/article/details/104533212
今日推荐