def encode_length(length):
    """encode BER length"""
    # if given length fits one byte
    if length < 0x80:
        return '%c' % length
    # two bytes required
    elif length < 0xFF:
        return '%c%c' % (0x81, length)
    # three bytes required
    else:
        return '%c%c%c' % (0x82, (length >> 8) & 0xFF, length & 0xFF)