如题,现在和第三方合作做一个应用,对方要求我们的数据用hmac-sha1算法加密据,给了个PHP的例子,hash_hmac()函数,但是我找不到相应的java实现,哪位前辈给一个实现。

解决方案 »

  1.   

    hash_hmac()函数的实现贴一下 
    不然怎么知道
      

  2.   

    找到方法了
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    public class HMACSHA1 {   
     
       private static final String HMAC_SHA1 = "HmacSHA1";   
      
        /**  
         * 生成签名数据  
         *   
         * @param data 待加密的数据  
          * @throws InvalidKeyException  
         * @throws NoSuchAlgorithmException  
         */  
        public static String getSignature(String data) throws Exception{
         byte[] key=QConstant.APP_SECRET.getBytes();
         //byte[] key="myappsecret".getBytes();
            SecretKeySpec signingKey = new SecretKeySpec(key, HMAC_SHA1);   
            Mac mac = Mac.getInstance(HMAC_SHA1);   
            mac.init(signingKey);   
            byte[] rawHmac = mac.doFinal(data.getBytes());
            StringBuilder sb=new StringBuilder();
            for(byte b:rawHmac){
             sb.append(byteToHexString(b));
            }
            //System.out.println("sb:"+sb.toString());
            return sb.toString();   
        }
        
        private static String byteToHexString(byte ib){
         char[] Digit={
         '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'
         };
         char[] ob=new char[2];
         ob[0]=Digit[(ib>>>4)& 0X0f];
         ob[1]=Digit[ib & 0X0F];
         String s=new String(ob);
         return s;
            
            
        }
        
        public static void main(String[] args) throws Exception{
         String s=HMACSHA1.getSignature("app_id=10001app_lang=2052app_nonce=nonceapp_ts=1287729243");
         System.out.println(s);
         if(s.equals("2319fcb6d60dd30119c1e0ff9e25e1a6cc86d72f")){
         System.out.println(true);
         }
         //System.out.println(s);
         /*String ss="aaaa";
         byte[] bb=ss.getBytes();
         String kk=new String(bb,"utf-8");
         System.out.println("bb:"+kk);*/
         /*String ss="aaa";
         byte[] bb=ss.getBytes();
         for(byte b:bb){
         System.out.println(b);
         }*/
        
    }
     }