{"record":{"id":"ef71376d284ea4cb","repo":"spring-projects/spring-security","slug":"cannot-encrypt-ef7137","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/RsaSecretEncryptor.java","lineNumber":197,"sourceCode":"\tprivate static byte[] encrypt(byte[] text, PublicKey key, RsaAlgorithm alg, String salt, boolean gcm) {\n\t\tbyte[] random = KeyGenerators.secureRandom(16).generateKey();\n\t\tBytesEncryptor aes = gcm ? Encryptors.stronger(new String(Hex.encode(random)), salt)\n\t\t\t\t: Encryptors.standard(new String(Hex.encode(random)), salt);\n\t\ttry {\n\t\t\tfinal Cipher cipher = Cipher.getInstance(alg.getJceName());\n\t\t\tcipher.init(Cipher.ENCRYPT_MODE, key);\n\t\t\tbyte[] secret = cipher.doFinal(random);\n\t\t\tByteArrayOutputStream result = new ByteArrayOutputStream(text.length + 20);\n\t\t\twriteInt(result, secret.length);\n\t\t\tresult.write(secret);\n\t\t\tresult.write(aes.encrypt(text));\n\t\t\treturn result.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 void writeInt(ByteArrayOutputStream result, int length) throws IOException {\n\t\tbyte[] data = new byte[2];\n\t\tdata[0] = (byte) ((length >> 8) & 0xFF);\n\t\tdata[1] = (byte) (length & 0xFF);\n\t\tresult.write(data);\n\t}\n\n\tprivate static int readInt(ByteArrayInputStream result) throws IOException {\n\t\tbyte[] b = new byte[2];\n\t\tresult.read(b);\n\t\treturn ((b[0] & 0xFF) << 8) | (b[1] & 0xFF);\n\t}\n\n\tprivate static byte[] decrypt(byte[] text, @Nullable PrivateKey key, RsaAlgorithm alg, String salt, boolean gcm) {\n\t\tByteArrayInputStream input = new ByteArrayInputStream(text);","sourceCodeStart":179,"sourceCodeEnd":215,"githubUrl":"https://github.com/spring-projects/spring-security/blob/96852e8860138a482cb13d1479573f24ff6443c6/crypto/src/main/java/org/springframework/security/crypto/encrypt/RsaSecretEncryptor.java#L179-L215","documentation":"RsaSecretEncryptor's static encrypt(byte[], PublicKey, RsaAlgorithm, String salt, boolean gcm) wraps any checked Exception (notably IOException from writeInt's ByteArrayOutputStream writes) into IllegalStateException(\"Cannot encrypt\") with the cause attached. It signals failure while building the hybrid envelope (random AES key + RSA-encrypted key + payload).","triggerScenarios":"IOException while writing the envelope structure into the internal ByteArrayOutputStream during encryption; any checked exception thrown inside the static encrypt path.","commonSituations":"Extremely large output causing memory pressure/OutOfMemoryError surfacing near this path; subtle I/O failure in the envelope writer; debugging unexpected encryption failures where the real cause is in ex.getCause().","solutions":["Inspect the wrapped cause via ex.getCause() to find the underlying exception.","Ensure the JVM has adequate heap if encrypting very large payloads — consider streaming or splitting large data.","Retry encryption; the random key generation makes failures essentially transient only if caused by resource pressure.","Update/verify the Spring Security crypto version if the cause points to a library bug."],"exampleFix":"// before\nbyte[] out = secretEncryptor.encrypt(hugePayload); // may wrap OOM/IO failure\n// after\nif (hugePayload.length > MAX_ENVELOPE_SIZE) {\n    throw new IllegalArgumentException(\"payload too large for RSA envelope encryption\");\n}\nbyte[] out = secretEncryptor.encrypt(hugePayload);","handlingStrategy":"try-catch","validationCode":"if (payload == null || payload.length == 0) throw new IllegalArgumentException(\"payload required\");\nif (publicKey == null) throw new IllegalArgumentException(\"public key required for encryption\");","typeGuard":"boolean encryptable(RsaSecretEncryptor enc, byte[] payload) { return enc != null && payload != null && payload.length > 0; }","tryCatchPattern":"try {\n    return encryptor.encrypt(payload);\n} catch (IllegalStateException ex) {\n    logger.error(\"Encryption failed: \" + ex.getCause(), ex);\n    throw new SecurityException(\"Encryption failed\", ex);\n}","preventionTips":["Always inspect ex.getCause() — the IllegalStateException is only a wrapper.","Keep payloads within reasonable size limits; hybrid RSA envelopes are not for bulk data.","Ensure ByteArrayOutputStream/I/O resources are not constrained (sufficient heap).","Round-trip test encrypt/decrypt with the same algorithm, salt, and gcm settings."],"tags":["rsa","encryption","illegal-state","io"],"backgroundTag":"encryption-failed","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"}