aes openssl java_如何用 Java 读取 openssl genrsa -aes256 生成的密钥
时间: 2023-10-12 16:10:07 浏览: 74
可以以下代码来读取 OpenSSL 生成的 AES 256 密钥:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class ReadOpenSSLPrivateKey {
public static void main(String[] args) throws Exception {
// 读取私钥文件
BufferedReader br = new BufferedReader(new FileReader("private_key.pem"));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
if (line.startsWith("-----BEGIN ") || line.startsWith("-----END ")) {
continue;
}
sb.append(line);
}
br.close();
// 解码 Base64 格式的密钥
byte[] keyBytes = Base64.getDecoder().decode(sb.toString());
// 获取密码
String password = "your_password";
// 生成 AES 密钥
byte[] ivBytes = new byte[16];
byte[] saltBytes = Arrays.copyOfRange(keyBytes, 8, 16);
byte[] keyBytesWithoutSalt = Arrays.copyOfRange(keyBytes, 16, keyBytes.length);
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec keySpec = new SecretKeySpec(getAESKey(password, saltBytes), "AES");
// 解密私钥
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decryptedBytes = cipher.doFinal(keyBytesWithoutSalt);
// 转换成 Key 对象
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decryptedBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
Key privateKey = kf.generatePrivate(spec);
System.out.println(privateKey);
}
public static byte[] getAESKey(String password, byte[] saltBytes) throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
return tmp.getEncoded();
}
}
```
其中 `private_key.pem` 是 OpenSSL 生成的密钥文件,`your_password` 是生成密钥时设置的密码。这段代码会读取密钥文件,解码 Base64 格式的密钥,生成 AES 密钥,解密私钥,并将其转换成 Java 的 `Key` 对象。
阅读全文