Search code examples
javaencryptionrsaunwrap

Cipher not initialized for encryption/decryption


When I run this code:

  public static byte[] unwrap(PrivateKey privateKey, byte[] wrappedKey) throws Exception {
      Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");  
      cipher.init(Cipher.UNWRAP_MODE, privateKey);

      return cipher.doFinal(wrappedKey);
  }

The return statement line throws this:

Exception in thread "main" java.lang.IllegalStateException: Cipher not initialized for encryption/decryption
    at javax.crypto.Cipher.checkCipherState(Cipher.java:1754)
    at javax.crypto.Cipher.doFinal(Cipher.java:2157)
    at x.y.z.decrypt.Main.unwrap(Main.java:47)
    at x.y.z.decrypt.Main.main(Main.java:33)

If I use DECRYPT_MODE it seems to try and decrypt, but I'm after unwrap. Any suggestions?


Solution

  • You initialized the cipher with UNWRAP_MODE mode, but you are trying to encrypt. You have to use wrap and unwrap functions, see the API

    unwrap​(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType)