Search code examples
javabouncycastleasn.1

How to add specific "key" to an ASN1EncodableVector in BouncyCastle?


So, I asked a similar question before but the issue has since evolved. So, I'll give you a whole overview and then I'll ask the question.

Currently, I am reading from a .yml file and parsing through it. I then store the data in a HashMap<String, ArrayList > that looks something like this:

[{p_table=[p_event/Name, p_fault/Name]}, 
{s_table=[s_event/Name, s_fault/Name]}, 
{r_table=[r_event/Name, r_fault/Name]}]

Now, I understand that if I want to create an extension with bouncycastle I first have to add all of my data into an ASN1EncodableVector. What I'm doing is using certificates to tell my IoT things what topics they can subscribe/publish/receive from. Hence, I can do something like this:

while(iterator.hasNext()) {
            Entry<String, ArrayList<String>> entry = iterator.next();
            ASN1EncodableVector vector = new ASN1EncodableVector

            for(String val : entry.getValue()) {                
                (vector).add(new DERUTF8String(val));
            }
            allowedTables.add(new DERSequence(vector));
        }

This will only add the values from the arraylist eg p_event/Name or p_fault/Name, is there a way for me to specify that those two DERUTF8String(s) belong to the p_table? Or is there some sort of identifier I can use when using the .add method?

So could the code change from something like this:

(vector).add(new DERUTF8String(val));

to:

(vector).add(new aConstructorToIdentifyWhatTheUTF8BelongsTo(entry.getKey()), new DERUTF8String(val));

Solution

  • You can nest sequences, i.e. you can build one DERSequence for each entry as you are doing and then add each of them to an outer ASN1EncodableVector and make a final sequence from that. The inner sequences could contain key/val/val if the number of values is fixed at 2 as in your example. Or you could have yet another sequence to hold the values e.g.:

    SEQUENCE {
      SEQUENCE {
        "p_table",
        SEQUENCE {
          "p_event/Name",
          "p_fault/Name",
        }
      },
      SEQUENCE {
        "s_table",
        SEQUENCE {
          "s_event/Name",
          "s_fault/Name",
          "s_other/Name",
        }
      },
      // and so on
    }