import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Encryption {
/**
* 静态方法的返回值必须是静态变量
*/
static String encryptedPassword;
/**
* @param password 在其他类中调用该方法,将需要加密的字符串作为参数传进来
* @return 将字符串加密后得到的字符串返回
*/
public static String getEncryption(String password) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA");
messageDigest.update(password.getBytes());
encryptedPassword = new BigInteger(messageDigest.digest()).toString(32);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return encryptedPassword;
}
}
笔记:
- 静态方法在声明的同时会被自动分配内存,因此可以直接在其他类中使用类名调用,例如在
Register
类中对用户密码进行加密。
public class Register extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
/* 对用户提交的明文密码进行加密后得到密文 */
password = Encryption.getEncryption(password);
}
}
MessageDigest
类提供消息摘要算法,如MD5
和SHA
等,信息摘要算法是安全的单向哈希函数,接收任意长度的数据,输出固定长度的哈希值。public static MessageDigest getInstance(String algorithm,String provider) throws NoSuchAlgorithmException, NoSuchProviderException
方法返回消息摘要对象实现指定的消息摘要算法。- 字符串调用
public byte[] getBytes()
方法使用平台默认字符集将字符串编码为byte
序列,并将结果存储在一个新的byte
数组中返回. MessageDigest
对象调用public void update(byte[] input)
方法使用指定的byte[]
更新摘要。public byte[] digest()
是用于产生散列值字符数组的方法。BigInteger(byte[] val)
将byte[]
转换成大数,BigInteger
类支持任意精度的整数,toString()
将数字转换成字符串。