java base64
时间: 2023-11-10 12:53:45 浏览: 120
Base64是一种常用的编码方法,用于将二进制数据表示为可打印字符。在Java中,有多种方式可以进行Base64的加密和解密操作。可以使用sun.misc.BASE64Encoder和sun.misc.BASE64Decoder类进行加密和解密操作,也可以使用com.sun.org.apache.xerces.internal.impl.dv.util.Base64类进行相同的操作。以下是使用这两种方式进行Base64编码和解码的示例代码:
方法一:
```java
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
public class Base64 {
public static void main(String[] args) {
System.out.println(Base64.getBase64Encode("你们好!!!"));
System.out.println(Base64.getBase64Decode("5L2g5Lus5aW977yB77yB77yB"));
}
// 加密
public static String getBase64Encode(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 getBase64Decode(String s) {
byte[] b = null;
String result = null;
if (s != null) {
BASE64Decoder decoder = new BASE64Decoder();
try {
b = decoder.decodeBuffer(s);
result = new String(b, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
}
```
方法二:
```java
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
public class Base64Demo {
public static void main(String[] args) {
// 加密
System.out.println(Base64Demo.getBase64Encode("Hello,World!"));
// 解密
System.out.println(Base64Demo.getBase64Decode("SGVsbG9Xb3JsZA=="));
}
public static String getBase64Encode(String str) {
if (str == null || "".equals(str)) {
return "";
}
try {
byte[] bt = str.getBytes("UTF-8");
str = String.valueOf(Base64.encode(bt));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
public static String getBase64Decode(String str) {
if (str == null || "".equals(str)) {
return "";
}
char[] ch = str.toCharArray();
byte[] bt = Base64.decode(String.valueOf(ch));
try {
str = new String(bt,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
}
```
阅读全文