密码未初始化加密/解密

时间:2018-12-05 19:37:04

标签: java encryption rsa unwrap

当我运行此代码时:

  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,它似乎会尝试解密,但是我在拆封之后。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

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

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