Base64工具类:
package com.example.demo.util;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
public class Base64 {
//文件转字符串
public static String file2String(File file) {
try {
BufferedReader buffer = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String temp;
while((temp = buffer.readLine()) !=null ){
sb.append(temp);
}
return sb.toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
//加密
public static String setEncryptionBase64(String str){
byte[] b = null;
String s = null;
try {
b = str.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if( b != null){
s = new BASE64Encoder().encode(b);
}
return s;
}
//解密
public static String getDecodeBase64(String str){
byte[] b = null;
String result = null;
if(str != null){
BASE64Decoder decoder = new BASE64Decoder();
try {
b = decoder.decodeBuffer(str);
result = new String(b, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
String phone ="15823562145";
String base64 = Base64.setEncryptionBase64(phone);
System.out.println("加密后:"+base64);
String fromBase64 = Base64.getDecodeBase64(base64);
System.out.println("解密后:"+fromBase64);
}
}
测试结果如下:
加密后:MTU4MjM1NjIxNDU=
解密后:15823562145
全部评论