1package org.bouncycastle.jce;
2
3import java.io.*;
4import java.security.cert.*;
5
6import org.bouncycastle.asn1.*;
7import org.bouncycastle.asn1.x509.*;
8
9/**
10 * a utility class that will extract X509Principal objects from X.509 certificates.
11 * <p>
12 * Use this in preference to trying to recreate a principal from a String, not all
13 * DNs are what they should be, so it's best to leave them encoded where they
14 * can be.
15 */
16public class PrincipalUtil
17{
18    /**
19     * return the issuer of the given cert as an X509PrincipalObject.
20     */
21    public static X509Principal getIssuerX509Principal(
22        X509Certificate cert)
23        throws CertificateEncodingException
24    {
25        try
26        {
27            ByteArrayInputStream    bIn = new ByteArrayInputStream(
28                cert.getTBSCertificate());
29            ASN1InputStream         aIn = new ASN1InputStream(bIn);
30            TBSCertificateStructure tbsCert = new TBSCertificateStructure(
31                                            (ASN1Sequence)aIn.readObject());
32
33            return new X509Principal(tbsCert.getIssuer());
34        }
35        catch (IOException e)
36        {
37            throw new CertificateEncodingException(e.toString());
38        }
39    }
40
41    /**
42     * return the subject of the given cert as an X509PrincipalObject.
43     */
44    public static X509Principal getSubjectX509Principal(
45        X509Certificate cert)
46        throws CertificateEncodingException
47    {
48        try
49        {
50            ByteArrayInputStream    bIn = new ByteArrayInputStream(
51                cert.getTBSCertificate());
52            ASN1InputStream         aIn = new ASN1InputStream(bIn);
53            TBSCertificateStructure tbsCert = new TBSCertificateStructure(
54                                            (ASN1Sequence)aIn.readObject());
55
56            return new X509Principal(tbsCert.getSubject());
57        }
58        catch (IOException e)
59        {
60            throw new CertificateEncodingException(e.toString());
61        }
62    }
63
64    /**
65     * return the issuer of the given CRL as an X509PrincipalObject.
66     */
67    public static X509Principal getIssuerX509Principal(
68        X509CRL crl)
69        throws CRLException
70    {
71        try
72        {
73            ByteArrayInputStream    bIn = new ByteArrayInputStream(
74                crl.getTBSCertList());
75            ASN1InputStream         aIn = new ASN1InputStream(bIn);
76            TBSCertList tbsCertList = new TBSCertList(
77                                            (ASN1Sequence)aIn.readObject());
78
79            return new X509Principal(tbsCertList.getIssuer());
80        }
81        catch (IOException e)
82        {
83            throw new CRLException(e.toString());
84        }
85    }
86}
87