summary refs log tree commit diff
path: root/crypto/src/x509/PrincipalUtil.cs
blob: 0edc4a3959a6df3416ad3ac92dcd9c3f80560498 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.IO;

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Security.Certificates;

namespace Org.BouncyCastle.X509
{
	/// <remarks>
	/// A utility class that will extract X509Principal objects from X.509 certificates.
	/// <p>
	/// Use this in preference to trying to recreate a principal from a string, not all
	/// DNs are what they should be, so it's best to leave them encoded where they
	/// can be.</p>
	/// </remarks>
	public class PrincipalUtilities
	{
		/// <summary>Return the issuer of the given cert as an X509Principal.</summary>
		public static X509Name GetIssuerX509Principal(
			X509Certificate cert)
		{
			try
			{
				TbsCertificateStructure tbsCert = TbsCertificateStructure.GetInstance(
					Asn1Object.FromByteArray(cert.GetTbsCertificate()));

				return tbsCert.Issuer;
			}
			catch (Exception e)
			{
				throw new CertificateEncodingException("Could not extract issuer", e);
			}
		}

		/// <summary>Return the subject of the given cert as an X509Principal.</summary>
		public static X509Name GetSubjectX509Principal(
			X509Certificate cert)
		{
			try
			{
				TbsCertificateStructure tbsCert = TbsCertificateStructure.GetInstance(
					Asn1Object.FromByteArray(cert.GetTbsCertificate()));

				return tbsCert.Subject;
			}
			catch (Exception e)
			{
				throw new CertificateEncodingException("Could not extract subject", e);
			}
		}

		/// <summary>Return the issuer of the given CRL as an X509Principal.</summary>
		public static X509Name GetIssuerX509Principal(
			X509Crl crl)
		{
			try
			{
				TbsCertificateList tbsCertList = TbsCertificateList.GetInstance(
					Asn1Object.FromByteArray(crl.GetTbsCertList()));

				return tbsCertList.Issuer;
			}
			catch (Exception e)
			{
				throw new CrlException("Could not extract issuer", e);
			}
		}
	}
}