TheAlgorithms/Java · error · IllegalArgumentException

length must be non-negative

Error message

length must be non-negative

What it means

Thrown by OneTimePadCipher.generateKey(int) when length is negative. The method allocates new byte[length]; a negative length is illegal for array allocation, so it is rejected explicitly with a clear message rather than a NegativeArraySizeException.

Source

Thrown at src/main/java/com/thealgorithms/ciphers/OneTimePadCipher.java:36

 */
public final class OneTimePadCipher {

    private static final SecureRandom RANDOM = new SecureRandom();

    private OneTimePadCipher() {
        // utility class
    }

    /**
     * Generates a random key of the given length in bytes.
     *
     * @param length the length of the key in bytes, must be non-negative
     * @return a new random key
     * @throws IllegalArgumentException if length is negative
     */
    public static byte[] generateKey(int length) {
        if (length < 0) {
            throw new IllegalArgumentException("length must be non-negative");
        }
        byte[] key = new byte[length];
        RANDOM.nextBytes(key);
        return key;
    }

    /**
     * Encrypts the given plaintext bytes using the provided key.
     * <p>The key length must be exactly the same as the plaintext length.
     *
     * @param plaintext the plaintext bytes, must not be {@code null}
     * @param key the one-time pad key bytes, must not be {@code null}
     * @return the ciphertext bytes
     * @throws IllegalArgumentException if the key length does not match plaintext length
     * @throws NullPointerException if plaintext or key is {@code null}
     */
    public static byte[] encrypt(byte[] plaintext, byte[] key) {
        validateInputs(plaintext, key);

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Ensure length >= 0 before calling (zero is allowed and returns an empty key).
  2. Treat a negative computed length as an error upstream rather than forwarding it.
  3. Default unset lengths to 0 or fail explicitly at the source.

Example fix

// before
byte[] key = OneTimePadCipher.generateKey(requestedLen);

// after
int len = Math.max(0, requestedLen);
byte[] key = OneTimePadCipher.generateKey(len);
Defensive patterns

Strategy: validation

Validate before calling

if (length < 0) {
    throw new IllegalArgumentException("length must be non-negative");
}
byte[] key = OneTimePadCipher.generateKey(length);

Type guard

static boolean validKeyLength(int n) { return n >= 0; }

Try / catch

try {
    byte[] key = OneTimePadCipher.generateKey(length);
} catch (IllegalArgumentException e) {
    key = OneTimePadCipher.generateKey(0); // or surface the error
}

Prevention

When it happens

Trigger: Calling generateKey(length) with length < 0. Occurs when length is computed from a size that underflows or is left at a sentinel value like -1.

Common situations: Length derived from input.length() where input is unexpectedly absent; a 'not set' sentinel of -1 reaching the call; arithmetic that can go negative.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/504d503df3f50dd6. Report an issue: GitHub.