服务器之家

服务器之家 > 正文

Java实现SHA1加密代码实例

时间:2021-05-17 15:06     来源/作者:花2不谢

微信接入中需要用到sha1的算法。java版的sha1加密如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
 * 微信公众平台(java) sdk
 *
 * copyright (c) 2016, ansitech network technology co.,ltd all rights reserved.
 * http://www.ansitech.com/weixin/sdk/
 *
 * licensed under the apache license, version 2.0 (the "license");
 * you may not use this file except in compliance with the license.
 * you may obtain a copy of the license at
 *
 *   http://www.apache.org/licenses/license-2.0
 *
 * unless required by applicable law or agreed to in writing, software
 * distributed under the license is distributed on an "as is" basis,
 * without warranties or conditions of any kind, either express or implied.
 * see the license for the specific language governing permissions and
 * limitations under the license.
 */
package com.levi.utils;
 
import java.security.messagedigest;
 
/**
 * <p>title: sha1算法</p>
 *
 * @author levi
 */
public final class sha1 {
 
  private static final char[] hex_digits = {'0', '1', '2', '3', '4', '5',
              '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
 
  /**
   * takes the raw bytes from the digest and formats them correct.
   *
   * @param bytes the raw bytes from the digest.
   * @return the formatted bytes.
   */
  private static string getformattedtext(byte[] bytes) {
    int len = bytes.length;
    stringbuilder buf = new stringbuilder(len * 2);
    // 把密文转换成十六进制的字符串形式
    for (int j = 0; j < len; j++) {
      buf.append(hex_digits[(bytes[j] >> 4) & 0x0f]);
      buf.append(hex_digits[bytes[j] & 0x0f]);
    }
    return buf.tostring();
  }
 
  public static string encode(string str) {
    if (str == null) {
      return null;
    }
    try {
      messagedigest messagedigest = messagedigest.getinstance("sha1");
      messagedigest.update(str.getbytes());
      return getformattedtext(messagedigest.digest());
    } catch (exception e) {
      throw new runtimeexception(e);
    }
  }
}

如果需要做微信接入,直接把上面的复制新建一个类即可使用,我自己做好的,测试微信接入成功。

原文链接:https://blog.csdn.net/qq_25821067/article/details/53643365

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部