您的当前位置:首页正文

Python怎么实现HMacMD5加密算法

2020-11-27 来源:好走旅游网

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

相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!

推荐阅读:

python字符串如何转为二维数组

Event emitter的监听事件

显示全文