package com.jqyd.app;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 利用MD5进行加密
*
* @param str
* 待加密的字符串
* @return 加密后的字符串
* @throws NoSuchAlgorithmException
* 没有这种产生消息摘要的算法
* @throws UnsupportedEncodingException
*/
public class Encrypt {
public static String EncoderByMd5(String str) {
StringBuffer buf = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte b[] = md.digest();
int i;
buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
System.out.println("result: " + buf.toString());// 32位的加密
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return buf.toString();
}
// 可逆的加密算法
public static String encryptmd5(String str) {
char[] a = str.toCharArray();
for (int i = 0; i < a.length; i++) {
a[i] = (char) (a[i] ^ 'l');
}
String s = new String(a);
System.out.println("pwd encryptmd5:::" + s);
return s;
}
/**
* 判断用户密码是否正确
*
* @param newpasswd
* 用户输入的密码
* @param oldpasswd
* 数据库中存储的密码--用户密码的摘要
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
public static boolean checkpassword(String newpasswd, String oldpasswd)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
if (EncoderByMd5(newpasswd).equals(oldpasswd))
return true;
else
return false;
}
}