summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/uic/barcode/asn1/uper/ObjectIdentifierCoder.java
blob: 2835e10af60653de049206baffe79767a6267f2b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package org.uic.barcode.asn1.uper;

import java.io.ByteArrayOutputStream;
import java.math.BigInteger;

public class ObjectIdentifierCoder {
	
	
/*
	OID encoding for dummies :) :

	each OID component is encoded to one or more bytes (octets)
	
	OID encoding is just a concatenation of these OID component encodings
	
	first two components are encoded in a special way (see below)
	
	if OID component binary value has less than 7 bits, the encoding is just a single octet, 
	holding the component value (note, most significant bit, leftmost, will always be 0)
	otherwise, if it has 8 and more bits, the value is "spread" into multiple octets - split the 
	binary representation into 7 bit chunks (from right), left-pad the first one with zeroes if needed,
	and form octets from these septets by adding most significant (left) bit 1, except from the last 
	chunk, which will have bit 0 there.
	
	first two components (X.Y) are encoded like it is a single component with a value 40*X + Y
	
	This is a rewording of ITU-T recommendation X.690, chapter 8.19
	
*/
	
	/*
	 * 
The first octet has value 40 * value1 + value2. (This is unambiguous, since value1 is limited to values 0, 1, and 2; value2 is limited to the range 0 to 39 when value1 is 0 or 1; and, according to X.208, n is always at least 2.)

The following octets, if any, encode value3, ..., valuen. 
Each value is encoded base 128, most significant digit first, with as few digits as possible, and the most significant bit of each octet except the last in the value's encoding set to "1."

Example: The first octet of the BER encoding of RSA Data Security, Inc.'s object identifier is 40 * 1 + 2 = 42 = 2a16. The encoding of 840 = 6 * 128 + 4816 is 86 48 and the encoding of 113549 = 6 * 1282 + 7716 * 128 + d16 is 86 f7 0d. This leads to the following BER encoding:

06 06 2a 86 48 86 f7 0d
	 */
	
    private static final Long LONG_LIMIT = (Long.MAX_VALUE >> 7) - 0x7f;	
	
    
    /*
     * adaptation of the bouncy castle implementation available at bouncy castle under APACHE 2.0 license
     */
	public static String decodeObjectId(byte[] bytes) {
		
		StringBuffer objId = new StringBuffer();
	    long value = 0;
	    BigInteger bigValue = null;
	    boolean first = true;

	    for (int i = 0; i != bytes.length; i++)   {
	     
	    	int b = bytes[i] & 0xff;

	        if (value <= LONG_LIMIT)   {
	        	value += (b & 0x7f);
	            if ((b & 0x80) == 0)    {      // end of number reached
	            	
	            	if (first) {
	            		if (value < 40) {
	            			objId.append('0');
	            		} else if (value < 80) {
	            			objId.append('1');
	            			value -= 40;
	                    } else {
	                    	objId.append('2');
	                    	value -= 80;
	                    }
	            		first = false;
	            	}

	            	objId.append('.');
	            	objId.append(value);
	            	value = 0;
	            } else {
	            	value <<= 7;
	            }
	        } else {
	        	if (bigValue == null) {
	        		bigValue = BigInteger.valueOf(value);
	            }
	            bigValue = bigValue.or(BigInteger.valueOf(b & 0x7f));
	            if ((b & 0x80) == 0) {
	            	if (first) {
	            		objId.append('2');
	            		bigValue = bigValue.subtract(BigInteger.valueOf(80));
	            		first = false;
	            	}
	            	objId.append('.');
	            	objId.append(bigValue);
	            	bigValue = null;
	            	value = 0;
	            } else {
	            	bigValue = bigValue.shiftLeft(7);
	            }
	        }
	    }

	    return objId.toString();

	}
	
	
	public static byte[] encodeObjectId(String oids) {
		
		String[] components = oids.split("\\.");
		
		if (components.length < 2)   throw new AssertionError("Object Identifier Format error (" + oids + ")");

		try {
			int first = Integer.parseInt(components[0]) * 40;
		
			ByteArrayOutputStream aOut = new ByteArrayOutputStream();

		
			if (components[1].length() <= 18) {
				writeField(aOut, first + Long.parseLong(components[1]));
			} else {
				writeField(aOut, new BigInteger(components[1]).add(BigInteger.valueOf(first)));
			}
		
			for (int i = 2; i < components.length; i++) {
			
				if (components[i].length() <= 18) {
					writeField(aOut, Long.parseLong(components[i]));
	       		} else {
	       			writeField(aOut, new BigInteger(components[i]));
	       		}
			}

			return aOut.toByteArray();
		
		} catch (NumberFormatException e) {
			 throw new AssertionError("Object Identifier Format error (" + oids + ")");
		}
	}
	

    private static void writeField(ByteArrayOutputStream out, long fieldValue)
    {
        byte[] result = new byte[9];
        int pos = 8;
        result[pos] = (byte)((int)fieldValue & 0x7f);
        while (fieldValue >= (1L << 7)) {
            fieldValue >>= 7;
            result[--pos] = (byte)((int)fieldValue & 0x7f | 0x80);
        }
        out.write(result, pos, 9 - pos);
    }

    private static void writeField(ByteArrayOutputStream out, BigInteger fieldValue)
    {
        int byteCount = (fieldValue.bitLength() + 6) / 7;
        if (byteCount == 0)  {
            out.write(0);
        } else {
            BigInteger tmpValue = fieldValue;
            byte[] tmp = new byte[byteCount];
            for (int i = byteCount - 1; i >= 0; i--) {
                tmp[i] = (byte)((tmpValue.intValue() & 0x7f) | 0x80);
                tmpValue = tmpValue.shiftRight(7);
            }
            tmp[byteCount - 1] &= 0x7f;
            out.write(tmp, 0, tmp.length);
        }
    }
    

	
}