/* WCEKeyStoreSpi.java -- 
   Copyright (C) 2009-2010 Mysaifu.com

This file is a part of Mysaifu JVM.

Mysaifu JVM is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.

Mysaifu JVM is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with Mysaifu JVM; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package com.mysaifu.jvm.java.security.provider;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.AccessController;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreSpi;
import java.security.KeyStoreException;
import java.security.UnrecoverableKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecurityPermission;
import java.security.UnrecoverableKeyException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateFactory;
import java.security.interfaces.RSAPrivateCrtKey;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Vector;

/**
 * KeyStoreSpi for Windows CE device.
 */
public abstract class WCEKeyStoreSpi
    extends KeyStoreSpi
{
  static
    {
      WCESecurity.loadLibraries();
    }

  /**
   * ネイティブポインタ
   */
  private int nativePointer;

  /**
   * この証明書ストアに含まれる全エイリアス
   */
  private Vector<String> aliases;

  /**
   * インスタンスを作成する
   */
  protected WCEKeyStoreSpi()
  {
  }

  /**
   * ネイティブポインタを返す
   */
  protected int getNativePointer()
  {
    return this.nativePointer;
  }

  /**
   * 指定されたInputStreamとパスワードを使って、証明書ストアをオープンする。
   * 
   * @param ins 入力データ。nullの場合もある。
   * @param password パスワード。nullの場合もある。
   * @return HCERTSTORE
   */
  protected abstract int openCertStore(InputStream ins, char[] password)
      throws IOException, NoSuchAlgorithmException, CertificateException;

  /**
   * 証明書ストアをクローズする
   */
  public final void close() throws CertificateException
  {
    if (this.nativePointer != 0)
      {
        closeCertStore(this.nativePointer);
        this.nativePointer = 0;
      }
  }

  /**
   * 証明書ストアをクローズする。
   * 
   * @throws KeyStoreException クローズに失敗した場合
   */
  protected abstract void closeCertStore(int nativePointer)
      throws CertificateException;

  /**
   * 指定されたエイリアスに対応するCERT_CONTEXT構造体のポインタを返す
   */
  protected int getCertContext(String name) throws CertificateException
  {
    return getNativeCertContext(nativePointer, name);
  }

  private native int getNativeCertContext(int nativePointer, String alias)
      throws CertificateException;

  /**
   * 指定された証明書に対応するCERT_CONTEXT構造体へのポインタを返す。
   */
  int getCertContextOf(WCECertificate cert) throws CertificateException
  {
    return getCertContext(cert.getAlias());
  }

  @Override
  public Key engineGetKey(String alias, char[] password)
      throws NoSuchAlgorithmException, UnrecoverableKeyException
  {
    throw new UnsupportedOperationException("Not implemented");
  }

  @Override
  public Certificate[] engineGetCertificateChain(String alias)
  {
    Certificate[] result = null;
    try
      {
        byte[][] chain = engineNativeGetCertificateChain(this.nativePointer,
                                                         alias);
        if (chain != null)
          {
            result = new Certificate[chain.length];
            for (int i = 0; i < chain.length; ++i)
              {
                byte[] encoded = chain[i];
                result[i] = new WCECertificate(this, alias, encoded, null);
              }
          }
      }
    catch (CertificateException ce)
      {
        ce.printStackTrace();
      }
    catch (IOException ioe)
      {
        ioe.printStackTrace();
      }
    return result;
  }

  /**
   * 指定されたエイリアスに対応する証明書チェーンを返す。
   */
  private native byte[][] engineNativeGetCertificateChain(int nativePointer,
                                                          String alias);

  @Override
  public Certificate engineGetCertificate(String alias)
  {
    Certificate[] chain = engineGetCertificateChain(alias);
    if (chain != null && chain.length > 0)
      {
        return chain[0];
      }
    return null;
  }

  @Override
  public Date engineGetCreationDate(String alias)
  {
    throw new UnsupportedOperationException("Not implemented");
  }

  @Override
  public void engineSetKeyEntry(String alias, Key key, char[] password,
                                Certificate[] chain) throws KeyStoreException
  {
    throw new UnsupportedOperationException("Not implemented");

  }

  @Override
  public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain)
      throws KeyStoreException
  {
    throw new UnsupportedOperationException("Not implemented");

  }

  @Override
  public void engineSetCertificateEntry(String alias, Certificate cert)
      throws KeyStoreException
  {
    throw new UnsupportedOperationException("Not implemented");

  }

  @Override
  public void engineDeleteEntry(String alias) throws KeyStoreException
  {
    throw new UnsupportedOperationException("Not implemented");

  }

  @Override
  public Enumeration<String> engineAliases()
  {
    return this.aliases.elements();
  }

  /**
   * 証明書ストアに格納されている証明書の、全エイリアスを返す。
   * 
   * @param nativePointer HCERTSTORE.
   * @return 全エイリアスが含まれる<code>Vector</code>.
   */
  private native Vector<String> getNativeAliases(int nativePointer);

  @Override
  public boolean engineContainsAlias(String alias)
  {
    return this.aliases.contains(alias);
  }

  @Override
  public int engineSize()
  {
    return this.aliases.size();
  }

  @Override
  public boolean engineIsKeyEntry(String alias)
  {
    throw new UnsupportedOperationException("Not implemented");
  }

  @Override
  public boolean engineIsCertificateEntry(String alias)
  {
    return this.aliases.contains(alias);
  }

  @Override
  public String engineGetCertificateAlias(Certificate cert)
  {
    if (cert instanceof WCECertificate)
      {
        WCECertificate wcert = (WCECertificate) cert;
        if (wcert.getKeyStoreSpi() == this)
          {
            return wcert.getAlias();
          }
      }
    return null;
  }

  @Override
  public void engineStore(OutputStream stream, char[] password)
      throws IOException, NoSuchAlgorithmException, CertificateException
  {
    throw new UnsupportedOperationException("Not implemented");
  }

  @Override
  public void engineLoad(InputStream stream, char[] password)
      throws IOException, NoSuchAlgorithmException, CertificateException
  {
    // 証明書ストアをオープンし、全エイリアスを取得する
    this.nativePointer = openCertStore(stream, password);
    this.aliases = getNativeAliases(this.nativePointer);
  }

  @Override
  protected void finalize() throws Throwable
  {
    // このストアをクローズする
    close();
  }
}
