001: package org.bouncycastle.asn1;
002:
003: import java.io.IOException;
004: import java.math.BigInteger;
005:
006: public class DERInteger extends ASN1Object {
007: byte[] bytes;
008:
009: /**
010: * return an integer from the passed in object
011: *
012: * @exception IllegalArgumentException if the object cannot be converted.
013: */
014: public static DERInteger getInstance(Object obj) {
015: if (obj == null || obj instanceof DERInteger) {
016: return (DERInteger) obj;
017: }
018:
019: if (obj instanceof ASN1OctetString) {
020: return new DERInteger(((ASN1OctetString) obj).getOctets());
021: }
022:
023: if (obj instanceof ASN1TaggedObject) {
024: return getInstance(((ASN1TaggedObject) obj).getObject());
025: }
026:
027: throw new IllegalArgumentException(
028: "illegal object in getInstance: "
029: + obj.getClass().getName());
030: }
031:
032: /**
033: * return an Integer from a tagged object.
034: *
035: * @param obj the tagged object holding the object we want
036: * @param explicit true if the object is meant to be explicitly
037: * tagged false otherwise.
038: * @exception IllegalArgumentException if the tagged object cannot
039: * be converted.
040: */
041: public static DERInteger getInstance(ASN1TaggedObject obj,
042: boolean explicit) {
043: return getInstance(obj.getObject());
044: }
045:
046: public DERInteger(int value) {
047: bytes = BigInteger.valueOf(value).toByteArray();
048: }
049:
050: public DERInteger(BigInteger value) {
051: bytes = value.toByteArray();
052: }
053:
054: public DERInteger(byte[] bytes) {
055: this .bytes = bytes;
056: }
057:
058: public BigInteger getValue() {
059: return new BigInteger(bytes);
060: }
061:
062: /**
063: * in some cases positive values get crammed into a space,
064: * that's not quite big enough...
065: */
066: public BigInteger getPositiveValue() {
067: return new BigInteger(1, bytes);
068: }
069:
070: void encode(DEROutputStream out) throws IOException {
071: out.writeEncoded(INTEGER, bytes);
072: }
073:
074: public int hashCode() {
075: int value = 0;
076:
077: for (int i = 0; i != bytes.length; i++) {
078: value ^= (bytes[i] & 0xff) << (i % 4);
079: }
080:
081: return value;
082: }
083:
084: boolean asn1Equals(DERObject o) {
085: if (!(o instanceof DERInteger)) {
086: return false;
087: }
088:
089: DERInteger other = (DERInteger) o;
090:
091: if (bytes.length != other.bytes.length) {
092: return false;
093: }
094:
095: for (int i = 0; i != bytes.length; i++) {
096: if (bytes[i] != other.bytes[i]) {
097: return false;
098: }
099: }
100:
101: return true;
102: }
103:
104: public String toString() {
105: return getValue().toString();
106: }
107: }
|