MD5的使用

来源:互联网 发布:mac 关闭已打开的程序 编辑:程序博客网 时间:2024/05/20 07:35
         MD5的使用

在Android系统中,一些重要的文件信息不想被别人获取到,那就可以使用加密技术来加密,让别人不能够轻易的获取你的信息,而常用的是MD5加密:
下面是MD5的一个工具类:

public class MD5Utils {
/**
* 采用md5加密算法,不可逆
* @param text
* @return
*/
public static String encode(String text){
try {
MessageDigest digest=MessageDigest.getInstance("md5"); //这里也可以使用sha-1
byte[] result=digest.digest(text.getBytes());
StringBuffer sb=new StringBuffer();
for(byte b:result){
String hex=Integer.toHexString(b&0xff)+2; //这里加上不同的数字,哈希码不一样,术语:加盐
if(hex.length()==1){
sb.append("0");
}
sb.append(hex);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
}
}
//获取目录下文件的MD5
public static String encodeMD5(URL url){
File file=new File(url);
MessageDigest digest=MessageDigest.getInstance("md5");
FileInputStream fis=new FileInputStream(file);
byte[] buffer=new byte[1024];
int len=0;
while((len=fis.read(buffer))!=-1){
digest.update(buffer, 0, len);
}
byte [] result=digest.digest();
StringBuffer sb=new StringBuffer();
for(byte b:result){
String str=Integer.toHexString(b&0xff);
if(str.length()==1){
sb.append("0");
}
sb.append(str);
}
String md5=sb.toString();
 
}
}

0 0