对Java代码进行加密的一种常用方法是使用Java加密扩展(JCE)提供的加密算法和相关类。下面是一个示例,演示如何使用AES进行加密:
- 导入所需的类和包:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
- 创建一个方法,用于将明文字符串加密为密文:
public static String encrypt(String plainText, String encryptionKey) throws Exception {
byte[] key = encryptionKey.getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encrypted);
}
- 创建一个方法,用于将密文字符串解密为明文:
public static String decrypt(String cipherText, String encryptionKey) throws Exception {
byte[] key = encryptionKey.getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(decrypted);
}
- 在主方法中调用加密和解密方法:
public static void main(String[] args) {
try {
String plainText = "Hello, world!";
String encryptionKey = "myEncryptionKey";
// 加密
String cipherText = encrypt(plainText, encryptionKey);
System.out.println("密文: " + cipherText);
// 解密
String decryptedText = decrypt(cipherText, encryptionKey);
System.out.println("明文: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
请注意,此示例使用AES算法,使用ECB模式和PKCS5Padding填充。加密和解密使用相同的密钥。确保使用适当的密钥管理和传递方法来保护密钥的安全性。