Páginas

Showing posts with label Cryptography. Show all posts
Showing posts with label Cryptography. Show all posts

Friday, July 23, 2010

DER Signing using Java and Bouncy Castle

Following my last post about DER coding in Java, I will now explain how to sign an object, using java.security.PrivateKey, java.security.cert.X509Certificate and the TSL standard as pointed in that post.

The TSL signature is an enveloped signature, that can be described by the following picture:


First let's assume that we have some previously initialized variables:
  • tslDER - Unsigned TSL object (instance of DEREncodable)
  • privateKey - Private key being used to sign
  • cert - PKI Certificate of the signer (this one is optional, but recommended)
Now let's define the algorithms used for signing and message digesting:

AlgorithmIdentifier sigAlg = new AlgorithmIdentifier(ObjectIdentifiers.getAlgorithmOID(sigAlgorithm));
ASN1Set sigAlgs = new DERSet(sigAlg);
AlgorithmIdentifier digestAlg = new AlgorithmIdentifier(ObjectIdentifiers.getAlgorithmOID(digestAlgorithm));
ASN1Set digestAlgs = new DERSet(digestAlg);


The getAlgorithmOID is a method that given a String returns the matching Object Identifier or throws an Exception.

After that, let's define the identification of the signer:

SignerIdentifier sid = null;
String[] names = cert.getIssuerDN().getName().split(",");

ASN1EncodableVector vec = new ASN1EncodableVector();
for (String name : names)
{
    ASN1EncodableVector nameVec = new ASN1EncodableVector();
    String[] vals = name.split("=");
    nameVec.add((DEREncodable) X509Name.DefaultLookUp.get(vals[0].trim().toLowerCase()));
    nameVec.add(new DERPrintableString(vals[1]));
    vec.add(new DERSequence(nameVec));
}

ASN1Set attr = new DERSet(vec);
X509Name issuer = new X509Name(new DERSequence(attr));
sid = new SignerIdentifier(new IssuerAndSerialNumber(issuer, cert.getSerialNumber()));


Now the encapsulated content info:

ContentInfo encapContent = new ContentInfo(ObjectIdentifiers.id_eContentType_signedTSL, tslDER);

The next step is building the byte array to be signed:


MessageDigest md = MessageDigest.getInstance(digestAlgorithm);
md.reset();
md.update(tslDER.getDERObject().getEncoded());

ASN1EncodableVector attrs = new ASN1EncodableVector();

ASN1EncodableVector contentTypeAttr = new ASN1EncodableVector();
contentTypeAttr.add(ObjectIdentifiers.id_contentType);
contentTypeAttr.add(ObjectIdentifiers.id_eContentType_signedTSL);
attrs.add(new DERSequence(contentTypeAttr));

ASN1EncodableVector messageDigestAttr = new ASN1EncodableVector();
messageDigestAttr.add(ObjectIdentifiers.id_messageDigest);
messageDigestAttr.add(new DEROctetString(md.digest()));
attrs.add(new DERSequence(messageDigestAttr));

ASN1Set signedAttr = new DERSet(attrs);

md.reset();
md.update(tslDER.getDERObject().getDEREncoded());
md.update(signedAttr.getDEREncoded());
byte[] data = md.digest();


And to finalize the signature:


Signature sig = Signature.getInstance(sigAlgorithm);
sig.initSign(privateKey);
sig.update(data);
byte[] signed = sig.sign();

SignerInfo signerInfo = new SignerInfo(sid, digestAlg, signedAttr, sigAlg, new DEROctetString(signed), null);
ASN1Set signerInfos = new DERSet(signerInfo);

ASN1Set certs = new DERSet(new DEROctetString(cert.getEncoded()));

SignedData signedData = new SignedData(digestAlgs, encapContent, certs, null, signerInfos);
ContentInfo content = new ContentInfo(CMSObjectIdentifiers.signedData, signedData);

DER using Java and Bouncy Castle

In the last few months I have been working with Distinguished Encoding Rules (DER) of ASN.1 a standard placed by X.509, used in cryptography. I needed to code this in Java, for which I chose to use the Bouncy Castle ASN.1 library.

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
Any of these types can be marked as OPTIONAL and have a tag, in the form [n].

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)))));