Java实现OpenSSL加解密

devtools/2024/9/25 6:17:20/

在Java中实现使用OpenSSL进行密钥的加密和解密,可以通过Java调用OpenSSL命令来完成。

调用OpenSSL

1. 使用OpenSSL进行密钥加密

java">import java.io.BufferedReader;
import java.io.InputStreamReader;public class OpenSSLUtil {/*** 使用OpenSSL加密密钥** @param secretKey 要加密的密钥* @param passphrase 用于加密的密码短语* @return 加密后的密钥字符串*/public static String encryptSecretKey(String secretKey, String passphrase) {try {// 构建OpenSSL加密命令String command = String.format("echo -n %s | openssl enc -aes-256-cbc -a -pass pass:%s", secretKey, passphrase);Process process = Runtime.getRuntime().exec(new String[]{"bash", "-c", command});// 读取加密后的输出BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));StringBuilder output = new StringBuilder();String line;while ((line = reader.readLine()) != null) {output.append(line);}process.waitFor();return output.toString();} catch (Exception e) {e.printStackTrace();throw new RuntimeException("Failed to encrypt secret key with OpenSSL");}}/*** 使用OpenSSL解密密钥** @param encryptedKey 加密后的密钥字符串* @param passphrase 用于解密的密码短语* @return 解密后的密钥字符串*/public static String decryptSecretKey(String encryptedKey, String passphrase) {try {// 构建OpenSSL解密命令String command = String.format("echo %s | openssl enc -aes-256-cbc -d -a -pass pass:%s", encryptedKey, passphrase);Process process = Runtime.getRuntime().exec(new String[]{"bash", "-c", command});// 读取解密后的输出BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));StringBuilder output = new StringBuilder();String line;while ((line = reader.readLine()) != null) {output.append(line);}process.waitFor();return output.toString();} catch (Exception e) {e.printStackTrace();throw new RuntimeException("Failed to decrypt secret key with OpenSSL");}}public static void main(String[] args) {// 加密和解密密钥String secretKey = "123456";String password = "admin";// 加密密钥String encryptedKey = encryptSecretKey(secretKey, password);System.out.println("Encrypted Key: " + encryptedKey);// 解密密钥String decryptedKey = decryptSecretKey(encryptedKey, password);System.out.println("Decrypted Key: " + decryptedKey);}
}
  • 加密和解密输出结果
java"># Encrypted Key: U2FsdGVkX1+Nm96WU2sh6KBKIsNIwD3grcJ2L9Qgkl0=
# Decrypted Key: 123456

2. 说明

  • 加密密钥encryptSecretKey方法使用OpenSSL通过AES-256-CBC算法和指定的password对给定的secretKey进行加密。加密后的密钥以Base64编码的形式返回。

  • 解密密钥decryptSecretKey方法使用相同的password对加密的密钥进行解密。返回的解密密钥应与原始密钥相同。

3. 注意

  • 依赖的环境:确保在执行代码的机器上已经安装了OpenSSL,并且可以通过命令行调用。

非调用OpenSSL

使用Java的内置加密库来实现相同的功能。Java提供了javax.crypto包来进行加密和解密操作,可以实现类似于OpenSSL的AES-256-CBC加密算法。

1. AES-256-CBC 加密和解密实现

java">import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;public class AESUtil {// 使用AES-256-CBC加密public static String encrypt(String plainText, String secretKey, String initVector) {try {IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(StandardCharsets.UTF_8));SecretKeySpec skeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);byte[] encrypted = cipher.doFinal(plainText.getBytes());return Base64.getEncoder().encodeToString(encrypted);} catch (Exception ex) {throw new RuntimeException("Error while encrypting: " + ex.toString());}}// 使用AES-256-CBC解密public static String decrypt(String encryptedText, String secretKey, String initVector) {try {IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(StandardCharsets.UTF_8));SecretKeySpec skeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedText));return new String(original);} catch (Exception ex) {throw new RuntimeException("Error while decrypting: " + ex.toString());}}public static void main(String[] args) {// 加密和解密String secretKey = "12345678901234567890123456789012"; // 32字节的密钥String initVector = "RandomInitVector"; // 16字节的初始化向量String password = "123456";System.out.println("Original Text: " + 123456);// 加密String encryptedText = encrypt(originalText, secretKey, initVector);System.out.println("Encrypted Text: " + 123456);// 解密String decryptedText = decrypt(encryptedText, secretKey, initVector);System.out.println("Decrypted Text: " + decryptedText);}
}

2. 说明

  • 密钥 (SecretKey):使用32字节(256位)的密钥进行AES-256加密。确保密钥长度为32字节。
  • 初始化向量 (IV):使用16字节的初始化向量(IV),用于确保相同的明文在每次加密时产生不同的密文。
  • 加密方法encrypt方法使用AES-256-CBC模式进行加密,并返回Base64编码后的加密字符串。
  • 解密方法decrypt方法将Base64编码的密文解码并使用AES-256-CBC模式进行解密,返回原始明文。

3. 结果

java"># Original Text: 123456
# Encrypted Text: PcYQ/IF5BlE/yCLVwbojOg==
# Decrypted Text: 123456

4. 注意

  • 密钥管理:确保加密密钥的安全管理,不应将其硬编码到源代码中。在实际应用中,密钥和IV应从安全的配置或密钥管理系统中获取。
  • 初始化向量 (IV):对于每次加密操作,应使用不同的IV以确保安全性。IV不需要保密,但应与密文一起存储或传输,以便解密时使用。

http://www.ppmy.cn/devtools/99685.html

相关文章

不懂就问,换毛季猫咪疯狂掉毛怎么办?宠物浮毛该如何清理?

最近天气变热了,每天都30度以上,我家猫狂掉毛,床上、地板上堆积了不少。第一次养猫的我没见过这种阵仗,以为它生病了,连忙带它去看医生。医生告诉我,这是正常的猫咪换毛现象,我才放下心来。原来…

iPhone变身万能钥匙,iOS 18.1让你的手机解锁一切

Apple 近日发布新闻稿宣布,在即将推出的 iOS 18.1 更新中,将开放全新的 NFC(近场通信)和 SE(安全元件)API 给第三方开发者使用。这一举措将使得开发者能够开发出更加多样化和实用的应用程序,如车…

【C# 】使用List<实体类>

1. 使用List<实体类> 要在C#中使用List<EntityTemp>并实现查找数据输出&#xff0c;首先需要定义EntityTemp类&#xff0c;并创建一个List<EntityTemp>类型的列表。然后&#xff0c;你可以使用LINQ或其他方法来查找和输出数据。 假设EntityTemp类具有一个…

出现 2003 - Can’t connect to MySQL server on ‘xxx‘(10060) 解决方法

目录 1. 问题所示2. 原理分析3. 解决方法1. 问题所示 sql链接远程服务器的时候,出现如下问题: 2003 - Can’t connect to MySQL server on xxx(10060)截图如下所示: 2. 原理分析 错误代码 10060 表示“连接超时”,说明客户端在尝试连接到服务器时,服务器没有响应或者响…

Kubernetes 中 etcd 的备份与还原操作指南

在 Kubernetes 生态系统中&#xff0c;etcd 是一个关键的分布式键值存储&#xff0c;用于保存有关集群的所有数据。etcd 为 Kubernetes 提供了数据的一致性和可靠性&#xff0c;使得集群在发生故障时能够迅速恢复。因此&#xff0c;定期备份和能够有效地还原 etcd 数据对保证 K…

微服务及安全

一、微服务的原理 1.什么是微服务架构 微服务架构区别于传统的单体软件架构,是一种为了适应当前互联网后台服务的「三高需求:高并发、高性能、高可用」而产生的的软件架构。 单体式应用程序 与微服务相对的另一个概念是传统的单体式应用程序( Monolithic application ),…

BEV学习---LSS-1:论文原理及代码串讲

目前在自动驾驶领域&#xff0c;比较火的一类研究方向是基于采集到的环视图像信息&#xff0c;去构建BEV视角下的特征完成自动驾驶感知的相关任务。所以如何准确的完成从相机视角向BEV视角下的转变就变得由为重要。目前感觉比较主流的方法可以大体分为两种&#xff1a; 1、显式…

MySQL 系统学习系列 - SQL 语句 DQL 语句的使用(1)《MySQL系列篇-03》

SQL 语句 DQL 数据库表常见查询语句 1. 全部查询 # 查询全部 [SELECT * FROM 表名]SELECT * FROM stu; # 查询stu表中的所有列# 再 SELECT 语句后加上 distinct 语句&#xff0c;表示去重查询SELECT distinct name FROM stu; # 查询stu表中的所有name列&#xff08;去重&#…