簡體   English   中英

解密使用 openssl 加密的非對稱密鑰,oaep 填充模式

[英]Decrypt asymmetric key encrypted using openssl, oaep padding mode

我使用以下命令生成了我的對稱

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

在 Oaep 參數規范下使用

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

它decrypys但校驗和不匹配。

但是使用解密的對稱密鑰我可以解碼加密的文件。 我在 openssl pkeyutl 上找到了一個很好的文檔

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM