1.生成随机密钥
public static SecretKey generateSecretKey() {
// 创建 AES 密钥生成器
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
// 设置密钥长度(128、192 或 256 位)
keyGenerator.init(128); // 这里使用 128 位密钥长度
// 生成随机密钥
SecretKey secretKey = keyGenerator.generateKey();
return secretKey;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
2.字符串加密解密
- 字符串加密
public static String[] encryption(String originalText) {
//获取秘钥
try {
SecretKey secretKey = generateSecretKey();
//这里使用的是 AES 加密算法
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(originalText.getBytes("UTF-8"));
// 将字节数组转换为 Base64 编码的字符串
String decryptedText = Base64.getEncoder().encodeToString(decryptedBytes);
// 将密钥转换为字节数组
byte[] keyBytes = secretKey.getEncoded();
String SecretKey=Base64.getEncoder().encodeToString(keyBytes);
System.out.println("原始文本:" + originalText);
System.out.println("加密后的文本=" + decryptedText);
System.out.println("秘钥=" + SecretKey);
// 返回秘钥和加密后的文本
String[] strings={SecretKey,decryptedText};
return strings;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
- 字符串解密
private static String decryption(String key, String decryptedText) {
byte[] encryptedBytes = Base64.getDecoder().decode(key);
try {
SecretKey secretKey = new SecretKeySpec(encryptedBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
// 解密操作
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decode = Base64.getDecoder().decode(decryptedText);
byte[] decryptedBytes = cipher.doFinal(decode);
return new String(decryptedBytes, "UTF-8");
}catch (Exception e) {
throw new RuntimeException(e);
}
}
3.完整代码
整体代码
public static void main(String[] args) {
// 原始字符串
String originalText = "Hello, this is a secret message.";
// 加密 返回秘钥,和加密后的字符串
String[] encryption = encryption(originalText);
// 解密 传入秘钥和密文
String decryption = decryption(encryption[0], encryption[1]);
System.out.println(decryption);
}
//加密
public static String[] encryption(String originalText) {
//获取秘钥
try {
SecretKey secretKey = generateSecretKey();
//这里使用的是 AES 加密算法
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(originalText.getBytes("UTF-8"));
// 将字节数组转换为 Base64 编码的字符串
String decryptedText = Base64.getEncoder().encodeToString(decryptedBytes);
// 将密钥转换为字节数组
byte[] keyBytes = secretKey.getEncoded();
String SecretKey=Base64.getEncoder().encodeToString(keyBytes);
System.out.println("原始文本:" + originalText);
System.out.println("加密后的文本=" + decryptedText);
System.out.println("秘钥=" + SecretKey);
String[] strings={SecretKey,decryptedText};
return strings;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//解密
private static String decryption(String key, String decryptedText) {
byte[] encryptedBytes = Base64.getDecoder().decode(key);
try {
SecretKey secretKey = new SecretKeySpec(encryptedBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
// 解密操作
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decode = Base64.getDecoder().decode(decryptedText);
byte[] decryptedBytes = cipher.doFinal(decode);
return new String(decryptedBytes, "UTF-8");
}catch (Exception e) {
throw new RuntimeException(e);
}
}
// 生成秘钥
public static SecretKey generateSecretKey() {
// 创建 AES 密钥生成器
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
// 设置密钥长度(128、192 或 256 位)
keyGenerator.init(128); // 这里使用 256 位密钥长度
// 生成随机密钥
SecretKey secretKey = keyGenerator.generateKey();
return secretKey;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
4.加密和解密文件
- 文件加密
/**
* @param inputFile 原始文件路径
* @param outputFile 加密后文件路径
* @return
* @throws Exception
*/
private static String fileEncryption(String inputFile, String outputFile) throws Exception {
// 获取秘钥
SecretKey secretKey = generateSecretKey();
Cipher cipher = Cipher.getInstance("AES"); // 根据加密模式获取Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, secretKey); // 初始化Cipher对象为加密模式
try (
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) >= 0) {
cipherOutputStream.write(buffer, 0, bytesRead); // 加密文件内容并写入输出流
}
return Base64.getEncoder().encodeToString(secretKey.getEncoded());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
2.文件解密
/**
* @param inputFile 原始文件路径
* @param outputFile 加密后文件路径
* @return
* @throws Exception
*/
private static String fileEncryption(String inputFile, String outputFile) throws Exception {
// 获取秘钥
SecretKey secretKey = generateSecretKey();
Cipher cipher = Cipher.getInstance("AES"); // 根据加密模式获取Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, secretKey); // 初始化Cipher对象为加密模式
try (
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) >= 0) {
cipherOutputStream.write(buffer, 0, bytesRead); // 加密文件内容并写入输出流
}
return Base64.getEncoder().encodeToString(secretKey.getEncoded());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
- 完整代码
public static void main(String[] args) throws Exception {
String key = fileEncryption("C:\\Users\\admin\\Desktop\\test.txt", "C:\\Users\\admin\\Desktop\\test2.txt");
System.out.println(key);
fileDecryption(key, "C:\\Users\\admin\\Desktop\\test2.txt", "C:\\Users\\admin\\Desktop\\test3.txt");
}
// 生成秘钥
public static SecretKey generateSecretKey() {
// 创建 AES 密钥生成器
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
// 设置密钥长度(128、192 或 256 位)
keyGenerator.init(128); // 这里使用 256 位密钥长度
// 生成随机密钥
SecretKey secretKey = keyGenerator.generateKey();
return secretKey;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @param inputFile 原始文件路径
* @param outputFile 加密后文件路径
* @return
* @throws Exception
*/
private static String fileEncryption(String inputFile, String outputFile) throws Exception {
// 获取秘钥
SecretKey secretKey = generateSecretKey();
Cipher cipher = Cipher.getInstance("AES"); // 根据加密模式获取Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, secretKey); // 初始化Cipher对象为加密模式
try (
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) >= 0) {
cipherOutputStream.write(buffer, 0, bytesRead); // 加密文件内容并写入输出流
}
return Base64.getEncoder().encodeToString(secretKey.getEncoded());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @param key 秘钥
* @param inputFile 加密文件路径
* @param outputFile 解密文件路径
*/
private static void fileDecryption(String key, String inputFile, String outputFile) throws Exception{
byte[] encryptedBytes = Base64.getDecoder().decode(key);
SecretKey secretKey = new SecretKeySpec(encryptedBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
// 解密操作
cipher.init(Cipher.DECRYPT_MODE, secretKey);
try (
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) >= 0) {
cipherOutputStream.write(buffer, 0, bytesRead); // 解密密文件内容并写入输出流
}
}catch (Exception e) {
throw new RuntimeException(e);
}
}