summaryrefslogtreecommitdiffstats
path: root/base/util/src/netscape/security/util/BigInt.java
blob: 9210648f124baee90e0e2aaa0a0357b97233552b (plain)
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package netscape.security.util;

import java.math.BigInteger;

/**
 * A low-overhead arbitrary-precision <em>unsigned</em> integer.
 * This is intended for use with ASN.1 parsing, and printing of
 * such parsed values. Convert to "BigInteger" if you need to do
 * arbitrary precision arithmetic, rather than just represent
 * the number as a wrapped array of bytes.
 * 
 * <P>
 * <em><b>NOTE:</b>  This class may eventually disappear, to
 * be supplanted by big-endian byte arrays which hold both signed
 * and unsigned arbitrary-precision integers.
 * 
 * @version 1.23
 * @author David Brownell
 */
public final class BigInt {

    // Big endian -- MSB first.
    private byte[] places;

    /**
     * Constructs a "Big" integer from a set of (big-endian) bytes.
     * Leading zeroes should be stripped off.
     * 
     * @param data a sequence of bytes, most significant bytes/digits
     *            first. CONSUMED.
     */
    public BigInt(byte[] data) {
        places = data.clone();
    }

    /**
     * Constructs a "Big" integer from a "BigInteger", which must be
     * positive (or zero) in value.
     */
    public BigInt(BigInteger i) {
        byte[] temp = i.toByteArray();

        if ((temp[0] & 0x80) != 0)
            throw new IllegalArgumentException("negative BigInteger");

        // XXX we assume exactly _one_ sign byte is used...

        if (temp[0] != 0)
            places = temp;
        else {
            // Note that if i = new BigInteger("0"),
            // i.toByteArray() contains only 1 zero.
            if (temp.length == 1) {
                places = new byte[1];
                places[0] = (byte) 0;
            } else {
                places = new byte[temp.length - 1];
                for (int j = 1; j < temp.length; j++)
                    places[j - 1] = temp[j];
            }
        }
    }

    /**
     * Constructs a "Big" integer from a normal Java integer.
     * 
     * @param i the java primitive integer
     */
    public BigInt(int i) {
        if (i < (1 << 8)) {
            places = new byte[1];
            places[0] = (byte) i;
        } else if (i < (1 << 16)) {
            places = new byte[2];
            places[0] = (byte) (i >> 8);
            places[1] = (byte) i;
        } else if (i < (1 << 24)) {
            places = new byte[3];
            places[0] = (byte) (i >> 16);
            places[1] = (byte) (i >> 8);
            places[2] = (byte) i;
        } else {
            places = new byte[4];
            places[0] = (byte) (i >> 24);
            places[1] = (byte) (i >> 16);
            places[2] = (byte) (i >> 8);
            places[3] = (byte) i;
        }
    }

    /**
     * Converts the "big" integer to a java primitive integer.
     * 
     * @exception NumberFormatException if 32 bits is insufficient.
     */
    public int toInt() {
        if (places.length > 4)
            throw new NumberFormatException("BigInt.toInt, too big");
        int retval = 0, i = 0;
        for (; i < places.length; i++)
            retval = (retval << 8) + ((int) places[i] & 0xff);
        return retval;
    }

    /**
     * Returns a hexadecimal printed representation. The value is
     * formatted to fit on lines of at least 75 characters, with
     * embedded newlines. Words are separated for readability,
     * with eight words (32 bytes) per line.
     */
    public String toString() {
        return hexify();
    }

    /**
     * Returns a BigInteger value which supports many arithmetic
     * operations. Assumes negative values will never occur.
     */
    public BigInteger toBigInteger() {
        return new BigInteger(1, places);
    }

    /**
     * Returns the length of the data as a byte array.
     */
    public int byteLength() {
        return places.length;
    }

    /**
     * Returns the data as a byte array. The most significant bit
     * of the array is bit zero (as in <code>java.math.BigInteger</code>).
     */
    public byte[] toByteArray() {
        if (places.length == 0) {
            byte zero[] = new byte[1];
            zero[0] = (byte) 0;
            return zero;
        } else {
            return places.clone();
        }
    }

    private static final String digits = "0123456789abcdef";

    private String hexify() {
        if (places.length == 0)
            return "  0  ";

        StringBuffer buf = new StringBuffer(places.length * 2);
        buf.append("    "); // four spaces
        for (int i = 0; i < places.length; i++) {
            buf.append(digits.charAt((places[i] >> 4) & 0x0f));
            buf.append(digits.charAt(places[i] & 0x0f));
            if (((i + 1) % 32) == 0) {
                if ((i + 1) != places.length)
                    buf.append("\n    "); // line after four words
            } else if (((i + 1) % 4) == 0)
                buf.append(' '); // space between words
        }
        return buf.toString();
    }

    /**
     * Returns true iff the parameter is a numerically equivalent
     * BigInt.
     * 
     * @param other the object being compared with this one.
     */
    public boolean equals(Object other) {
        if (other instanceof BigInt)
            return equals((BigInt) other);
        return false;
    }

    /**
     * Returns true iff the parameter is numerically equivalent.
     * 
     * @param other the BigInt being compared with this one.
     */
    public boolean equals(BigInt other) {
        if (this == other)
            return true;

        byte[] otherPlaces = other.toByteArray();
        if (places.length != otherPlaces.length)
            return false;
        for (int i = 0; i < places.length; i++)
            if (places[i] != otherPlaces[i])
                return false;
        return true;
    }
}