我对Python不熟悉。我有一个 java 片段来实现将数据编码为 MD5 字符串的算法。我想把它转换成Python。我的java代码使用commons-codec1.9来encodeBase64。 有人可以帮忙吗?非常感谢。
public static void Main(args){
String data ="token=cd264af2fbd&app_key=060176144a&client_os_type=4";
String key = "87483ik98abh";
String md5EncodedData = getEncodeData(data, key);
}
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
public String getEncodeData(String app_secret, String data){
try{
byte[] hmc = calculateRFC2104HMAC(Base64.encodeBase64(data.getBytes()), app_secret);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(hmc);
return new String(Hex.encodeHex(thedigest));
}catch (Exception ex){
System.out.print(ex.getMessage().toString());
}
return "";
}
public static byte[] calculateRFC2104HMAC(byte[] data, String key)
throws java.security.SignatureException
{
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(data);
return rawHmac;
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
}
最佳答案
你看过python的hashlib模块吗?
https://docs.python.org/2/library/hashlib.html#module-hashlib
关于java - 如何在 Python 中实现将数据编码为 MD5 字符串的算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37313342/