1 package org.bouncycastle.asn1; 2 3 import java.io.IOException; 4 import java.math.BigInteger; 5 6 import org.bouncycastle.util.Arrays; 7 8 public class DERInteger 9 extends ASN1Object 10 { 11 byte[] bytes; 12 13 /** 14 * return an integer from the passed in object 15 * 16 * @exception IllegalArgumentException if the object cannot be converted. 17 */ 18 public static DERInteger getInstance( 19 Object obj) 20 { 21 if (obj == null || obj instanceof DERInteger) 22 { 23 return (DERInteger)obj; 24 } 25 26 if (obj instanceof ASN1OctetString) 27 { 28 return new DERInteger(((ASN1OctetString)obj).getOctets()); 29 } 30 31 if (obj instanceof ASN1TaggedObject) 32 { 33 return getInstance(((ASN1TaggedObject)obj).getObject()); 34 } 35 36 throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); 37 } 38 39 /** 40 * return an Integer from a tagged object. 41 * 42 * @param obj the tagged object holding the object we want 43 * @param explicit true if the object is meant to be explicitly 44 * tagged false otherwise. 45 * @exception IllegalArgumentException if the tagged object cannot 46 * be converted. 47 */ 48 public static DERInteger getInstance( 49 ASN1TaggedObject obj, 50 boolean explicit) 51 { 52 return getInstance(obj.getObject()); 53 } 54 55 public DERInteger( 56 int value) 57 { 58 bytes = BigInteger.valueOf(value).toByteArray(); 59 } 60 61 public DERInteger( 62 BigInteger value) 63 { 64 bytes = value.toByteArray(); 65 } 66 67 public DERInteger( 68 byte[] bytes) 69 { 70 this.bytes = bytes; 71 } 72 73 public BigInteger getValue() 74 { 75 return new BigInteger(bytes); 76 } 77 78 /** 79 * in some cases positive values get crammed into a space, 80 * that's not quite big enough... 81 */ 82 public BigInteger getPositiveValue() 83 { 84 return new BigInteger(1, bytes); 85 } 86 87 void encode( 88 DEROutputStream out) 89 throws IOException 90 { 91 out.writeEncoded(INTEGER, bytes); 92 } 93 94 public int hashCode() 95 { 96 int value = 0; 97 98 for (int i = 0; i != bytes.length; i++) 99 { 100 value ^= (bytes[i] & 0xff) << (i % 4); 101 } 102 103 return value; 104 } 105 106 boolean asn1Equals( 107 DERObject o) 108 { 109 if (!(o instanceof DERInteger)) 110 { 111 return false; 112 } 113 114 DERInteger other = (DERInteger)o; 115 116 return Arrays.areEqual(bytes, other.bytes); 117 } 118 119 public String toString() 120 { 121 return getValue().toString(); 122 } 123 } 124