summary refs log tree commit diff
path: root/crypto/src/crmf/CertificateRepMessage.cs
blob: 756021981a7cf6c192bc57e67db33ed0650b7ee4 (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;

using Org.BouncyCastle.Asn1.Cmp;
using Org.BouncyCastle.X509;

namespace Org.BouncyCastle.Crmf
{
    public class CertificateRepMessage
    {
        public static CertificateRepMessage FromPkiBody(PkiBody pkiBody)
        {
            if (!IsCertificateRepMessage(pkiBody.Type))
                throw new ArgumentException("content of PKIBody wrong type: " + pkiBody.Type);

            return new CertificateRepMessage(CertRepMessage.GetInstance(pkiBody.Content));
        }

        public static bool IsCertificateRepMessage(int bodyType)
        {
            switch (bodyType)
            {
            case PkiBody.TYPE_INIT_REP:
            case PkiBody.TYPE_CERT_REP:
            case PkiBody.TYPE_KEY_UPDATE_REP:
            case PkiBody.TYPE_CROSS_CERT_REP:
                return true;
            default:
                return false;
            }
        }

        private readonly CertResponse[] m_resps;
        private readonly CmpCertificate[] m_caCerts;

        public CertificateRepMessage(CertRepMessage repMessage)
        {
            m_resps = repMessage.GetResponse();
            m_caCerts = repMessage.GetCAPubs();
        }

        public virtual CertificateResponse[] GetResponses() => Array.ConvertAll(m_resps, resp => new CertificateResponse(resp));

        public virtual X509Certificate[] GetX509Certificates()
        {
            List<X509Certificate> certs = new List<X509Certificate>();

            foreach (var caCert in m_caCerts)
            {
                if (caCert.IsX509v3PKCert)
                {
                    certs.Add(new X509Certificate(caCert.X509v3PKCert));
                }
            }

            return certs.ToArray();
        }

        /**
         * Return true if the message only contains X.509 public key certificates.
         *
         * @return true if only X.509 PK, false otherwise.
         */
        public virtual bool IsOnlyX509PKCertificates()
        {
            bool isOnlyX509 = true;

            foreach (var caCert in m_caCerts)
            {
                isOnlyX509 &= caCert.IsX509v3PKCert;
            }

            return isOnlyX509;
        }

        /**
         * Return the actual CMP certificates - useful if the array also contains non-X509 PK certificates.
         *
         * @return CMPCertificate array
         */
        public virtual CmpCertificate[] GetCmpCertificates() => (CmpCertificate[])m_caCerts.Clone();

        public virtual CertRepMessage ToAsn1Structure() => new CertRepMessage(m_caCerts, m_resps);
    }
}