I'm trying to read a custom extension from a digital certificate. I know the value is a GeneralString encoded in DER. Is there an easy way to correctly decode it and get a Java String? I tried the following, but 's' includes some of the encoding metadata as junk characters at the start of the string.
byte[] ext = cert.getExtensionValue("1.2.3.4");
String s= new String(ext);
System.out.println(s);
Is there a quick and easy way to do this? Or do I really need to use some full fledged ASN.1 library?
Thanks!
In Oracle VM (JDK 7):
http://www.docjar.com/docs/api/sun/security/util/DerValue.html
NOTE: The original question called for a "quick-and-dirty" solution, so I think this was valid back then, but since it relies on the Sun internal API, it shouldn't be used anymore especially since JDK 9 onwards.
Bouncy Castle is the proper solution for this.
This turns out to be quite straightforward with BouncyCastle:
BouncyCastle is (among everything else):
JcaX509ExtensionUtils
does what the answers above do in a much simpler way.Using instructions contained on the following page I've made some changes and the code worked fine with me.
Porting from earlier BC releases to 1.47 and later - The Legion of the Bouncy Castle http://www.bouncycastle.org/wiki/display/JA1/Porting+from+earlier+BC+releases+to+1.47+and+later