MD5+Salt值

时间:2021-08-16 23:50:33

生成Salt值

package util;

import java.util.Random;

public class Salt {

    public String getSalt()
{
Random random = new Random();
StringBuilder sBuilder = new StringBuilder(16);
sBuilder.append(random.nextInt(99999999)).append(random.nextInt(99999999));
int len = sBuilder.length();
if (len < 16) {
for (int i = 0; i < 16 - len; i++) {
sBuilder.append("0");
}
}
String salt = sBuilder.toString();
return salt;
}
}

MD5:

package util;

import java.security.MessageDigest;

import org.apache.commons.codec.binary.Hex;

public class MD5 {

    //使用Apache的Hex类实现Hex(16进制字符串和)和字节数组的互转
private static String md5Hex(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(str.getBytes()); //
return new String(new Hex().encode(digest));
// } catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
return "";
}
}
/**
* 简单的MD5加密
* @param password
* @return
*/
public String getEsayStrMD5(String password) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte strTemp[] = password.getBytes("UTF-8");
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte md[] = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 15];
str[k++] = hexDigits[byte0 & 15];
}
// return new String(str);
// } catch (Exception e) {
return null;
}
}
/**
* 获取的salt和
* @param password
* @param salt
* @return
*/
public String getSaltMD5(String password,String salt) { //System.out.println(password);
password = md5Hex(password + salt);
//System.out.println(password);
char[] cs = new char[48];
for (int i = 0; i <48 ; i += 3)
{
cs[i] = password.charAt(i / 3 * 2);
char c = salt.charAt(i / 3);
cs[i + 1] = c;
cs[i + 2] = password.charAt(i / 3 * 2 + 1); }
return String.valueOf(cs);
}
}

Salt与MD5合并加密并验证

package util;

public class MD5_Salt {  

    public String get_MD5Salt(String password,String salt1,String salt2)
{ MD5 md5 =new MD5();
String password1=md5.getSaltMD5(password, salt1);
String dbpassword =md5.getSaltMD5(password1, salt2);
return dbpassword; }
public boolean TF_Password_DBpassword(String password, String dbpassword,String salt1,String salt2)
{
int i=0;
MD5 md5 =new MD5();
password=md5.getSaltMD5(password, salt1);
String dbpassword1 =md5.getSaltMD5(password, salt2);
if(dbpassword1.equals(dbpassword))
{
i=1;
} if(i==0)
{
return false;
}
else
{
return true;
} }
}