1package org.bouncycastle.asn1.pkcs;
2
3import java.math.BigInteger;
4import java.util.Enumeration;
5
6import org.bouncycastle.asn1.ASN1EncodableVector;
7import org.bouncycastle.asn1.ASN1Integer;
8import org.bouncycastle.asn1.ASN1Object;
9import org.bouncycastle.asn1.ASN1Primitive;
10import org.bouncycastle.asn1.ASN1Sequence;
11import org.bouncycastle.asn1.ASN1TaggedObject;
12import org.bouncycastle.asn1.DERSequence;
13
14public class RSAPublicKey
15    extends ASN1Object
16{
17    private BigInteger modulus;
18    private BigInteger publicExponent;
19
20    public static RSAPublicKey getInstance(
21        ASN1TaggedObject obj,
22        boolean          explicit)
23    {
24        return getInstance(ASN1Sequence.getInstance(obj, explicit));
25    }
26
27    public static RSAPublicKey getInstance(
28        Object obj)
29    {
30        if (obj instanceof RSAPublicKey)
31        {
32            return (RSAPublicKey)obj;
33        }
34
35        if (obj != null)
36        {
37            return new RSAPublicKey(ASN1Sequence.getInstance(obj));
38        }
39
40        return null;
41    }
42
43    public RSAPublicKey(
44        BigInteger modulus,
45        BigInteger publicExponent)
46    {
47        this.modulus = modulus;
48        this.publicExponent = publicExponent;
49    }
50
51    private RSAPublicKey(
52        ASN1Sequence seq)
53    {
54        if (seq.size() != 2)
55        {
56            throw new IllegalArgumentException("Bad sequence size: "
57                    + seq.size());
58        }
59
60        Enumeration e = seq.getObjects();
61
62        modulus = ASN1Integer.getInstance(e.nextElement()).getPositiveValue();
63        publicExponent = ASN1Integer.getInstance(e.nextElement()).getPositiveValue();
64    }
65
66    public BigInteger getModulus()
67    {
68        return modulus;
69    }
70
71    public BigInteger getPublicExponent()
72    {
73        return publicExponent;
74    }
75
76    /**
77     * This outputs the key in PKCS1v2 format.
78     * <pre>
79     *      RSAPublicKey ::= SEQUENCE {
80     *                          modulus INTEGER, -- n
81     *                          publicExponent INTEGER, -- e
82     *                      }
83     * </pre>
84     * <p>
85     */
86    public ASN1Primitive toASN1Primitive()
87    {
88        ASN1EncodableVector v = new ASN1EncodableVector();
89
90        v.add(new ASN1Integer(getModulus()));
91        v.add(new ASN1Integer(getPublicExponent()));
92
93        return new DERSequence(v);
94    }
95}
96