/*
 *  Name:    $Id: X509CertificateBuilder.java,v 1.3 2010/01/27 16:01:10 t724w Exp $
 *
 *  Copyright 2009 Bundesamt für Informatik und Telekommunikation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ch.admin.bit.edec.dsig.builder;

import ch.admin.bit.edec.dsig.context.SystemContext;

import java.io.*;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

/**
 * This class creates X509 certificates from a specified content or path.
 *
 * @author t724w (mru)
 */
public class X509CertificateBuilder {

  private static final String HEADER = "-----BEGIN CERTIFICATE-----\n";
  private static final String FOOTER = "\n-----END CERTIFICATE-----";

  private final SystemContext context;

  /**
   * @param context
   */
  public X509CertificateBuilder(SystemContext context) {
    this.context = context;
  }

  /**
   * Create a certificate from a raw content
   *
   * @param content
   * @return
   * @throws CertificateException
   * @throws NoSuchProviderException
   */
  public X509Certificate createCertificate(String content) throws CertificateException, NoSuchProviderException {
    // X509 Token is encoded in base64

    // so we need a to add the certificate header and footer to the raw x509 data
    byte[] x509data = (HEADER + content + FOOTER).getBytes();
    ByteArrayInputStream bis = new ByteArrayInputStream(x509data);

    // create certificate
    CertificateFactory cf = context.getProviderSelector().getCertificateFactory();
    return (X509Certificate) cf.generateCertificate(bis);
  }

  /**
   * Create a certificate from a given file path
   *
   * @param path
   * @return
   * @throws CertificateException
   * @throws FileNotFoundException
   * @throws NoSuchProviderException
   */
  public X509Certificate createCertificateFromPath(String path)
      throws CertificateException, FileNotFoundException, NoSuchProviderException {
    File file = new File(path);

    // read in ca cert
    InputStream is = new FileInputStream(file);

    CertificateFactory cf = context.getProviderSelector().getCertificateFactory();
    X509Certificate cert = (X509Certificate) cf.generateCertificate(is);

    try {
      is.close();
    }
    catch (IOException e) {
      // do nothing
    }

    return cert;
  }

}
