package com.tu.Security;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import org.apache.commons.codec.binary.Base64;
/**
 * 对称加密算法-PBE
 * PBE(Password Based Encryption)基于口令加密
 * 
 * 算法                                                                     密钥长度        默认  工作模式       填充方式                   实现
 * PBEWithMD5AndDES                64       64   CBC      PKCS5Padding    BC
 * PBEWithMd5AndRC2                112      128            PKCS7Padding
 * PBEWithSHA1AndDES               6        64             ISO10126Padding
 * PBEWithSHAAndIDEA-CBC           128      128
 * PBEWithSHAAnd2-KeyTripleDES-CBC 128      128
 * PBEWithSHAAnd3-KeyTripleDES-CBC 192      192
 * 
 * @author comtu
 */
public class PBE {

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

	public static void jdkPBE(String src) {
		try {
			// 初始化盐
			SecureRandom random = new SecureRandom();
			byte[] salt = random.generateSeed(8);

			// 口令与密钥
			String password = "password_comtu";
			PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
			SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWITHMD5andDES");
			Key key = factory.generateSecret(pbeKeySpec);

			// 加密
			PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 100);
			Cipher cipher = Cipher.getInstance("PBEWITHMD5andDES");
			cipher.init(Cipher.ENCRYPT_MODE, key, pbeParameterSpec);
			byte[] result = cipher.doFinal(src.getBytes());
			System.out.println("jdk pbe encrypt : " + Base64.encodeBase64String(result));

			// 解密
			cipher.init(Cipher.DECRYPT_MODE, key, pbeParameterSpec);
			result = cipher.doFinal(result);
			System.out.println("jdk pbe decrypt : " + new String(result));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
