spring-projects/spring-security · error · IllegalStateException

Cannot encrypt

Error message

Cannot encrypt

What it means

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.

Source

Thrown at crypto/src/main/java/org/springframework/security/crypto/encrypt/RsaRawEncryptor.java:139

		try {
			final Cipher cipher = Cipher.getInstance(alg.getJceName());
			int limit = Math.min(text.length, alg.getMaxLength());
			int pos = 0;
			while (pos < text.length) {
				cipher.init(Cipher.ENCRYPT_MODE, key);
				cipher.update(text, pos, limit);
				pos += limit;
				limit = Math.min(text.length - pos, alg.getMaxLength());
				byte[] buffer = cipher.doFinal();
				output.write(buffer, 0, buffer.length);
			}
			return output.toByteArray();
		}
		catch (RuntimeException ex) {
			throw ex;
		}
		catch (Exception ex) {
			throw new IllegalStateException("Cannot encrypt", ex);
		}
	}

	private static byte[] decrypt(byte[] text, @Nullable RSAPrivateKey key, RsaAlgorithm alg) {
		ByteArrayOutputStream output = new ByteArrayOutputStream(text.length);
		try {
			final Cipher cipher = Cipher.getInstance(alg.getJceName());
			int maxLength = getByteLength(key);
			int pos = 0;
			while (pos < text.length) {
				int limit = Math.min(text.length - pos, maxLength);
				cipher.init(Cipher.DECRYPT_MODE, key);
				cipher.update(text, pos, limit);
				pos += limit;
				byte[] buffer = cipher.doFinal();
				output.write(buffer, 0, buffer.length);
			}
			return output.toByteArray();

View on GitHub (pinned to 96852e8860)

Solutions

  1. Inspect getCause() — usually InvalidKeyException — and correct the supplied RSA key.
  2. Verify the Key passed to the encryptor is a valid RSAPublicKey for the chosen RsaAlgorithm.
  3. Check JVM JCE policy / install unlimited strength policy files on legacy JDKs (8u161-).
  4. Test encryption with a freshly generated key pair to isolate key vs. environment issues.

Example fix

// before
Key badKey = loadKey(); // may be non-RSA or null-ish
byte[] ct = encryptor.encrypt(data); // IllegalStateException: Cannot encrypt
// after
if (badKey instanceof RSAPublicKey) {
    byte[] ct = encryptor.encrypt(data);
} else {
    throw new IllegalArgumentException("Expected RSAPublicKey, got " + badKey.getClass());
}
Defensive patterns

Strategy: try-catch

Validate before calling

if (!(key instanceof RSAPublicKey)) {
    throw new IllegalArgumentException("Encryption requires an RSAPublicKey, got: " + (key == null ? "null" : key.getClass().getName()));
}

Try / catch

try {
    byte[] cipher = encryptor.encrypt(plaintext);
} catch (IllegalStateException e) {
    log.error("Encryption failed: " + e.getCause(), e); // cause is the real InvalidKey/ProviderException
    throw e;
}

Prevention

When it happens

Trigger: 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.

Common situations: Passing a non-RSA or corrupted Key object, JCE policy/algorithm restrictions in older JVMs, or a security provider mismatch on the runtime environment.

Understand the failure class

Background: "This is a bug, please report it": internal invariant violations, unreachable panics, and SNH errors explained — this error's family across 47 libraries.

Related errors


AI-assisted analysis of spring-projects/spring-security@96852e8860 (2026-09-10). Data as JSON: /api/errors/3740e040fe885765. Report an issue: GitHub.