spring-projects/spring-security · error · IllegalArgumentException

key cannot be null

Error message

key cannot be null

What it means

RsaRawEncryptor.getByteLength(RSAKey) is a static helper (copied from sun.security.rsa.RSACore) that computes the RSA modulus size in bytes. It throws IllegalArgumentException("key cannot be null") when passed a null RSAKey, as a fail-fast guard instead of a NullPointerException.

Source

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

				cipher.update(text, pos, limit);
				pos += limit;
				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 decrypt", ex);
		}
	}

	// copied from sun.security.rsa.RSACore.getByteLength(java.math.BigInteger)
	public static int getByteLength(@Nullable RSAKey key) {
		if (key == null) {
			throw new IllegalArgumentException("key cannot be null");
		}
		int n = key.getModulus().bitLength();
		return (n + 7) >> 3;
	}

}

View on GitHub (pinned to 96852e8860)

Solutions

  1. Pass a non-null RSAKey (RSAPublicKey or RSAPrivateKey) to getByteLength.
  2. If using maxLength() on an encryptor, verify the encryptor was constructed with a valid key before calling.
  3. Add a null check on the key at the construction/assignment site.

Example fix

// before
int max = RsaRawEncryptor.getByteLength(maybeKey);
// after
Assert.notNull(maybeKey, "RSA key must be provided");
int max = RsaRawEncryptor.getByteLength(maybeKey);
Defensive patterns

Strategy: validation

Validate before calling

if (key == null) {
    throw new IllegalArgumentException("RSA key must be initialized before computing byte length");
}
int max = RsaRawEncryptor.getByteLength(key);

Type guard

boolean hasKey(@Nullable RSAKey key) { return key != null && key.getModulus() != null; }

Try / catch

try {
    int len = RsaRawEncryptor.getByteLength(key);
} catch (IllegalArgumentException ex) {
    throw new IllegalStateException("Key was not configured", ex);
}

Prevention

When it happens

Trigger: Calling RsaRawEncryptor.getByteLength(null) directly, or indirectly via maxLength()/encryption helpers when the encryptor was constructed without a key (e.g. key field never initialized).

Common situations: Programmatically built RsaRawEncryptor where key injection failed or a nullable key variable was passed; tests calling getByteLength with a mock/unset key.

Related errors


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