HmacMD5加密

 

//C# HmacMD5加密

string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.UTF8.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.UTF8.GetBytes(source));
StringBuilder sb = new StringBuilder();

for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}

hmacmd.Clear();

return sb.ToString();
}

 

 

 

 

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


public class SignatureUtil {

/**
* MD5 签名 *
*
* @param source 签名参数
* @param key 签名密钥
* @return
*/
public static String cryptMd5(String source, String key) {
byte k_ipad[] = new byte[64];
byte k_opad[] = new byte[64];
byte keyb[];
byte value[];
try {
keyb = key.getBytes("UTF-8");
value = source.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
keyb = key.getBytes();
value = source.getBytes();
}
Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
for (int i = 0; i < keyb.length; i++) {
k_ipad[i] = (byte) (keyb[i] ^ 0x36);
k_opad[i] = (byte) (keyb[i] ^ 0x5c);
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
md.update(k_ipad);
md.update(value);
byte dg[] = md.digest();
md.reset();
md.update(k_opad);
md.update(dg, 0, 16);
dg = md.digest();
return toHex(dg);
}

private static String toHex(byte input[]) {
if (input == null) return null;
StringBuffer output = new StringBuffer(input.length * 2);
for (int i = 0; i < input.length; i++) {
int current = input[i] & 0xff;
if (current < 16) output.append("0");
output.append(Integer.toString(current, 16));
}
return output.toString();
}

}

posted @ 2020-12-23 17:16  liangyubin  阅读(656)  评论(0)    收藏  举报