How to create a parseable instance of BouncyCastle Extension object?

The BouncyCastle libraries provide a systematic and simple set of APIs and tools to work with encryption and encoding of data to be used in secure communication channels like HTTPS. The X.509 standard is the standard for creating certificates issued to Certificate Authorities (CA) and End Entities.

Jave provides the X509Certificate class to create X.509 certificates. It also provides the concept of Certificate Extensions to supply additional information about the subject (often called "Subject Principal") for which the certificate has been issued.

The BouncyCastle libraries provide a convenient way to add a Certificate Extension to an instance of X509Certificate class as shown below:
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.cert.X509V3CertificateBuilder;
....
...
String caName = ...
String subjectName =  ...
KeyPair pair = KeyGenerator.getInstance("RSA").generateKeyPair();
X509v3CertificateBuilder builder = new X509v3CertificateBuilder(
                createSimpleDN(caName), valueOf(System.currentTimeMillis()),
                notBefore, notAfter, createSimpleDN(subjectName),
                getInstance(pair.getPublic().getEncoded()));
builder.addExtension("1.3.6.1.5.5.7.48.1", false, new DERIA5String("http://crl.cacert.org/revoke.crl")   // Sample CRL 
But in the above code snippet, instead of passing the values to the addExtension method, if you have an instance of org.bouncycastle.asn1.x509.Extension object, how would you use it? Unfortunately the org.bouncycastle.cert.X509V3CertificateBuilder does not provide a 
builder.addExtension(<extension object>) // not available, oops!!
variant.

The solution is to pass the OID, isCritical and Value fields of the org.bouncycastle.asn1.x509.Extension object.

But oh wait, you see that org.bouncycastle.asn1.x509.Extension provides two methods that return value, namely:

  • getExtValue  - this returns the ASN1OctetString corresponding to the value used when creating the instance of org.bouncycastle.asn1.x509.Extensio)  
  • getParsedValue - this returns the corresponding ASN1Primitive of the value set during object construction
Both seem to be equally applicable/correct. Which one do you use?

Turns out that if you use getExtValue(), you will see the 
Invalid encoding exception
when the extension is stored in the java.security.cert.X509Certificate object (i.e. if you try to fetch the extension value from the object)

The getParsedValue() should be used instead to get the extension properly loaded into the java.security.cert.X509Certificate object as shown below:
builder.addExtension(extension.getExtOid(), extension.isCritical(),  extension.getParsedValue());
Hope that this article helps when you are stuck with a similar encoding exception as I faced.

Please leave your comments on this article. 






How to use Rails I18n fallback key in conjunction with parameter list?

When using I18n rails API, you will most likely find examples of how to use parameter lists to the translation API.

For e.g.

If you have the following entry in your en.yml
          en:
               test_message_specific: "This is a specific test message for user %{user}"

Now if you have to use this key along with a parameter, you will most likely specify

I18n.t("test_message_specific", user: "Bob")

If you want to use a default key if the specified key is not available, again the API provides clear examples for this case:

E.g.

  en:
       test_message_specific: "This is a specific test message"
       test_message_default "This is a default test message"

We will then translate as follows:

I18n.t("test_message_specific", default: t("test_message_default"))

But what if we want to have both, i.e. parameter lists and default key as well, with both the specified key and default key needing same number of parameters? At least I could not find clear examples for this case from the API but it does support this. Now when will you need this? Let's say, you have a key whose value has to be overridden for say a few cases (say a few countries where the application is used), but for most other cases you want to use a default key, wouldn't it be easy if we are able to declare just as many custom keys instead of many repeated keys even for countries that don't need customisation?

E.g. if our application is used in US, UK, and Canada (this list is small but you will really feel the pinch if you have a long list and had to duplicate the same key for every case unless Rails I18n API provided this feature), and let's say we want to override only for Canada, then we can simply declare only two keys,

e.g.
      en: 
          test_message_default: "This is the default test message for %{user}"
          test_message_ca: "This is the canadian test message for %{user}"

Now let's see how to use the I18n API with these keys:

I18n.t("test_message_"+@country, default: I18n.t("test_message_default"), user: @user)

and ....

