package net.foreworld.util; 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; /** * * @author huangxin <3203317@qq.com> * */ public class PBECoder { public static final String ALGORITHM = "PBEWITHMD5andDES"; public static final int SALT_COUNT = 100; public static SecureRandom random; static { random = new SecureRandom(); } public static void main(String[] args) throws Exception { String message = "123456 hello 世界!"; PBEParameterSpec pbe = genPBEParameterSpec(genSalt("12345678")); String edata = encrypt("password", pbe, message); System.out.println("pbe encrypt: " + edata); String ddata = decrypt("password", pbe, edata); System.err.println("pbe decrypt: " + ddata); System.err.println("pbe compare: " + message.equals(ddata)); } /** * * @param pwd * @return * @throws Exception */ public static Key genKey(String pwd) throws Exception { PBEKeySpec pbeKeySpec = new PBEKeySpec(pwd.toCharArray()); SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM); return factory.generateSecret(pbeKeySpec); } /** * * @param need * @return */ public static byte[] genSalt(String need) { return need.getBytes(); } /** * * @return */ public static byte[] genSalt() { return random.generateSeed(8); } /** * * @param salt * @return */ public static PBEParameterSpec genPBEParameterSpec(byte[] salt) { return new PBEParameterSpec(salt, SALT_COUNT); } /** * 加密 * * @param pwd * @param pbe * @param data * @return * @throws Exception */ public static String encrypt(String pwd, PBEParameterSpec pbe, String data) throws Exception { Key key = genKey(pwd); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key, pbe); byte[] result = cipher.doFinal(data.getBytes()); return Base64.encodeBase64String(result); } /** * 解密 * * @param pwd * @param pbe * @param data * @return * @throws Exception */ public static String decrypt(String pwd, PBEParameterSpec pbe, String data) throws Exception { Key key = genKey(pwd); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key, pbe); byte[] result = cipher.doFinal(Base64.decodeBase64(data)); return new String(result); } }
pbe encrypt: LvKXdcVMaEsu1Hfr/0gii2xTZO5PLOvX pbe decrypt: 123456 hello 世界! pbe compare: true