package com.tu.Security;

import java.security.AlgorithmParameterGenerator;
import java.security.AlgorithmParameters;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.spec.DHParameterSpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * <PRE>
 *  非对称加密算法 - ElGamal
 *  公钥加密算法
 * 实现方:BC 密钥长度:160~16384(8的整数倍) , 默认:1024 工作模式:ECB,NONE
 * 填充方式:
 * NoPadding , PKCS1Padding
 * OAEPWITHMD5AndMGF1Pading
 * OAEPWITSHA1AndMGF1Pading
 * OAEPWITSHA224AndMGF1Pading
 * OAEPWITSHA256AndMGF1Pading
 * OAEPWITSHA384AndMGF1Pading
 * OAEPWITSHA512AndMGF1Pading
 * ISO9796-1Padding
 * </PRE>
 * 
 * @author comtu
 */
public class ElGamal {

	public static void main(String[] args) {
		bcElGamal("comtu");
	}

	public static void bcElGamal(String src) {
		try {
			// 公钥加密,私钥解密
			Security.addProvider(new BouncyCastleProvider());

			// 1.初始化密钥
			AlgorithmParameterGenerator algorithmParameterGenerator = AlgorithmParameterGenerator.getInstance("ElGamal");
			algorithmParameterGenerator.init(256);
			AlgorithmParameters algorithmParameters = algorithmParameterGenerator.generateParameters();

			DHParameterSpec dhParameterSpec =  (DHParameterSpec) algorithmParameters.getParameterSpec(DHParameterSpec.class);
			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ElGamal");
			keyPairGenerator.initialize(dhParameterSpec, new SecureRandom());
			KeyPair keyPair = keyPairGenerator.generateKeyPair();
			PublicKey elGamalPublicKey = keyPair.getPublic();
			PrivateKey elGamalPrivateKey = keyPair.getPrivate();

			System.out.println("Public Key:" + org.apache.commons.codec.binary.Base64.encodeBase64String(elGamalPublicKey.getEncoded()));
			System.out.println("Private Key:" + org.apache.commons.codec.binary.Base64.encodeBase64String(elGamalPrivateKey.getEncoded()));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
