我使用以下命令生成了对称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);
它解密,但校验和不匹配。
但是使用解密的对称密钥,我可以解码加密的文件。我在openssl pkeyutl上找到了很好的文档
https://www.openssl.org/docs/man1.0.2/man1/pkeyutl.html