用python/java实现hmacmd5加密的一个示例

hmacmd5(using python/java)

1. python实现hmacmd5的示例

# coding: utf-8

import hmac
import hashlib

ekey = 'samplekey'
to_enc = 'sampledata'

enc_res = hmac.new(ekey, to_enc, hashlib.md5).hexdigest()
print enc_res

2.java实现hmacmd5加密的示例

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 Coder {
    /**
     * MAC算法可选以下多种算法
     *
     * 
     * HmacMD5
     * HmacSHA1
     * HmacSHA256
     * HmacSHA384
     * HmacSHA512
     * 
*/
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 = "{\"somek\":\"somev\"}"; byte[] inputData = inputStr.getBytes(); String key = "somekey"; System.out.println(Coder.byteArrayToHexString(Coder.encryptHMAC(inputData, key))); } } 在线加解密站点 http://encode.chahuo.com/

你可能感兴趣的:(用python/java实现hmacmd5加密的一个示例)