title: Bad Padding Exception - RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING in pkcs11
body: <p>My application is accessing e-Token for decrypting the response coming from the server</p>
  
  <p>The session key from the server is encrypted using :-</p>
  
  <blockquote>
    <p>RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING</p>
  </blockquote>
  
  <p>I am using SunPKCS11 Provider for implementing the access to crypto token.
  Whenever i try to decrypt this using the above mechanishm i.e. with <strong>RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING</strong> i am getting :-</p>
  
  <pre><code>**javax.crypto.BadPaddingException: doFinal() failed  
      at sun.security.pkcs11.P11RSACipher.implDoFinal(P11RSACipher.java:328)  
      at sun.security.pkcs11.P11RSACipher.engineDoFinal(P11RSACipher.java:353)  
      at javax.crypto.Cipher.doFinal(DashoA13*..)
  </code></pre>
  
  <p>The following is my code :-</p>
  
  <pre><code>private static final String TRANSFORMATION = "RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING";
  private static final String SECURITY_PROVIDER = "BC";
  private static final String DIGEST_ALGORITHM = "SHA-256";
  private static final String MASKING_FUNCTION = "MGF1";
  </code></pre>
  
  <p>The code snippet where the error is coming is as follows :-</p>
  
  <pre><code>private byte[] decryptSecretKeyData(byte[] encryptedSecretKey, byte[] iv, PrivateKey privateKey) throws Exception {
  
          try {
              Cipher rsaCipher = Cipher.getInstance(TRANSFORMATION, SECURITY_PROVIDER);
  
              System.out.println("Cipher block initialized"); - **Printed**
              PSource pSrc = (new PSource.PSpecified(iv));
              System.out.println("PSource inisitialized"); - **Printed**
  
  
              rsaCipher.init(Cipher.DECRYPT_MODE, privateKey,
                      new OAEPParameterSpec(DIGEST_ALGORITHM, MASKING_FUNCTION,
                              MGF1ParameterSpec.SHA256, pSrc));
  
  
              System.out.println("Here after cipher initilaization");  - **Not Printed***
  
              return rsaCipher.doFinal(encryptedSecretKey);
          } catch (GeneralSecurityException e) {
              System.out.println("GeneralSecurityException is "+e.getMessage());
              throw new Exception("Failed to decrypt AES secret key using RSA.", e);
          }
      }
  </code></pre>
  
  <p>I am Stuck in here and unable to decrypt the OAEP Transformation.</p>