Java 9.0.1中BASE64Encoder/BASE64Decoder无法解析的解决方法
解决Java 9+中BASE64Encoder/BASE64Decoder无法解析的问题
嘿,这个问题我太熟了!Java 9及更高版本直接移除了sun.misc.BASE64Encoder和sun.misc.BASE64Decoder——这俩本来就是Sun的内部API,之前在Java 8就已经被标记为废弃,官方早就不推荐用了。咱们直接换成Java 8开始引入的标准Base64工具类就行,完全兼容且更可靠。
具体修改步骤
1. 替换导入语句
先把原来可能存在的import sun.misc.BASE64Encoder;和import sun.misc.BASE64Decoder;删掉,换成标准库的导入:
import java.util.Base64;
2. 改造加密解密的Base64处理逻辑
结合你给出的DesEncrypter代码片段,我补全并修改了完整的可运行版本,重点替换了Base64相关的调用:
import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Base64; class DesEncrypter { Cipher ecipher; Cipher dcipher; public DesEncrypter(SecretKey key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { ecipher = Cipher.getInstance("DES"); dcipher = Cipher.getInstance("DES"); // 补充初始化加密/解密模式(你原来的代码里漏了这步) ecipher.init(Cipher.ENCRYPT_MODE, key); dcipher.init(Cipher.DECRYPT_MODE, key); } // 方便直接传入密钥字符串的重载构造 public DesEncrypter(String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { this(new SecretKeySpec(key.getBytes(), "DES")); } // 加密字符串返回Base64格式结果 public String encrypt(String str) throws UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException { byte[] utf8Bytes = str.getBytes("UTF8"); byte[] encryptedBytes = ecipher.doFinal(utf8Bytes); // 替换原来的BASE64Encoder.encode return Base64.getEncoder().encodeToString(encryptedBytes); } // 解密Base64格式的字符串 public String decrypt(String encryptedBase64Str) throws IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { // 替换原来的BASE64Decoder.decodeBuffer byte[] encryptedBytes = Base64.getDecoder().decode(encryptedBase64Str); byte[] decryptedUtf8Bytes = dcipher.doFinal(encryptedBytes); return new String(decryptedUtf8Bytes, "UTF8"); } }
核心替换点
- 加密时:用
Base64.getEncoder().encodeToString(字节数组)替代new BASE64Encoder().encode(字节数组) - 解密时:用
Base64.getDecoder().decode(Base64字符串)替代new BASE64Decoder().decodeBuffer(Base64字符串)
额外提示
如果你的场景需要处理URL中的Base64内容(避免+、/等字符被转义),可以用Base64.getUrlEncoder()和Base64.getUrlDecoder(),用法和普通编码器完全一致。
内容的提问来源于stack exchange,提问作者J_Lobster
相关产品推荐
相关产品推荐

