java 中不能直接用字符编码(如 utf-8)对敏感数据进行加密保护,因为编码是用于数据表示的无损转换,不具备密钥机制,无法抵御逆向还原。正确的做法是使用专门的加密算法(如 aes),并将编码作为辅助手段处理字符串与字节流之间的转换。具体而言,应使用 cipher 类配合 aes 算法进行加解密,在加解密前通过 standardcharsets.utf_8 将明文转为字节数组,解密后再转回字符串。

encode() 和 decode() 能否直接替代加密?
不能。String.getBytes() 和 new String(bytes) 只是字符集映射,任何知道目标编码的人都能瞬间还原原文。例如,UTF-8 编码后的字节序列可以直接被解码回原始文本,没有任何保密性可言。

import java.nio.charset.StandardCharsets;
public class EncodingDemo {
public static void main(String[] args) throws Exception {
String secret = "SensitiveData";
// 编码:明文 -> 字节
byte[] encodedBytes = secret.getBytes(StandardCharsets.UTF_8);
System.out.println("Encoded Hex: " + bytesToHex(encodedBytes));
// 解码:字节 -> 明文
String decodedText = new String(encodedBytes, StandardCharsets.UTF_8);
System.out.println("Decoded Text: " + decodedText);
}
private static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
运行结果:
Encoded Hex: 53656e73697469766544617461
Decoded Text: SensitiveData
如何正确使用 Cipher 实现 AES 加密?
使用 Cipher.getInstance("AES") 初始化加密器,配合 SecretKeySpec 设置密钥。加密时先调用 secret.getBytes(StandardCharsets.UTF_8) 获取输入字节,解密时同理。注意密钥长度必须为 16、24 或 32 字节。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AesEncryptionDemo {
private static final String ALGORITHM = "AES";
private static final String KEY = "MySecretKey12345"; // 16 chars for AES-128
public static void main(String[] args) throws Exception {
String plainText = "SensitiveData";
// 加密
byte[] cipherText = encrypt(plainText, KEY);
System.out.println("Encrypted Base64: " + Base64.getEncoder().encodeToString(cipherText));
// 解密
String decryptedText = decrypt(cipherText, KEY);
System.out.println("Decrypted Text: " + decryptedText);
}
public static byte[] encrypt(String data, String key) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
return cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
public static String decrypt(byte[] data, String key) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
return new String(cipher.doFinal(data), StandardCharsets.UTF_8);
}
}
运行结果:
Encrypted Base64: [随机Base64字符串]
Decrypted Text: SensitiveData
加密后输出的字节数组如何安全存储?
加密后的字节数组包含不可打印字符,直接存入文件或数据库可能导致乱码或截断。应使用 Base64 或十六进制编码将密文转换为 ASCII 字符串。Base64 编码后的字符串仅包含字母、数字和符号,适合网络传输和存储。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










