import java.nio.charset.StandardCharsets; import java.util.Base64; public class Base64Example { public static void main(String[] args) { String originalString = "oa:123456"; // 使用Base64編碼器 Base64.Encoder encoder = Base64.getEncoder(); // 將字串轉換為位元組陣列 byte[] encodedBytes = encoder.encode(originalString.getBytes(StandardCharsets.UTF_8)); // 將位元組陣列轉換為字串 String encodedString = new String(encodedBytes, StandardCharsets.UTF_8); System.out.println("原始字串: " + originalString); System.out.println("Base64 編碼後: " + encodedString); Base64.Decoder decoder = Base64.getDecoder(); byte[] decodedBytes = decoder.decode(encodedString); // 將解碼後的位元組陣列轉換為字串 String decodedString = new String(decodedBytes, StandardCharsets.UTF_8); System.out.println("原始字串: " + decodedString); } }
<dependencies> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.7</version> </dependency> </dependencies> import cn.hutool.core.codec.Base64; import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.StrUtil; public class Base64Example2 { public static void main(String[] args) { String originalString = "oa:123456"; System.out.println(originalString); byte[] plain = StrUtil.bytes(originalString, CharsetUtil.CHARSET_UTF_8); String cipherText = Base64.encode(plain); System.out.println(cipherText); byte[] encData = Base64.decode(cipherText); String encStr = StrUtil.str(encData, CharsetUtil.CHARSET_UTF_8); System.out.println(encStr); } }
public static String getBase64Str(String originalString) { java.util.Base64.Encoder encoder = java.util.Base64.getEncoder(); byte[] encodedBytes = encoder.encode(originalString.getBytes(StandardCharsets.UTF_8)); return new String(encodedBytes); } public static String getOriginalStr(String base64Str) { java.util.Base64.Decoder decoder = java.util.Base64.getDecoder(); byte[] decodedBytes = decoder.decode(base64Str); return new String(decodedBytes, StandardCharsets.UTF_8); }