package org.bouncycastle.x509.extension;

import java.io.IOException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;

import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.jce.PrincipalUtil;

/**
 * A high level authority key identifier.
 */
public class AuthorityKeyIdentifierExtension
    extends AuthorityKeyIdentifier
{
    private AuthorityKeyIdentifier authKeyID;
    
    public AuthorityKeyIdentifierExtension(
        byte[]  encodedValue)
        throws IOException
    {
        super((ASN1Sequence)X509ExtensionUtil.fromExtensionValue(encodedValue));
    }
    
    private static ASN1Sequence fromCertificate(
        X509Certificate certificate)
        throws CertificateParsingException
    {
        try
        {
            SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                                            (ASN1Sequence)new ASN1InputStream(certificate.getPublicKey().getEncoded()).readObject());
            
            GeneralName             genName = new GeneralName(PrincipalUtil.getSubjectX509Principal(certificate));
            ASN1EncodableVector     v = new ASN1EncodableVector();
            
            v.add(genName);
            
            return (ASN1Sequence)new AuthorityKeyIdentifier(
                                info, new GeneralNames(new DERSequence(v)), certificate.getSerialNumber()).toASN1Object();
        }
        catch (Exception e)
        {
            throw new CertificateParsingException("Exception extracting certificate details: " + e.toString());
        }
    }
    
    public AuthorityKeyIdentifierExtension(
        X509Certificate certificate)
        throws CertificateParsingException
    {
        super(fromCertificate(certificate));
    }
}
