Java實現(xiàn)SHA1加密代碼實例
更新時間:2018年07月17日 08:16:20 作者:花2不謝
這篇文章給大家分享了Java實現(xiàn)SHA1加密的相關實例代碼,有興趣的朋友可以測試參考下。
微信接入中需要用到SHA1的算法。Java版的SHA1加密如下:
/*
* 微信公眾平臺(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);
}
}
}
如果需要做微信接入,直接把上面的復制新建一個類即可使用,我自己做好的,測試微信接入成功。
相關文章
SpringBoot使用MapStruct生成映射代碼的示例詳解
MapStruct 是一個用于 Java 的代碼生成器,專門用于生成類型安全的 bean 映射代碼,它通過注解處理器在編譯時生成映射代碼,從而避免了運行時的性能開銷和潛在的錯誤,本文給大家介紹了SpringBoot使用MapStruct生成映射代碼的示例,需要的朋友可以參考下2024-11-11
SpringBoot WebSocket實時監(jiān)控異常的詳細流程
最近做了一個需求,消防的設備巡檢,如果巡檢發(fā)現(xiàn)異常,通過手機端提交,后臺的實時監(jiān)控頁面實時獲取到該設備的信息及位置,然后安排員工去處理。這篇文章主要介紹了SpringBoot WebSocket實時監(jiān)控異常的全過程,感興趣的朋友一起看看吧2021-10-10
SpringBoot基于SpringSecurity表單登錄和權限驗證的示例
這篇文章主要介紹了SpringBoot基于SpringSecurity表單登錄和權限驗證的示例。文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09

