SHA1加密JAVA

  1. /* 
  2.  * 微信公众平台(JAVA) SDK 
  3.  * 
  4.  * Copyright (c) 2016, Ansitech Network Technology Co.,Ltd All rights reserved. 
  5.  * http://www.ansitech.com/weixin/sdk/ 
  6.  * 
  7.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  8.  * you may not use this file except in compliance with the License. 
  9.  * You may obtain a copy of the License at 
  10.  * 
  11.  *      http://www.apache.org/licenses/LICENSE-2.0 
  12.  * 
  13.  * Unless required by applicable law or agreed to in writing, software 
  14.  * distributed under the License is distributed on an "AS IS" BASIS, 
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  16.  * See the License for the specific language governing permissions and 
  17.  * limitations under the License. 
  18.  */  
  19. package com.levi.utils;  
  20.   
  21. import java.security.MessageDigest;  
  22.   
  23. /** 
  24.  * <p>Title: SHA1算法</p> 
  25.  * 
  26.  * @author levi 
  27.  */  
  28. public final class SHA1 {  
  29.   
  30.     private static final char[] HEX_DIGITS = {'0''1''2''3''4''5',  
  31.                            '6''7''8''9''a''b''c''d''e''f'};  
  32.   
  33.     /** 
  34.      * Takes the raw bytes from the digest and formats them correct. 
  35.      * 
  36.      * @param bytes the raw bytes from the digest. 
  37.      * @return the formatted bytes. 
  38.      */  
  39.     private static String getFormattedText(byte[] bytes) {  
  40.         int len = bytes.length;  
  41.         StringBuilder buf = new StringBuilder(len * 2);  
  42.         // 把密文转换成十六进制的字符串形式  
  43.         for (int j = 0; j < len; j++) {  
  44.             buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);  
  45.             buf.append(HEX_DIGITS[bytes[j] & 0x0f]);  
  46.         }  
  47.         return buf.toString();  
  48.     }  
  49.   
  50.     public static String encode(String str) {  
  51.         if (str == null) {  
  52.             return null;  
  53.         }  
  54.         try {  
  55.             MessageDigest messageDigest = MessageDigest.getInstance("SHA1");  
  56.             messageDigest.update(str.getBytes());  
  57.             return getFormattedText(messageDigest.digest());  
  58.         } catch (Exception e) {  
  59.             throw new RuntimeException(e);  
  60.         }  
  61.     }  
  62. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值