java实现HMACSHA256加密签名

java实现HMACSHA256加密签名,需要按照字典排序的朋友可以用
SortedMap<Object, Object> message=new TreeMap<Object, Object>();进行排序后在加密。


/**

* @version 1.0
* @project: autoTrade 
* @author: QC班长 
* @date:2017/8/3 
* @time:10:17 
*/

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;
public class HMACSHA256 { 
 //   SECRET KEY    
 private final static String secret_key = "ndE2jdZNFixH9G6Aidsfyf7lYT3PxW";  
  /**     
  * 将加密后的字节数组转换成字符串   
  *    
  * @param b 字节数组    
  * @return 字符串     
  */   
 private static String byteArrayToHexString(byte[] b) {  
      StringBuilder hs = new StringBuilder();     
      String stmp;      
  for (int n = 0; b!=null && n < b.length; n++) {   
         stmp = Integer.toHexString(b[n] & 0XFF);    
         if (stmp.length() == 1)           
         hs.append('0');      
         hs.append(stmp);    
    }      
   return hs.toString().toLowerCase();   
 }   

 /**   
  * sha256_HMAC加密    
  * @param message 消息   
  * @param secret  秘钥 
  * @return 加密后字符串  
  */  
  private static String sha256_HMAC(String message, String secret) {     
   String hash = "";      
   try {         
       Mac sha256_HMAC = Mac.getInstance("HmacSHA256");     
       SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");      
       sha256_HMAC.init(secret_key);       
       byte[] bytes = sha256_HMAC.doFinal(message.getBytes());   
       hash = byteArrayToHexString(bytes);         
       System.out.println(hash);    
       } catch (Exception e) {     
       System.out.println("Error HmacSHA256 ===========" + e.getMessage());   
     }       
    return hash;   
   }     
 }

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

QC班长

班长有话说:要是有瓶水喝就好了

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值