Voila! It works! When country is CA, it uses Canadian message and substitutes the "user" parameter, else it uses the default message, but still substitutes the parameter.


PS: Please leave your comment on this post (as long as it is not abusive ;)), as it will help me understand the usefulness.

How to specify web application-specific custom URL rewrites when using Tomcat server?

Recently, I had been working on a UI project where we used Ember.js as the MVC framework to render screens for the single-page application we were building.

One of the advantages that MVC frameworks like Ember.js and Angular.js provide us is the support for HTML5 pushState functionality using the history feature. This history feature allows the user to navigate back to previous screens of the single-page application easily. 

But the downside is that they append the route information to the end of the application-context, thereby creating new URLs that cannot be individually bookmarked. For example, if I had a route /Screen1 as a route that takes me to the Screen1 of my application, these frameworks automatically navigate to a URL like http://localhost:8080/<APP>/Screen1, where <APP> is my application-context. As we can see, this URL in itself cannot be bookmarked as Tomcat as no idea of this URL in isolation. This can lead to unforeseen errors that the user is not going to like. The requirement is that whenever URLs of the form http://localhost:8080/<APP>/* is hit, except for static content, all other relative URLs has to be served by the application and not try to be resolved by Tomcat server. How do we achieve this?

One way to achieve this is using Apache HTTP server and configuring URL re-writes. But what if you do not have Apache HTTP server already installed or do not want to introduce one into your eco-system just for this requirement? UrlRewriteFilter comes to the rescue.

I am not delving into the usages of this particular library and the filter as such, which we can find in abundance in the aforementioned website, but capturing a few points I noted when trying to figure out the right way to configure URL rewrites (I haven't written mod_rewrite modules,  so those of us who have used it may find it simpler enough).

  1. The application-context is not part of your from element in the rule. I did not figure this out initially, but later when I removed it, the redirects were happening properly. So specify only the part after application-context that you want to rewrite, e.g. for rewriting http://localhost:8080/<APP>/Screen1, specify a pattern that includes just /Screen1 and rewrite to the in-built variable %{context-path}.
  2. Use a simple regex pattern like the one below to exclude static content from the application of the rules.  e.g. ^/(?:(?!images|scripts|styles).)+$ excludes all URLs of the form /<APP-CONTEXT>/images, /<APP-CONTEXT>/scripts and /<APP-CONTEXT>/styles normally and does not do any redirects for these static content.
PS: Please leave your comment on this post (as long as it is not abusive ;)), as it will help me understand the usefulness.

The unobvious difference between split method in String class and the default split method in StringUtils

Programmers who have dabbled excessively with String manipulation in Java and have used the split method offered by Java's String class and the one offered by StringUtils class from Apache Commons library inter-changeably must have come across the subtle difference mentioned below some time.

The difference lies in how the two split methods consider an empty token before the first occurrence of the delimiter. The 'split' method in String class includes the empty token while the one offered by StringUtils does not.

E.g.

",1,2,3,".split(",") - returns the array [<>, <1>, <2>, <3>] (the '<>' used intentionally to illustrate the empty token). Trailing tokens are anyway discarded by even this split method (refer Javadoc)

StringUtils.split(",1,2,3,") - returns the array [<1>, <2>, <3>] (note the empty token is not returned here).

The difference lies in the way 'split' in String class works. It internally uses Matcher and Pattern and the one line comment below in Matcher explains the reason:
public String[] split(CharSequence input, int limit) {
        ...
        ...

        Matcher m = matcher(input);

        // Add segments before each match found
        while(m.find()) {
        ...
        ...
}
The StringUtils class also has a mechanism to preserve all tokens but the default split method passes false to this parameter and hence the difference.

P.S.: This class however has the 'splitPreserveAllTokens' method and its overloaded variants that retain even trailing tokens (which is the main difference between this set of methods and the 'split' in String class).

So for e.g.

StringUtils.splitPreserveAllTokens(",1,2,3,") - returns the array [<>,<1>, <2>, <3>,<>]

PS: Please leave your comment on this post (as long as it is not abusive ;)), as it will help me understand the usefulness.

Blog Archive

Powered by Blogger.

Followers