{"record":{"id":"3740e040fe885765","repo":"spring-projects/spring-security","slug":"cannot-encrypt","errorCode":null,"errorMessage":"Cannot encrypt","messagePattern":"Cannot encrypt","errorType":"exception","errorClass":"IllegalStateException","httpStatus":null,"severity":"error","filePath":"crypto/src/main/java/org/springframework/security/crypto/encrypt/RsaRawEncryptor.java","lineNumber":139,"sourceCode":"\t\ttry {\n\t\t\tfinal Cipher cipher = Cipher.getInstance(alg.getJceName());\n\t\t\tint limit = Math.min(text.length, alg.getMaxLength());\n\t\t\tint pos = 0;\n\t\t\twhile (pos < text.length) {\n\t\t\t\tcipher.init(Cipher.ENCRYPT_MODE, key);\n\t\t\t\tcipher.update(text, pos, limit);\n\t\t\t\tpos += limit;\n\t\t\t\tlimit = Math.min(text.length - pos, alg.getMaxLength());\n\t\t\t\tbyte[] buffer = cipher.doFinal();\n\t\t\t\toutput.write(buffer, 0, buffer.length);\n\t\t\t}\n\t\t\treturn output.toByteArray();\n\t\t}\n\t\tcatch (RuntimeException ex) {\n\t\t\tthrow ex;\n\t\t}\n\t\tcatch (Exception ex) {\n\t\t\tthrow new IllegalStateException(\"Cannot encrypt\", ex);\n\t\t}\n\t}\n\n\tprivate static byte[] decrypt(byte[] text, @Nullable RSAPrivateKey key, RsaAlgorithm alg) {\n\t\tByteArrayOutputStream output = new ByteArrayOutputStream(text.length);\n\t\ttry {\n\t\t\tfinal Cipher cipher = Cipher.getInstance(alg.getJceName());\n\t\t\tint maxLength = getByteLength(key);\n\t\t\tint pos = 0;\n\t\t\twhile (pos < text.length) {\n\t\t\t\tint limit = Math.min(text.length - pos, maxLength);\n\t\t\t\tcipher.init(Cipher.DECRYPT_MODE, key);\n\t\t\t\tcipher.update(text, pos, limit);\n\t\t\t\tpos += limit;\n\t\t\t\tbyte[] buffer = cipher.doFinal();\n\t\t\t\toutput.write(buffer, 0, buffer.length);\n\t\t\t}\n\t\t\treturn output.toByteArray();","sourceCodeStart":121,"sourceCodeEnd":157,"githubUrl":"https://github.com/spring-projects/spring-security/blob/96852e8860138a482cb13d1479573f24ff6443c6/crypto/src/main/java/org/springframework/security/crypto/encrypt/RsaRawEncryptor.java#L121-L157","documentation":"encrypt wraps any non-RuntimeException failure from the cipher/byte-stream encryption (e.g. InvalidKeyException, BadPaddingException, IllegalBlockSizeException, or stream IO) in an IllegalStateException with the message 'Cannot encrypt' and the original exception as cause.","triggerScenarios":"Calling encrypt with a key the provider rejects (wrong key type/size, invalid encoding), or an underlying Cipher/OutputStream failure while processing the plaintext bytes.","commonSituations":"Passing a non-RSA or corrupted Key object, JCE policy/algorithm restrictions in older JVMs, or a security provider mismatch on the runtime environment.","solutions":["Inspect getCause() — usually InvalidKeyException — and correct the supplied RSA key.","Verify the Key passed to the encryptor is a valid RSAPublicKey for the chosen RsaAlgorithm.","Check JVM JCE policy / install unlimited strength policy files on legacy JDKs (8u161-).","Test encryption with a freshly generated key pair to isolate key vs. environment issues."],"exampleFix":"// before\nKey badKey = loadKey(); // may be non-RSA or null-ish\nbyte[] ct = encryptor.encrypt(data); // IllegalStateException: Cannot encrypt\n// after\nif (badKey instanceof RSAPublicKey) {\n    byte[] ct = encryptor.encrypt(data);\n} else {\n    throw new IllegalArgumentException(\"Expected RSAPublicKey, got \" + badKey.getClass());\n}","handlingStrategy":"try-catch","validationCode":"if (!(key instanceof RSAPublicKey)) {\n    throw new IllegalArgumentException(\"Encryption requires an RSAPublicKey, got: \" + (key == null ? \"null\" : key.getClass().getName()));\n}","typeGuard":null,"tryCatchPattern":"try {\n    byte[] cipher = encryptor.encrypt(plaintext);\n} catch (IllegalStateException e) {\n    log.error(\"Encryption failed: \" + e.getCause(), e); // cause is the real InvalidKey/ProviderException\n    throw e;\n}","preventionTips":["Always inspect getCause(); the message itself is generic.","Validate key type/size before constructing the encryptor.","Confirm JCE unlimited-strength policies on older JDKs if using large keys.","Smoke-test encrypt/decrypt round-trip at startup with a known key pair."],"tags":["rsa","encryption","cipher","wrapped-exception"],"backgroundTag":"internal-invariant-violation","analyzedSha":"96852e8860138a482cb13d1479573f24ff6443c6","analyzedAt":"2026-09-10T23:25:23.477Z","contentChangedAt":"2026-09-10T23:25:23.477Z","schemaVersion":2},"datasetVersion":"2026-09-14T16:17:12.679Z"}