java - 解密使用openssl、oaep padding模式加密的非对称 key

标签 java openssl cryptography

我使用以下命令生成了对称

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 上找到了一个很好的文档

https://www.openssl.org/docs/man1.0.2/man1/pkeyutl.html

关于java - 解密使用openssl、oaep padding模式加密的非对称 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61675764/

相关文章:

python - 如何使用 Python 加密大文件?

java - 无法在 Android 设备上创建 XML 文件

java - 为什么我的 Java 类在从包目录内部编译时无法编译?

java - 数组列表的数组列表作为关系的表示

SSL 证书已更新但更改不可见

c++ - 无法将 PFX 导入 Microsoft 示例 key 存储提供程序(加密提供程序开发工具包)

java - OSGi/blueprint 中的服务引用无法正常工作

c - 使用 SNI 在一个盒子中提供多个域

php - 计算 OpenID 的 Diffie Hellman key 的共享 secret 的问题

ios - xamarin 中的 CryptoCommon 类在哪里