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