Posted on 2010-02-09 13:13
疯狂 阅读(2559)
评论(1) 编辑 收藏 所属分类:
java安全
package com.test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
//使用md5和盐验证安全登陆
public class Test_MD5 {
private static final String PWD_FILE = "c:\\pwd.txt";
/**
* @param args
*/
public static void main(String[] args) throws Exception{
//用户创建密码,服务端杂凑并保存
saveMessagePwdInFile("admin");
////验证用户输入
checkUserPwd("admin1");
}
public static void saveMessagePwdInFile(String inputPwd)throws Exception{
byte[] salt = new byte[8];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
System.out.println("生成的盐:"+Arrays.toString(salt));
MessageDigest digest = MessageDigest.getInstance("MD5");//当然可以使用SHA(160位),MD5(128位)
digest.update(salt);
digest.update(inputPwd.getBytes("utf-8"));
byte[] afterMd5 = digest.digest();
System.out.println("杂凑值:"+Arrays.toString(afterMd5));
//盐和杂凑值写入文件
FileOutputStream outputStream = new FileOutputStream(new File(PWD_FILE));
FileChannel channel = outputStream.getChannel();
channel.write(ByteBuffer.wrap(salt));
channel.write(ByteBuffer.wrap(afterMd5));
outputStream.flush();
outputStream.close();
System.out.println("保存信息完毕...");
}
public static void checkUserPwd(String pwd)throws Exception{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
FileInputStream fileInputStream = new FileInputStream(new File(PWD_FILE));
FileChannel channel2 = fileInputStream.getChannel();
ByteBuffer dst = ByteBuffer.allocate(1024);
int l = -1;
while((l=channel2.read(dst))!=-1){
dst.flip();
byteArrayOutputStream.write(dst.array(),0,l);
dst.compact();
dst.clear();
}
fileInputStream.close();
byte[] pwdbyte = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.reset();
byte[] salt2 = new byte[8];
System.arraycopy(pwdbyte, 0, salt2, 0, 8);
System.out.println("从文件获取盐:"+Arrays.toString(salt2));
byte[] pwdinfile = new byte[pwdbyte.length-8];
System.arraycopy(pwdbyte, 8, pwdinfile, 0, pwdbyte.length-8);
System.out.println("从文件获取杂凑值:"+Arrays.toString(pwdinfile));
byte[] toyz = getUserMd5Pwd(salt2,pwd);
System.out.println(Arrays.equals(toyz, pwdinfile)==true?"登陆成功":"密码有误,登录失败...");
}
public static byte[] getUserMd5Pwd(byte[] salt,String pwd) throws Exception{
MessageDigest digest2 = MessageDigest.getInstance("MD5");
digest2.update(salt);
digest2.update(pwd.getBytes("utf-8"));
byte[] toyz = digest2.digest();
System.out.println("用户输入杂凑值:"+Arrays.toString(toyz));
return toyz;
}
}