注意的地方:java
Base64Encoder,Base64Decoder並不屬於JDK標準庫範疇,可是又包含在了JDK中算法
解決方法:按照以下方法設置Eclipse導入%JAVA_HOME%\jre\lib目錄下的rt.jar包便可,Project->Properties,選擇Java Build Path設置項,再選擇Libraries標籤,Add External Jars添加%JAVA_HOME%\jre\lib\rt.jar就能夠使用啦!數組
若是在使用BASE64Decoder時遇到了這種狀況:Access restriction : The type BASE64Decoder is not accessible due to restriction on required library C:\Program
files\java\jre6\lib\rt.jar ,只須要在project build path中先移除JRE System Library,再添加庫JRE System Library就好了dom
具體代碼以下:ui
package leetcode; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.UUID; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class Test12 { public static String getId(){ //UUID java中不重複序列 String id = UUID.randomUUID().toString(); //System.out.println(id); //獲得的這個序列號很長,能夠用哈希碼來表示 int hashCode = Math.abs(id.hashCode()); return hashCode+""; } //md5加密算法,單向加密,沒有解密的 public static String md5(String str){ byte[] bytes = null; try { bytes = MessageDigest.getInstance("md5").digest(str.getBytes());//獲得MD5的實例,再將字符串加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return new BigInteger(1,bytes).toString(16);//把字節數組轉化爲正的bigInteger,而後變成16進製表示 } //base64算法,解密,加密 public static String base64Encode(String str){ BASE64Encoder baseEncode = new BASE64Encoder(); return baseEncode.encode(str.getBytes());//加密 } public static String base64Decode(String str){ BASE64Decoder baseDecoder = new BASE64Decoder(); try { return new String(baseDecoder.decodeBuffer(str));//解密 } catch (IOException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { System.out.println(getId()); System.out.println("1234加密後:"+md5("1234")); String str = base64Encode("1234"); System.out.println("1234加密後:"+str); System.out.println("解密後:"+base64Decode(str)); } }
運行結果以下:加密
888859973
1234加密後:81dc9bdb52d04dc20036dbd8313ed055
1234加密後:MTIzNA==
解密後:1234spa