1 /*
2 * Copyright 2012-2025 CodeLibs Project and the Others.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13 * either express or implied. See the License for the specific language
14 * governing permissions and limitations under the License.
15 */
16 package org.codelibs.fess.ldap;
17
18 /**
19 * Utility class for LDAP operations.
20 */
21 public final class LdapUtil {
22
23 private LdapUtil() {
24 }
25
26 /**
27 * Escapes special characters in a value for use in LDAP search filters.
28 * This method escapes characters that have special meaning in LDAP filter expressions
29 * to prevent LDAP injection attacks.
30 *
31 * @param value the value to escape (null is treated as empty string)
32 * @return the escaped value safe for use in LDAP search filters
33 * @see <a href="https://tools.ietf.org/html/rfc4515">RFC 4515 - LDAP String Representation of Search Filters</a>
34 */
35 public static String escapeValue(final String value) {
36 if (value == null) {
37 return "";
38 }
39 final StringBuilder sb = new StringBuilder(value.length() * 2);
40 for (int i = 0; i < value.length(); i++) {
41 final char c = value.charAt(i);
42 switch (c) {
43 case '\\':
44 sb.append("\\5c");
45 break;
46 case '*':
47 sb.append("\\2a");
48 break;
49 case '(':
50 sb.append("\\28");
51 break;
52 case ')':
53 sb.append("\\29");
54 break;
55 case '\0':
56 sb.append("\\00");
57 break;
58 default:
59 sb.append(c);
60 }
61 }
62 return sb.toString();
63 }
64 }