encryption/decryption 的密码未初始化

Cipher not initialized for encryption/decryption

当我运行这段代码时:

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

return 语句行抛出这个:

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)

如果我使用 DECRYPT_MODE 它似乎尝试解密,但我在解包之后。有什么建议吗?

您使用 UNWRAP_MODE 模式初始化密码,但您正在尝试加密。您必须使用 wrapunwrap 函数,请参阅 API

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