随着或联网的飞速发展,计算机病毒泛滥多达250万种,黑客也是多如牛毛,为了在数据传输过程中不被非法分子利用,程序的安全性显得格外重要,最近了解了有关Md5加密的有关用法,在此总结一下,希望大家共同探讨,共同学习开发出安全的程序!
方法一:使用Java自带类security来实现数据加密
eg:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5{
public static void main(String args[])
{
Md5 d=new Md5();
String str="123456789";
String string=d.getMD5Str(str);
ystem.out.println("加密前数据为"+ str +"加密后数据为"+string);
}
private String getMD5Str(String str) {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(str.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
System.out.println("NoSuchAlgorithmException caught!");
System.exit(-1);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] byteArray = messageDigest.digest();
StringBuffer md5StrBuff = new StringBuffer();
for (int i = 0; i < byteArray.length; i++) {
if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
else
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
}
return md5StrBuff.toString();
}
}
输出结果为:加密前数据为123456789加密后数据为25f9e794323b453885f5181f1b624d0b
方法二:用自己的算法加密
eg:
package com.yaox;
import java.security.MessageDigest;
public class Test_MD5{
public static void main(String args[])
{
String str="123456789";
String s=MD5(str);
System.out.println("加密前数据为"+ str +"加密后数据为"+s);
}
private final static String MD5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] strTemp = s.getBytes();
//使用MD5创建MessageDigest对象
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 b = md[i];
//System.out.println((int)b);
//将没个数(int)b进行双字节加密
str[k++] = hexDigits[b >> 4 & 0xf];
str[k++] = hexDigits[b & 0xf];
}
return new String(str);
} catch (Exception e) {return null;}
}
}
输出结果为:package com.yaox;
import java.security.MessageDigest;
public class Test_MD5{
public static void main(String args[])
{
String str="123456789";
String s=MD5(str);
System.out.println("加密前数据为"+ str +"加密后数据为"+s);
}
private final static String MD5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] strTemp = s.getBytes();
//使用MD5创建MessageDigest对象
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 b = md[i];
//System.out.println((int)b);
//将没个数(int)b进行双字节加密
str[k++] = hexDigits[b >> 4 & 0xf];
str[k++] = hexDigits[b & 0xf];
}
return new String(str);
} catch (Exception e) {return null;}
}
}
输出结果为:加密前数据为123456789加密后数据为25f9e794323b453885f5181f1b624d0b