import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; import java.util.Base64; public class Base64Test { private static final String UTF8 = StandardCharsets.UTF_8.name(); @Test public void testBase64() throws Exception{ /** * 首先利用jdk自带的base64 */ String str = "this is content,这是需要需要加密的报文"; String encode = Base64.getEncoder().encodeToString(str.getBytes(UTF8)); System.out.println("base64编码后的数据: " + encode); System.out.println("============解码============"); byte[] decode = Base64.getDecoder().decode(encode.getBytes(UTF8)); System.out.println("解码:" + new String(decode,UTF8)); } }
使用依赖的工具类进行编码,首先需要引入jar
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </dependency>
@Test public void testCommonsCodec() throws Exception{ /** * 首先利用jdk自带的base64 */ String str = "this is content,这是需要需要加密的报文"; String s = org.apache.commons.codec.binary.Base64.encodeBase64String(str.getBytes(UTF8)); System.out.println("加密后的数据: " + s); System.out.println("======================="); byte[] decodeBase64 = org.apache.commons.codec.binary.Base64.decodeBase64(s.getBytes(UTF8)); System.out.println("解码后的数据: " + new String(decodeBase64,UTF8)); }
** 可以发现:两种实现方式加密的密文是一样的。** 3. 为什么要叫base64? 因为加密之后的密文总是由64个字符组成的.