您的位置:首页 > 编程语言 > Python开发

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

2016-01-11 10:10 651 查看

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算法可选以下多种算法
*
* <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 = "{\"somek\":\"somev\"}";
byte[] inputData = inputStr.getBytes();
String key = "somekey";
System.out.println(Coder.byteArrayToHexString(Coder.encryptHMAC(inputData, key)));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: