【问题标题】:Decrypt asymmetric key encrypted using openssl, oaep padding mode解密使用openssl、oaep填充模​​式加密的非对称密钥
【发布时间】:2020-05-08 09:11:40
【问题描述】:

我使用以下命令生成了我的 Symmetric

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

但是当我尝试使用我的私钥解密时,它给了我 Bad padding 错误。

我的 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;
  }

【问题讨论】:

  • 这不行,Madhav,你只能用@符号来ping已经评论的人。除此之外,这不是一个您可以请求特定人员提供帮助的网站,我们这里没有付费顾问。请将 full stracktrace 放在您的问题中,并指出异常在您的代码中发生的位置。我也错过了我认为的对称加密部分。
  • final byte[] symmetricKey = cipher.doFinal(ciphertext); 此代码抛出异常给出 BadPadding 异常

标签: java openssl cryptography


【解决方案1】:

在Oaep参数规范下使用

new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);

它解密但校验和不匹配。

但是使用解密的对称密钥我可以解码加密的文件。我在 openssl pkeyutl 上找到了一个很好的文档

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

【讨论】:

  • 由于在 OpenSSL 语句中既没有明确指定标签也没有明确指定 MGF1 摘要,因此使用默认摘要,在这两种情况下都是 SHA-1。因此,解密使用响应中发布的配置。你说的是哪个校验和?
猜你喜欢
  • 2018-09-23
  • 1970-01-01
  • 2020-03-15
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多