Java實(shí)現(xiàn)SHA1加密代碼實(shí)例
更新時(shí)間:2018年07月17日 08:16:20 作者:花2不謝
這篇文章給大家分享了Java實(shí)現(xiàn)SHA1加密的相關(guān)實(shí)例代碼,有興趣的朋友可以測試參考下。
微信接入中需要用到SHA1的算法。Java版的SHA1加密如下:
/*
* 微信公眾平臺(tái)(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);
// 把密文轉(zhuǎn)換成十六進(jìn)制的字符串形式
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);
}
}
}
如果需要做微信接入,直接把上面的復(fù)制新建一個(gè)類即可使用,我自己做好的,測試微信接入成功。
相關(guān)文章
SpringBoot使用MapStruct生成映射代碼的示例詳解
MapStruct 是一個(gè)用于 Java 的代碼生成器,專門用于生成類型安全的 bean 映射代碼,它通過注解處理器在編譯時(shí)生成映射代碼,從而避免了運(yùn)行時(shí)的性能開銷和潛在的錯(cuò)誤,本文給大家介紹了SpringBoot使用MapStruct生成映射代碼的示例,需要的朋友可以參考下2024-11-11
SpringBoot WebSocket實(shí)時(shí)監(jiān)控異常的詳細(xì)流程
最近做了一個(gè)需求,消防的設(shè)備巡檢,如果巡檢發(fā)現(xiàn)異常,通過手機(jī)端提交,后臺(tái)的實(shí)時(shí)監(jiān)控頁面實(shí)時(shí)獲取到該設(shè)備的信息及位置,然后安排員工去處理。這篇文章主要介紹了SpringBoot WebSocket實(shí)時(shí)監(jiān)控異常的全過程,感興趣的朋友一起看看吧2021-10-10
SpringBoot基于SpringSecurity表單登錄和權(quán)限驗(yàn)證的示例
這篇文章主要介紹了SpringBoot基于SpringSecurity表單登錄和權(quán)限驗(yàn)證的示例。文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
Mybatis-Plus主鍵插入null值報(bào)錯(cuò)問題及解決
這篇文章主要介紹了Mybatis-Plus主鍵插入null值報(bào)錯(cuò)問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
Java字節(jié)碼增強(qiáng)技術(shù)知識(shí)點(diǎn)詳解
在本篇文章里小編給大家整理的是一篇關(guān)于Java字節(jié)碼增強(qiáng)技術(shù)知識(shí)點(diǎn)詳解內(nèi)容,有興趣的朋友可以跟著學(xué)習(xí)下。2021-08-08

