so,so结果如下
gem install ruby-hmac require 'hmac-md5' HMAC::MD5.new("test_key").update("test_string").hexdigest.upcase()
ruby的输出结果
引用
=> "3FD9B6B4901DAF25BFB9DAA0718B3698"
package com.study; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class HmacMD5 { private static byte[] encryptHMAC(String data, String secret) { byte[] bytes = null; SecretKey secretKey; try { secretKey = new SecretKeySpec(secret.getBytes(Constants.CHARSET_UTF8), "HmacMD5"); Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); bytes = mac.doFinal(data.getBytes(Constants.CHARSET_UTF8)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bytes; } private static String byte2hex(byte[] bytes) { StringBuilder sign = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() == 1) { sign.append("0"); } sign.append(hex.toUpperCase()); } return sign.toString(); } public abstract class Constants { public static final String CHARSET_UTF8 = "UTF-8"; } public static void main(String[] args) throws UnsupportedEncodingException, IOException { String str = "test_string"; byte[] bytes = encryptHMAC(str,"test_key"); String data = byte2hex(bytes); System.out.println(data); } }
java的输出结果
引用
3FD9B6B4901DAF25BFB9DAA0718B3698
补充一下:
如果不用secret key直接MD5的话,调用下面ruby代码即可。
Digest::MD5.hexdigest('test_string').upcase => "3474851A3410906697EC77337DF7AAE4"
MD5方面的库还是比较多的,Openssl里面也有