Java实现SHA1加密代码实例

网友投稿 254 2023-01-25


Java实现SHA1加密代码实例

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

/*

* 微信公众平台(JAVA) SDK

*

* Copyright (c) 2016, Ansitech Network Technology Co.,Ltd All rights reserved.

* http://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://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;

/**

*

Title: SHA1算法

*

* @author levihttp://

*/

public final clhttp://ass 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);

}

}

}

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:嵌入式接口自动化测试工具(嵌入式接口自动化测试工具)
下一篇:spring+maven实现发送邮件功能
相关文章

 发表评论

暂时没有评论,来抢沙发吧~