DER has some primitives that let's you define the various structures and types needed for your endeavors. Here are some:
- Sequence
- Choice
- IA5String
- PrintableString
- Integer
- Object Identifier
- GeneralizedTime
- Boolean
- OctetString
As an example I shall use the Trust-service Status List ETSI TS 102 231 V3.1.2 standard specification.
A sequence:
LangPointer ::= SEQUENCE {
languageTag LanguageTag,
uRI NonEmptyURI
}
Encoding:
ASN1EncodableVector vec = new ASN1EncodableVector();
vec.add(LanguageTag);
vec.add(NonEmptyURI);
DERSequence seq = new DERSequence(vec);
Decoding:
DEREncodable obj = ...;
DERSequence tslscheme = (DERSequence) obj;
Enumeration e = tslscheme.getObjects();
LanguageTag lt = (LanguageTag) e.nextElement();
A choice:
TSLpolicy ::= CHOICE {
pointer [0] MultiLangPointer,
text [1] MultiLangString
}
Encoding (using a sequence):
if(multiLangPointer != null)
vec.add(new DERTaggedObject(0, MultiLangPointer));
else if(multiLangString !=null)
vec.add(new DERTaggedObject(1, MultiLangString));
Decoding:
while(e.hasMoreElements())
{
DERTaggedObject tagged = (DERTaggedObject) e.nextElement();
switch (tagged.getTagNo())
{
case 0: multiLangPointer = tagged.getObject(); break;
case 1: multiLangString = tagged.getObject(); break;
}
}
The primitive types are all encoded and decoded in a similar way, the only thing changing being the name, therefore I will only give one example:
NonEmptyURI ::= IA5String (SIZE (1..MAX))
Encoding:
DERIA5String neuri = new DERIA5String(String);
Decoding (in a sequence):
DERIA5String neuri = (DERIA5String) e.nextElement();
String str = type.getString();
A little bit trickier is casting a DERGeneralizedTime to a GregorianCalendar, but here's how you do it:
DERGeneralizedTime issueTime = (DERGeneralizedTime) e.nextElement();
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddkkmmss");
GregorianCalendar greg = new GregorianCalendar();
greg.setTime(f.parse(issueTime.getTimeString()));
The date format can be changed as you see fit, to do what you need.
The last thing are the OPTIONALS, that are very much like a CHOICE, except that there can be more than one at the same time. Even though, the encoding and decoding are done in the same way, using DERTaggedObjects.
To write and read from DER encoded files, you can use ASN1Streams, initialized like this:
ASN1InputStream ain = new ASN1InputStream(new DataInputStream(new BufferedInputStream(new FileInputStream(new File(file)))));
No comments:
Post a Comment