/*
 * @(#)DHConnection.java
 *
 * Copyright (C) 2007 Infocity Inc. All Rights Reserved.
 */
package info.dragonlady.crypto;

import java.security.AlgorithmParameterGenerator;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.KeyAgreement;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;

/**
 * TODO クラス概要
 * 
 * @author Hiroshi.Ebata(INFOCITY)
 * @version $Revision: 1.0 $ $Date: 2007/04/04 19:46:48 $
 */
public class DHConnection {

	/**
	 * コンストラクタ。
	 */
	public DHConnection() {
		// TODO 自動生成されたコンストラクター・スタブ
	}

	public static final KeyPair generateKeyPair() throws NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException {
        AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
        paramGen.init(1024);
	    AlgorithmParameters params = paramGen.generateParameters();
	    DHParameterSpec dhParamSpec = (DHParameterSpec)params.getParameterSpec(DHParameterSpec.class);

	    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");
	    keyPairGen.initialize(dhParamSpec);
	    KeyPair keyPair = keyPairGen.generateKeyPair();
		return keyPair;
	}

	public byte[] createPublicKeyEncode(byte[] pubKeyEnc) throws Exception {
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKeyEnc);
		PublicKey publicKey = KeyFactory.getInstance("DH").generatePublic(x509KeySpec);

		DHParameterSpec dhParamSpec = ((DHPublicKey)publicKey).getParams();
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");
		keyPairGen.initialize(dhParamSpec);
		KeyPair keyPair = keyPairGen.generateKeyPair();

//		KeyAgreement keyAgree = KeyAgreement.getInstance("DH");
//		keyAgree.init(keyPair.getPrivate());

		return keyPair.getPublic().getEncoded();
	}

}
