title: BER Encoding of a "Choice"
body: <p>I am trying to parse an LDAP bind request using the Apache Harmony ASN.1/BER classes (could use another library, I just chose that as it has an Apache License).</p>
  
  <p>My question is on the encoding specifically of a "CHOICE" in ASN.1.  The RFC that defines the LDAP ASN.1 schema (<a href="http://www.rfc-editor.org/rfc/rfc2251.txt" rel="nofollow">http://www.rfc-editor.org/rfc/rfc2251.txt</a>) gives the following as part a bind request:</p>
  
  <pre><code>   BindRequest ::= [APPLICATION 0] SEQUENCE {
              version                 INTEGER (1 .. 127),
              name                    LDAPDN,
              authentication          AuthenticationChoice }
  
      AuthenticationChoice ::= CHOICE {
              simple                  [0] OCTET STRING,
                                       -- 1 and 2 reserved
              sasl                    [3] SaslCredentials }
  
      SaslCredentials ::= SEQUENCE {
              mechanism               LDAPString,
              credentials             OCTET STRING OPTIONAL }
  </code></pre>
  
  <p>How is that CHOICE there actually encoded?  </p>
  
  <p>I generated a sample bind request using JXplorer and captured the raw data that was sent.  It looks like this:</p>
  
  <pre><code>00000000  30 31 02 01 01 60 2c 02  01 03 04 1b 75 69 64 3d  |01...`,.....uid=|
  00000010  74 65 73 74 75 73 65 72  2c 64 63 3d 74 65 73 74  |testuser,dc=test|
  00000020  2c 64 63 3d 63 6f 6d 80  0a 74 65 73 74 69 6e 67  |,dc=com..testing|
  00000030  31 32 33                                          |123|
  </code></pre>
  
  <p>The 80 there (at offset 0x27) seems to represent that choice.  Fair enough - and I get that (per <a href="http://en.wikipedia.org/wiki/Basic_Encoding_Rules#BER_encoding" rel="nofollow">http://en.wikipedia.org/wiki/Basic_Encoding_Rules#BER_encoding</a>) the last bit is set in order to indicate that it's "context specific" (i.e. defined by this application/protocol)  But how would I know if this is a "simple" or "sasl" auth?  What indicates which option of the choice is being used?  In this case it looks like the next byte (0x0a) is the length of the string - so this could be an OctetString or something of the sort - but I don't see anything here that indicates what the actual is other than 0x80...</p>
  
  <p>I'm also not sure what the [0] and [3] mean in the CHOICE section above.  Is that saying there are four options but only options numbered 0 and 3 are in use?</p>