一、Maven依赖
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
二、Base64加密工具类
import org.apache.commons.codec.binary.Base64;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Base64Utils {
public static String encodeStr(String plainText) {
byte[] b = plainText.getBytes();
Base64 base64 = new Base64();
b = base64.encode(b);
return new String(b);
}
public static String decodeStr(String encodeStr) {
byte[] b = encodeStr.getBytes();
Base64 base64 = new Base64();
b = base64.decode(b);
return new String(b);
}
public static byte[] decodeStr2byte(String encodeStr) {
byte[] b = encodeStr.getBytes();
Base64 base64 = new Base64();
b = base64.decode(b);
return b;
}
public static String encodeByte(byte[] b) {
Base64 base64 = new Base64();
b = base64.decode(b);
return new String(b);
}
public static Boolean Base64ToImg(String imageBase64, String filePath) {
byte[] buffer;
try {
buffer = Base64.decodeBase64(imageBase64.replace("data:image/png;base64,", "").replace("data:image/jpeg;base64,", "").replace("data:image/gif;base64,", "").replace("data:image/bmp;base64,", ""));
String path = filePath + "/" + System.currentTimeMillis() + ".png";
FileOutputStream out = new FileOutputStream(path);
out.write(buffer);
out.close();
return Boolean.TRUE;
} catch (IOException e) {
e.printStackTrace();
return Boolean.FALSE;
}
}
public static String img2base64(String imgFile) {
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imgFile);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return encodeByte(data);
}
}
三、测试
public class Base64UtilsTest {
public static void main(String[] args) {
String string = "123456";
String s = Base64Utils.encodeStr(string);
System.out.println("加密结果为:" + s);
String s1 = Base64Utils.decodeStr(s);
System.out.println("解密结果为:" + s1);
byte[] bytes = Base64Utils.decodeStr2byte(string);
System.out.println("解码转byte[]数组:" + Arrays.toString(bytes));
}
}