加密算法分类
1:单向不可逆加密(MD5,SHA1) 只能加密,不能解密
明文(123456)—> 散列函数(hash)—>32位或64位的字符串(0ef89gh67yyy…)
可以通过加盐 来解决hash碰撞问题。
使用MD5加密+salt 可以保证安全
2:对称加密算法(AES DES)
双方使用同一把秘钥(加密)和(解密)
客户端
明文—>通过特定的秘钥进行加密---->加密存储的字符串
服务端
加密存储的字符串—>使用特定的秘钥进行解密---->明文
HTTPS协议采用的就是对称加密算法
3:非对称加密算法(RSA ECC)
双方分别使用一把秘钥(公钥、私钥)
客户端
明文---->使用客户端本地的私钥进行加密----->数据到达服务端
---->服务端使用客户端的公钥进行解密----->取到明文
明文----->服务端使用本地的私钥进行加密------>数据到达客户端
----->客户端使用服务端的公钥进行解密------>明文
那么应该怎么使用SHA1加密应用呢?来util
package com.xiupeilian.carpart.util;
/**
* 2016??1??18??
* Chatpay
*
*/
import java.security.MessageDigest;
/*
'============================================================================
'api?????
'createSHA1Sign???????SHA1
'getSha1()Sha1???
'============================================================================
'*/
public class SHA1Util {
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());
str=getFormattedText(messageDigest.digest());
str=str.substring(8, 24);
return str ;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
// System.out.println(SHA1Util.encode("123456"));
System.out.println(SHA1Util.encode("123456"));
}
}
使用方法
vo.setPassword(SHA1Util.encode(vo.getPassword()));