实验4 MD5加密的Java实现
一、实验目的
通过实验了解MD5加密的原理,掌握Java语言MD5加密的实现。
二、实验原理
1.哈希(Hash)函数的定义
实现数字签名或计算消息的鉴别码。
以任意长度的消息作为输入,输出一个固定长度的二进制值,称为哈希值或消息摘要。
2.MD(Message Digest)消息摘要
MD5对任意输入的消息计算一个128位的固定长度的值
三、实验环境
开发工具:JDK、Eclipse或JCreator
参考资料:JDK API文档
java.security包
MessageDigest类
四、实验内容和任务
(1)注册时输入用户名和密码,把密码进行MD5加密后保存在变量里;
(2)登录时,输入用户名和密码,把密码进行MD5加密后,和注册时保存的用户名和密码比较,判断是否登录成功。
五、实验过程
1、核心模块
public static String makeMD5(String password) {
MessageDigest md;
try {
// 生成一个MD5加密计算摘要
md = MessageDigest.getInstance("MD5");
// 计算md5函数
md.update(password.getBytes());
// digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
// BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
String pwd = new BigInteger(1, md.digest()).toString(16);
//System.err.println(pwd);
return pwd;
} catch (Exception e) {
e.printStackTrace();
}
return password;
}
2、完整程序
public class MD5 {
/**@author chenguanghong
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String password="";
String account="";
System.out.print("注册\n用户名:");
Scanner inaccount = new Scanner(System.in);
account=inaccount.nextLine();
System.out.print("密码:");
Scanner inpassword = new Scanner(System.in);
password=inpassword.nextLine();
password=makeMD5(password);
String password2="";
String account2="";
System.out.print("\n\n登录\n用户名:");
Scanner inaccount2 = new Scanner(System.in);
account2=inaccount2.nextLine();
System.out.print("密码:");
Scanner inpassword2 = new Scanner(System.in);
password2=inpassword2.nextLine();
password2=makeMD5(password2);
if(account.equals(account2)&&password.equals(password2))
{
System.out.println("登录成功!!!");
System.out.println("密文:"+makeMD5(password));
}
else
{
System.out.println("登录失败!!!");
}
//System.out.println("密文:"+makeMD5(password));
}
public static String makeMD5(String password) {
MessageDigest md;
try {
// 生成一个MD5加密计算摘要
md = MessageDigest.getInstance("MD5");
// 计算md5函数
md.update(password.getBytes());
// digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
// BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
String pwd = new BigInteger(1, md.digest()).toString(16);
//System.err.println(pwd);
return pwd;
} catch (Exception e) {
e.printStackTrace();
}
return password;
}
}
六、实验结果
登陆成功的结果
登陆失败的结果
七、实验小结
通过本次实验,我对MD5加密的原理有了一定了解,并且掌握通过Java语言实现MD5加密。