def _escape_dn_value(val):
    """Escape special characters in RFC4514 Distinguished Name value."""
    if not val:
        return ''
    val = val.replace('\\', '\\\\')
    val = val.replace('"', '\\"')
    val = val.replace('+', '\\+')
    val = val.replace(',', '\\,')
    val = val.replace(';', '\\;')
    val = val.replace('<', '\\<')
    val = val.replace('>', '\\>')
    val = val.replace('\x00', '\\00')
    if val[0] in ('#', ' '):
        val = '\\' + val
    if val[-1] == ' ':
        val = val[:-1] + '\\ '
    return val
