java中消息摘要算法mac的实现
jdk中mac的实现
package hmac;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
public class HmacMD5Jdk {
public static void main(String[] args) throws Exception{
String source = "test";
/**随机产生秘钥或者指定秘钥 */
//随机产生秘钥
KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
byte[] key =keyGenerator.generateKey().getEncoded();
//或者去指定秘钥
key = "aaaaa".getBytes();
Mac mac = Mac.getInstance("HmacMD5");
mac.init(new SecretKeySpec(key, "HmacMD5"));
mac.update(source.getBytes());
System.out.println(Hex.encodeHexString(mac.doFinal()));
}
}
bc(boucy castle)中mac的实现:
package hmac;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;
public class HmacMD5Bc {
public static void main(String[] args) {
String source = "test";
HMac hmac = new HMac(new MD5Digest());
hmac.init(new KeyParameter("aaaaa".getBytes()));
hmac.update(source.getBytes(), 0, source.getBytes().length);
byte[] resultBytes = new byte[hmac.getMacSize()];
hmac.doFinal(resultBytes, 0);
System.out.println(Hex.toHexString(resultBytes));
}
}