Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I decode a DER encoded string in Java?

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!

like image 816
Ragesh Avatar asked Mar 09 '10 14:03

Ragesh


People also ask

How do you decode a string in Java?

decode(encodedString); String actualString= new String(actualByte); Explanation: In above code we called Base64. Decoder using getDecoder() and then decoded the string passed in decode() method as parameter then convert return value to string.

How do I change the encoding of a string in Java?

Strings are immutable in Java, which means we cannot change a String character encoding. To achieve what we want, we need to copy the bytes of the String and then create a new one with the desired encoding.

Are Java strings UTF 8?

String objects in Java are encoded in UTF-16. Java Platform is required to support other character encodings or charsets such as US-ASCII, ISO-8859-1, and UTF-8. Errors may occur when converting between differently coded character data. There are two general types of encoding errors.


1 Answers

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

private String getExtensionValue(X509Certificate X509Certificate, String oid) throws IOException
{
    String decoded = null;
    byte[] extensionValue = X509Certificate.getExtensionValue(oid);

    if (extensionValue != null)
    {
        ASN1Primitive derObject = toDERObject(extensionValue);
        if (derObject instanceof DEROctetString)
        {
            DEROctetString derOctetString = (DEROctetString) derObject;

            derObject = toDERObject(derOctetString.getOctets());
            if (derObject instanceof ASN1String)
            {
                ASN1String s = (ASN1String)derObject;
                decoded = s.getString();
            }

        }
    }
    return decoded;
}

/**
 * From http://stackoverflow.com/questions/2409618/how-do-i-decode-a-der-encoded-string-in-java
 */
private ASN1Primitive toDERObject(byte[] data) throws IOException
{
    ByteArrayInputStream inStream = new ByteArrayInputStream(data);
    ASN1InputStream asnInputStream = new ASN1InputStream(inStream);

    return asnInputStream.readObject();
}
like image 129
agnoldo Avatar answered Sep 22 '22 18:09

agnoldo