效果图
全部代码
package encryption001;import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;public class EncryptionDemo {// 加密算法private static final String ALGORITHM = "AES";// 加密模式和填充方式private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";// 密钥,这里是一个简单的硬编码密钥,实际使用中需要更复杂的密钥管理机制private static final String SECRET_KEY = "MySecretKey12345"; // 16字符的密钥/*** 加密函数** @param plainText 待加密的字符串* @return 加密后的Base64编码字符串*/public static String encrypt(String plainText) {try {// 创建用于AES加密的密钥规格SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);// 创建AES加密器Cipher cipher = Cipher.getInstance(TRANSFORMATION);// 初始化加密器为加密模式,并使用密钥cipher.init(Cipher.ENCRYPT_MODE, key);// 对明文进行加密,得到加密后的字节数组byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());// 将加密后的字节数组转换成Base64编码的字符串return Base64.getEncoder().encodeToString(encryptedBytes);} catch (Exception e) {// 捕捉可能的异常,并打印错误信息e.printStackTrace();return null;}}/*** 解密函数** @param encryptedText 加密后的Base64编码字符串* @return 解密后的字符串*/public static String decrypt(String encryptedText) {try {// 创建用于AES解密的密钥规格SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);// 创建AES解密器Cipher cipher = Cipher.getInstance(TRANSFORMATION);// 初始化解密器为解密模式,并使用密钥cipher.init(Cipher.DECRYPT_MODE, key);// 对Base64编码的加密字符串进行解码,得到加密后的字节数组byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);// 对加密后的字节数组进行解密,得到原始的字节数组byte[] decryptedBytes = cipher.doFinal(encryptedBytes);// 将解密后的字节数组转换成字符串return new String(decryptedBytes);} catch (Exception e) {// 捕捉可能的异常,并打印错误信息e.printStackTrace();return null;}}/*** 主函数,用于测试加解密功能** @param args 命令行参数*/public static void main(String[] args) {// 待加密的原始文本String originalText = "Hello, Encryption!";System.out.println("Original Text: " + originalText);// 调用加密函数,得到加密后的字符串String encryptedText = encrypt(originalText);System.out.println("Encrypted Text: " + encryptedText);// 调用解密函数,得到解密后的字符串String decryptedText = decrypt(encryptedText);System.out.println("Decrypted Text: " + decryptedText);}
}