我使用以下命令生成了对称
openssl rand 32 > test.key
它是使用我的公钥加密的,如下命令所示。它使用OAEP填充模式。
openssl pkeyutl -pkeyopt rsa_padding_mode:oaep -encrypt -inkey public.key -pubin -in test.key -out test.key.enc
但是当我尝试使用我的私钥解密时,它给了我错误的填充错误。
我的Java代码
// few imports
private static PrivateKey getPrivateKey(final String privateKeyFile)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
final KeyFactory keyFactory = KeyFactory.getInstance(PayboxUtil.ENCRYPTION_ALGORITHM);
final PemReader reader = new PemReader(new FileReader(privateKeyFile));
final byte[] pubKey = reader.readPemObject().getContent();
final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pubKey);
return keyFactory.generatePrivate(spec);
}
public static byte[] decryptRandomKey(final byte[] encryptedKey, final String private_key_file)
throws NoSuchProviderException {
try {
final Key privKey = getPrivateKey(private_key_file);
final byte[] ciphertext = encryptedKey;
final Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");
final OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-512", "MGF1",
new MGF1ParameterSpec("SHA-1"), PSpecified.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, privKey, oaepParams);
final byte[] symmetricKey = cipher.doFinal(ciphertext);
return symmetricKey;
} catch (final Exception e) {
e.printStackTrace();
}
return null;
}
最佳答案
在 Oaep 参数规范下使用
new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
它可以解密,但校验和不匹配。
但是使用解密的对称 key 我可以解码加密的文件。我在 openssl pkeyutl 上找到了一个很好的文档
关于java - 解密使用openssl、oaep padding模式加密的非对称 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61675764/