* @param value
* the value to be written.
* @return the corresponding byte array representation.
*/
private byte[] writeTLV(int tag, byte[] value) {
DatagramWriter writer = new DatagramWriter();
// write the tag
writer.write(tag, OCTET_BITS);
switch (tag) {
case BIT_STRING_TAG:
// add the unused field to the value, as described here:
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb540792(v=vs.85).aspx
byte[] unusedByte = new byte[1];
// in our cases, there are never unused bits in the last byte
unusedByte[0] = 0x00;
value = ByteArrayUtils.concatenate(unusedByte, value);
break;
default:
break;
}
int length = value.length;
if (length > 127) {
/*
* If it is more than 127 bytes, bit 7 of the Length field is set to
* 1 and bits 6 through 0 specify the number of additional bytes
* used to identify the content length.
*/
int additionalBytes = 0;
if (length >= 16777216) { // 2^24
additionalBytes = 4;
} else if (length >= 65536) { // 2^16
additionalBytes = 3;
} else if (length >= 256) { // 2^8
additionalBytes = 2;
} else {
additionalBytes = 1;
}
int lengthField = 0x80;
lengthField += additionalBytes;
writer.write(lengthField, OCTET_BITS);
writer.write(length, additionalBytes * OCTET_BITS);
} else {
/*
* If the SEQUENCE contains fewer than 128 bytes, the Length field
* of the TLV triplet requires only one byte to specify the content
* length.
*/
writer.write(length, OCTET_BITS);
}
writer.writeBytes(value);
return writer.toByteArray();
}