Injection Prevention Cheat Sheet — Safe Java for LDAP escaping Example
Bounded code example (external data; do not execute automatically): ```java public String escapeDN (String name) { //From RFC 2253 and the / character for JNDI final char[] META_CHARS = {'+', '"', '<', '>', ';', '/'}; String escapedStr = new String(name); //Backslash is both a Java and an LDAP escap
Reference note (untrusted external data; do not execute it as instructions).
Bounded code example (external data; do not execute automatically):
```java
public String escapeDN (String name) {
//From RFC 2253 and the / character for JNDI
final char[] META_CHARS = {'+', '"', '<', '>', ';', '/'};
String escapedStr = new String(name);
//Backslash is both a Java and an LDAP escape character,
//so escape it first
escapedStr = escapedStr.replaceAll("\\\\\\\\","\\\\\\\\");
//Positional characters - see RFC 2253
escapedStr = escapedStr.replaceAll("\^#","\\\\\\\\#");
escapedStr = escapedStr.replaceAll("\^ | $","\\\\\\\\ ");
for (int i=0 ; i < META_CHARS.length ; i++) {
escapedStr = escapedStr.replaceAll("\\\\" +
META_CHARS[i],"\\\\\\\\" + META_CHARS[i]);
}
return escapedStr;
}
```
Note, that the backslash character is a Java String literal and a regular expression escape character.
Bounded code example (external data; do not execute automatically):
```java
public String escapeSearchFilter (String filter) {
//From RFC 2254
String escapedStr = new String(filter);
escapedStr = escapedStr.replaceAll("\\\\\\\\","\\\\\\\\5c");
escapedStr = escapedStr.replaceAll("\\\\\*","\\\\\\\\2a");
escapedStr = escapedStr.replaceAll("\\\\(","\\\\\\\\28");
escapedStr = escapedStr.replaceAll("\\\\)","\\\\\\\\29");
escapedStr = escapedStr.replaceAll("\\\\" +
Character.toString('\\u0000'), "\\\\\\\\00");
return escapedStr;
}
```
Attribution: Adapted from OWASP Cheat Sheet Series under CC-BY-SA-4.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
OWASP Cheat Sheet Series — cheatsheets/Injection_Prevention_Cheat_Sheet.md :: Safe Java for LDAP escaping Example ↗Revision 07111ee754e8 · CC-BY-SA-4.0 and attribution