您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python实现的HMacMD5加密算法示例_python

2024/3/18 8:22:14发布37次查看
这篇文章主要介绍了python实现的hmacmd5加密算法,简单说明了hmac-md5加密算法的概念、原理并结合实例形式分析了python实现hmac-md5加密算法的相关操作技巧,,末尾还附带了java实现hmac-md5加密算法的示例,需要的朋友可以参考下
本文实例讲述了python实现的hmacmd5加密算法。分享给大家供大家参考,具体如下:
什么是 hmac-md5?
1、比如你和对方共享了一个密钥k,现在你要发消息给对方,既要保证消息没有被篡改,又要能证明信息确实是你本人发的,那么就把原信息和使用k计算的hmac的值一起发过去。对方接到之后,使用自己手中的k把消息计算一下hmac,如果和你发送的hmac一致,那么可以认为这个消息既没有被篡改也没有冒充。
2、md5就是通过散列对要输出的数据进行摘要,接收到数据时,再同样进行md5散列,与给定的md5散列值比较,一致不一致就很清楚了。通常来说,传输的数据和md5是不同的渠道给出的,比如网页上显示md5,下载链接是某个镜像网站的。如果要通过同一个渠道发送数据和散列值的话(比如消息认证码),就要考虑数据和md5同时被篡改的问题,如果第三方修改了数据,然后进行md5散列,并一块发给接收方,接收方并不能察觉到数据被篡改。hmac-md5就可以用一把发送方和接收方都有的key进行计算,而没有这把key的第三方是无法计算出正确的散列值的,这样就可以防止数据被篡改。
python 版:
#coding:utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') import hmac import hashlib ####################设置key值############## ekey = 'laidefa' ###############输入数据############ to_enc = '{"name":"zhangsan"}' enc_res = hmac.new(ekey, to_enc, hashlib.md5).hexdigest() print enc_res
输出结果:
"d:\program files\python27\python.exe" d:/pycharmprojects/learn2017/hmacmd5.py
2cbb94ce78b35e4030851c4d40dacf12
process finished with exit code 0
java版:
package tom; import java.security.messagedigest; import javax.crypto.keygenerator; import javax.crypto.mac; import javax.crypto.secretkey; import javax.crypto.spec.secretkeyspec; /** * 基础加密组件 * @version 1.0 */ public class hmacmd5 { /** * mac算法可选以下多种算法 * * <pre> * hmacmd5 * hmacsha1 * hmacsha256 * hmacsha384 * hmacsha512 * </pre> */ public static final string key_mac = "hmacmd5"; /** * hmac加密 * * @param data * @param key * @return * @throws exception */ public static byte[] encrypthmac(byte[] data, string key) throws exception { secretkey secretkey = new secretkeyspec(key.getbytes(), key_mac); mac mac = mac.getinstance(secretkey.getalgorithm()); mac.init(secretkey); return mac.dofinal(data); } /*byte数组转换为hexstring*/ public static string bytearraytohexstring(byte[] b) { stringbuffer sb = new stringbuffer(b.length * 2); for (int i = 0; i < b.length; i++) { int v = b[i] & 0xff; if (v < 16) { sb.append('0'); } sb.append(integer.tohexstring(v)); } return sb.tostring(); } public static void main(string[] args)throws exception{ string inputstr = "{\"name\":\"zhangsan\"}"; byte[] inputdata = inputstr.getbytes(); string key = "laidefa"; system.out.println(hmacmd5.bytearraytohexstring(hmacmd5.encrypthmac(inputdata, key))); } }
输出结果:
2cbb94ce78b35e4030851c4d40dacf12
ps:关于加密解密感兴趣的朋友还可以参考本站在线工具:
文字在线加密解密工具(包含aes、des、rc4等):
http://tools.jb51.net/password/txt_encode
md5在线加密工具:
http://tools.jb51.net/password/createmd5password
在线散列/哈希算法加密工具:
http://tools.jb51.net/password/hash_encrypt
在线md5/hash/sha-1/sha-2/sha-256/sha-512/sha-3/ripemd-160加密工具:
http://tools.jb51.net/password/hash_md5_sha
在线sha1/sha224/sha256/sha384/sha512加密工具:
http://tools.jb51.net/password/sha_encode
相关推荐:
转:hmacmd5算法[php版]
以上就是python实现的hmacmd5加密算法示例_python的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product