{"record":{"id":"504d503df3f50dd6","repo":"TheAlgorithms/Java","slug":"length-must-be-non-negative","errorCode":null,"errorMessage":"length must be non-negative","messagePattern":"length must be non-negative","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/ciphers/OneTimePadCipher.java","lineNumber":36,"sourceCode":" */\npublic final class OneTimePadCipher {\n\n    private static final SecureRandom RANDOM = new SecureRandom();\n\n    private OneTimePadCipher() {\n        // utility class\n    }\n\n    /**\n     * Generates a random key of the given length in bytes.\n     *\n     * @param length the length of the key in bytes, must be non-negative\n     * @return a new random key\n     * @throws IllegalArgumentException if length is negative\n     */\n    public static byte[] generateKey(int length) {\n        if (length < 0) {\n            throw new IllegalArgumentException(\"length must be non-negative\");\n        }\n        byte[] key = new byte[length];\n        RANDOM.nextBytes(key);\n        return key;\n    }\n\n    /**\n     * Encrypts the given plaintext bytes using the provided key.\n     * <p>The key length must be exactly the same as the plaintext length.\n     *\n     * @param plaintext the plaintext bytes, must not be {@code null}\n     * @param key the one-time pad key bytes, must not be {@code null}\n     * @return the ciphertext bytes\n     * @throws IllegalArgumentException if the key length does not match plaintext length\n     * @throws NullPointerException if plaintext or key is {@code null}\n     */\n    public static byte[] encrypt(byte[] plaintext, byte[] key) {\n        validateInputs(plaintext, key);","sourceCodeStart":18,"sourceCodeEnd":54,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/ciphers/OneTimePadCipher.java#L18-L54","documentation":"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.","triggerScenarios":"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.","commonSituations":"Length derived from input.length() where input is unexpectedly absent; a 'not set' sentinel of -1 reaching the call; arithmetic that can go negative.","solutions":["Ensure length >= 0 before calling (zero is allowed and returns an empty key).","Treat a negative computed length as an error upstream rather than forwarding it.","Default unset lengths to 0 or fail explicitly at the source."],"exampleFix":"// before\nbyte[] key = OneTimePadCipher.generateKey(requestedLen);\n\n// after\nint len = Math.max(0, requestedLen);\nbyte[] key = OneTimePadCipher.generateKey(len);","handlingStrategy":"validation","validationCode":"if (length < 0) {\n    throw new IllegalArgumentException(\"length must be non-negative\");\n}\nbyte[] key = OneTimePadCipher.generateKey(length);","typeGuard":"static boolean validKeyLength(int n) { return n >= 0; }","tryCatchPattern":"try {\n    byte[] key = OneTimePadCipher.generateKey(length);\n} catch (IllegalArgumentException e) {\n    key = OneTimePadCipher.generateKey(0); // or surface the error\n}","preventionTips":["Clamp computed lengths to >= 0 (zero is valid).","Treat sentinel -1 as an upstream error, not a length.","Derive length from the actual message size."],"tags":["cryptography","ciphers","one-time-pad","java","validation","illegalargumentexception"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}