title: Bouncy Castle vs Java default RSA with OAEP
body: <p>Can someone explain to me why this code throws <code>javax.crypto.BadPaddingException: Decryption error</code> on the final line when it's decrypting the key?</p>
  
  <pre><code>// Given an RSA key pair...
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(2048);
  KeyPair keyPair = keyGen.genKeyPair();
  PrivateKey privateKey = keyPair.getPrivate();
  PublicKey publicKey = keyPair.getPublic();
  
  // ... and an AES key:
  KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
  keyGenerator.init(256);
  SecretKey aesKey = keyGenerator.generateKey();
  
  // When I encrypt the key with this Bouncy Castle cipher:
  Cipher encryptionCipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding", "BC");
  encryptionCipher.init(Cipher.ENCRYPT_MODE, publicKey);
  byte[] encryptedKey = encryptionCipher.doFinal(aesKey.getEncoded());
  
  // Then trying to decrypt the key with this cipher...
  Cipher decryptionCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
  decryptionCipher.init(Cipher.DECRYPT_MODE, privateKey);
  // ... throws `javax.crypto.BadPaddingException: Decryption error` here:
  decryptionCipher.doFinal(encryptedKey);
  </code></pre>
  
  <p>Is the following statement from <a href="https://stackoverflow.com/a/27886397/66722">https://stackoverflow.com/a/27886397/66722</a> also true for RSA with OAEP?</p>
  
  <blockquote>
    <p>"RSA/ECB/PKCS1Padding" actually doesn't implement ECB mode encryption.
    It should have been called "RSA/None/PKCS1Padding" as it can only be
    used to encrypt a single block of plaintext (or, indeed a secret key).
    This is just a naming mistake of Sun/Oracle.</p>
  </blockquote>
  
  <p>If so, I would expect these transformations to be equivalent and my test above to pass. The same padding has been specified in both, so why the <code>BadPaddingException</code>?</p>
  
  <p>Either way, I would appreciate a layman's explanation of what the difference is.</p>