咸鱼

咸鱼是以盐腌渍后,晒干的鱼

0%

Java和Android的Base64加密解密

Java8

Java8上的自带Base64工具 java.util.Base64;

1
2
3
4
5
6
//编码
Base64.getEncoder().encodeToString("Hello".getBytes("utf-8"));

//解码
byte[] asBytes = Base64.getDecoder().decode("SGVsbG8=");
System.out.println(new String(asBytes, "utf-8"));

Android

Android SDK 自带 android.util.Base64;

| Public methods |
| ———- | — |
| static byte[] | decode(String str, int flags) Decode the Base64-encoded data in input and return the data in a new byte array. |
| static byte[] | decode(byte[] input, int flags) Decode the Base64-encoded data in input and return the data in a new byte array. |
| static byte[] | decode(byte[] input, int offset, int len, int flags) Decode the Base64-encoded data in input and return the data in a new byte array. |
| static byte[] | encode(byte[] input, int flags) Base64-encode the given data and return a newly allocated byte[] with the result. |
| static byte[] | encode(byte[] input, int offset, int len, int flags) Base64-encode the given data and return a newly allocated byte[] with the result. |
| static String | encodeToString(byte[] input, int offset, int len, int flags) Base64-encode the given data and return a newly allocated String with the result. |
| static String | encodeToString(byte[] input, int flags) Base64-encode the given data and return a newly allocated String with the result. |

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import android.util.Base64;

//编码
public static String getEncoder(String str) throws UnsupportedEncodingException {

//return Base64.encodeToString(str.getBytes("utf-8"),Base64.DEFAULT);
//android sdk 27
return Base64.encode(str.getBytes("utf-8"),Base64.DEFAULT);
}

//解码
public static String getDecoder(String encode) throws UnsupportedEncodingException {

byte[] asBytes = Base64.decode(encode,Base64.DEFAULT);
return new String(asBytes, "utf-8");
}