一、生成uuid
说明:jdk1.5以后,api才可生成uuid
实现:
import java.util.UUID;
/**
* Document:本类作用---->java获取uuid
* User: yangjf
* Date: 2016/9/21 20:15
*/
public class CreateUUID {
public static void main(String[] args) {
//由于UUID是一个静态方法,可以直接调用
String uuid=UUID.randomUUID().toString();
System.out.println("生成的32位UUID码:"+uuid);
System.out.println("去除分割符号后的UUID:"+uuid.replaceAll("-",""));
System.out.println("去除分割符号后的UUID:"+uuid.replace("-",""));
//获取64位的uuid
System.out.println("uuid64位:"+new StringBuffer().append(UUID.randomUUID().toString().replace("-","")).append(UUID.randomUUID().toString().replaceAll("-","")));
}
}
二、md5加密
说明:本加密生成字符串是32位长度
实现:
import java.security.MessageDigest;
/**
* Document:本类作用---->MD5加密算法
* User: yangjf
* Date: 2016/9/21 22:01
*/
public class Md5Util {
public static void main(String[] args) {
String hello="hello world";
System.out.println("MD5加密后的结果:"+getMD5(hello));
}
public static String getMD5(String str) {
try {
// 生成一个MD5加密计算摘要
MessageDigest md = MessageDigest.getInstance("MD5");
// 计算md5函数
md.update(str.getBytes());
// digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
// BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
return new BigInteger(1, md.digest()).toString(16);
} catch (Exception e) {
throw new SpeedException("MD5加密出现错误");
}
}
}
注:以上测试已经通过,可以直接使用。