欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > Java实现OpenSSL加解密

Java实现OpenSSL加解密

2024/10/24 17:31:51 来源:https://blog.csdn.net/promise524/article/details/141476367  浏览:    关键词:Java实现OpenSSL加解密

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

调用OpenSSL

1. 使用OpenSSL进行密钥加密

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);}
}
  • 加密和解密输出结果
# 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 加密和解密实现

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. 结果

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

4. 注意

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com