300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > java sha1hash 算法_javaweb使用sha1算法登录加密的整个过程

java sha1hash 算法_javaweb使用sha1算法登录加密的整个过程

时间:2020-07-23 22:15:28

相关推荐

java sha1hash 算法_javaweb使用sha1算法登录加密的整个过程

sha1算法还是比较潮流的算法并且可以简单使用的算法,建议新手可以选用sha1算法。

百度百科对sha1算法的解释:安全哈希算法(Secure Hash Algorithm)主要适用于数字签名标准 (Digital Signature Standard DSS)里面定义的数字签名算法(Digital Signature Algorithm DSA)。对于长度小于2^64位的消息,SHA1会产生一个160位的消息摘要。当接收到消息的时候,这个消息摘要可以用来验证数据的完整性。在传输的过程中,数据很可能会发生变化,那么这时候就会产生不同的消息摘要。 SHA1有如下特性:不可以从消息摘要中复原信息;两个不同的消息不会产生同样的消息摘要,(但会有1x10 ^ 48分之一的机率出现相同的消息摘要,一般使用时忽略)。

下面是使用的过程,

1.首先在前端,对需要传到后端数据进行加密(需要导入sha1.js)

var sha = hex_sha1('helloworld') ;

alert(sha);

提示框加密结果为:07f804138ac308f552b17d7881105a9cb08758ca;

2.在后端对数据进行加密对比

public static String getSha1(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {

if (null == str || str.length() == 0){

return null;

}

char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',

'a', 'b', 'c', 'd', 'e', 'f'};

try {

MessageDigest mdTemp = MessageDigest.getInstance("SHA1");

mdTemp.update(str.getBytes("UTF-8"));

byte[] md = mdTemp.digest();

int j = md.length;

char[] buf = new char[j * 2];

int k = 0;

for (int i = 0; i < j; i++) {

byte byte0 = md[i];

buf[k++] = hexDigits[byte0 >>> 4 & 0xf];

buf[k++] = hexDigits[byte0 & 0xf];

}

return new String(buf);

} catch (Exception e) {

e.printStackTrace();

return null;

}

}

public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {

String data = "helloworld";

String result = getSha1(data);

System.out.println("加密后:"+result);

}

注意如果涉及到中文的话,js和java的结果可不一样。因为js对中文字符串处理为utf-16格式的。而java是utf-8所以我们要对字符串进行转换。代码如下:

function utf16to8(str){

var out, i, len, c;

out = "";

len = str.length;

for(i = 0; i < len; i++){

c = str.charCodeAt(i);

if ((c >= 0x0001) && (c <= 0x007F)) {

out += str.charAt(i);

} else if (c > 0x07FF){

out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));

out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));

out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));

} else {

out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));

out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));

}

}

return out;

}

我是个菜鸟,如果有什么不对或不好的地方欢迎指点。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。