Java tutorial
//package com.java2s; import java.io.*; public class Main { /** * Converts an Oid in dot-separated string representation to a * DER-encoded byte array. * * @param oid Oid in dot-separated String representation * @return DER-encoded Oid byte array * */ public static byte[] OidString2DER(String oid) { int octet = 0; int base = 0; int times = 0; int tbMaj = 0; ByteArrayOutputStream bytearray = new ByteArrayOutputStream(); ByteArrayOutputStream tmpArray = new ByteArrayOutputStream(); /* Convert String to int[] */ String[] tmp = oid.split("\\."); int[] input = new int[tmp.length]; for (int i = 0; i < tmp.length; i++) { input[i] = Integer.parseInt(tmp[i]); } /* Add tag for OID (0x06) */ bytearray.write(6); /* Calculate first byte */ tmpArray.write((input[0] * 40) + input[1]); /* Encode the rest of the OID nodes in DER format */ for (int j = 2; j < input.length; j++) { if (input[j] <= 127) { /* Encode directly */ tmpArray.write(input[j]); } else if (input[j] > 127) { /* Reset variables */ octet = input[j]; base = 128; times = 0; tbMaj = 8; /* If bigger than 16383 */ if (octet > 16383) { base = 262144; times = (int) Math.floor(octet / base); tbMaj = 8 + times; octet = octet - (times * base); base = 16384; times = (int) Math.floor(octet / base); tmpArray.write((16 * tbMaj) + times); /* Reset tbMaj in case we're skipping next if */ tbMaj = 8; } /* 2047 < octet <= 16383 */ if (octet > 2047 && octet <= 16383) { base = 2048; times = (int) Math.floor(octet / base); tbMaj = 8 + times; octet = octet - (times * base); } /* 127 < octet < 2047 */ base = 128; times = (int) Math.floor(octet / base); tmpArray.write((16 * tbMaj) + times); tmpArray.write(octet - (times * 128)); } } byte[] convArray = tmpArray.toByteArray(); bytearray.write(convArray.length); for (int k = 0; k < convArray.length; k++) { bytearray.write(convArray[k]); } return bytearray.toByteArray(); } }