summaryrefslogtreecommitdiff
path: root/bcpkix/src/main/java/org/bouncycastle/pkix/jcajce/JcaPKIXIdentity.java
blob: 4872c1b12c3c2fdbfe1166e67276e6a3defb9f64 (plain)
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
package org.bouncycastle.pkix.jcajce;

import java.security.PrivateKey;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;

import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
import org.bouncycastle.pkix.PKIXIdentity;

/**
 * Holder class for public/private key based identity information.
 */
public class JcaPKIXIdentity
    extends PKIXIdentity
{
    private final PrivateKey privKey;
    private final X509Certificate[] certs;

    private static PrivateKeyInfo getPrivateKeyInfo(PrivateKey privateKey)
    {
         try
         {
             return PrivateKeyInfo.getInstance(privateKey.getEncoded());
         }
         catch (Exception e)             // for a HSM getEncoded() may do anything...
         {
             return null;
         }
    }

    private static X509CertificateHolder[] getCertificates(X509Certificate[] certs)
    {
        X509CertificateHolder[] certHldrs = new X509CertificateHolder[certs.length];

        try
        {
            for (int i = 0; i != certHldrs.length; i++)
            {
                certHldrs[i] = new JcaX509CertificateHolder(certs[i]);
            }

            return certHldrs;
        }
        catch (CertificateEncodingException e)
        {
            throw new IllegalArgumentException("Unable to process certificates: " + e.getMessage());
        }
    }

    public JcaPKIXIdentity(PrivateKey privKey, X509Certificate[] certs)
    {
        super(getPrivateKeyInfo(privKey), getCertificates(certs));

        this.privKey = privKey;
        this.certs = new X509Certificate[certs.length];

        System.arraycopy(certs, 0, this.certs, 0, certs.length);
    }

    /**
     * Return the private key for this identity.
     *
     * @return the identity's private key.
     */
    public PrivateKey getPrivateKey()
    {
        return privKey;
    }

    /**
     * Return the certificate associated with the private key.
     *
     * @return the primary certificate.
     */
    public X509Certificate getX509Certificate()
    {
        return certs[0];
    }
}