注:内容来源于上课笔记,如有侵权请联系删除!
二、MD5加密码
public class MD5Util {
public static String encode(String str) {
// 定义一个字节数组
byte[] secretBytes = null;
try {
// 创建MD5加密算法实例
MessageDigest md = MessageDigest.getInstance("MD5");
// 加密字符串
md.update(str.getBytes());
// 获取加密后的数据
secretBytes = md.digest();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("没有md5这个算法!");
}
// 将加密后的数据转换为16进制数字
String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
// 如果生成数字未满32位,需要前面补0
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code = "0" + md5code;
}
return md5code.toUpperCase();
}
public static boolean equals(String newPasswd, String oldPasswd) {
return encode(newPasswd).equalsIgnoreCase(oldPasswd) ? true : false;
}
public static void main(String[] args) {
System.out.println(MD5Util.encode("123"));
System.out.println(MD5Util.equals("123", "202cb962ac59075b964b07152d234b70"));
}
}
三、验证码
1、简介
1)作用
防止恶意破解密码、刷票、论坛灌水、刷页等。
2)分类
图片
手机短信
2、实现
1)自定义
第一:编写Servlet程序,生成验证码
/**
* 生成验证码
*/
@WebServlet("/code.jpg")
public class CheckCode extends HttpServlet {
private static final long serialVersionUID = 1L;
// 设置字母的大小,大小
private Font mFont = new Font("Times New Roman", Font.PLAIN, 17);
// 随机产生颜色
Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置头信息:设置页面不缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 表明生成的响应是图片
response.setContentType("image/jpeg");
//在内存中创建图象
int width = 100, height = 18;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
//实例化随机类对象
Random random = new Random();
// 设定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(1, 1, width - 1, height - 1);
// 画边框
g.setColor(new Color(102, 102, 102));
g.drawRect(0, 0, width - 1, height - 1);
// 设置字体、颜色
g.setFont(mFont);
g.setColor(getRandColor(160, 200));
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width - 1);
int y = random.nextInt(height - 1);