1.用到的jar包:http://pan.baidu.com/s/1mgIbLvq提取码:ytj9
2.用法
3。代码实现:
package com.tan.sucurity; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; import org.apache.commons.codec.binary.Base64; import org.bouncycastle.asn1.pkcs.PBEParameter; /** * 功能:PEB算法 * @author TanZi * @time 2015年4月25日 上午10:05:40 */ public class MyPBE { public static void main(String[] args) { //初始化盐 SecureRandom random=new SecureRandom(); byte[] salt=random.generateSeed(8); MyPBE myPBE=new MyPBE(); byte[] result=myPBE.EncryptPBE("tanzi", "nihao",salt); System.out.println("加密:"+Base64.encodeBase64String(result)); result=myPBE.DecryptPBE("tanzi", result,salt); System.out.println("解密:"+new String(result)); } /** * 功能:获取一个Key * @param password * @return */ public Key toKey(String password){ Key key=null; try { PBEKeySpec pbeKeySpec=new PBEKeySpec(password.toCharArray()); SecretKeyFactory factory=SecretKeyFactory.getInstance("PBEWITHMD5andDES"); key=factory.generateSecret(pbeKeySpec); } catch (Exception e) { e.printStackTrace(); } return key; } /** * 功能:解密 * @param password 口令 * @param result 加密数据 * @param salt 盐 * @return */ public byte[] DecryptPBE(String password,byte[] result,byte[] salt){ try { Key key=toKey(password); PBEParameterSpec pbeParameterSpec=new PBEParameterSpec(salt, 100); Cipher cipher=Cipher.getInstance("PBEWITHMD5andDES"); cipher.init(Cipher.DECRYPT_MODE, key, pbeParameterSpec); result=cipher.doFinal(result); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /** * 功能:对数据的加密 * @param password 口令 * @param src 要加密的数据 * @param salt 盐 * @return */ public byte[] EncryptPBE(String password,String src,byte[] salt){ byte[] result=null; //口令与密钥 PBEKeySpec pbeKeySpec=new PBEKeySpec(password.toCharArray()); try { 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); result=cipher.doFinal(src.getBytes()); } catch (Exception e) { e.printStackTrace(); } return result; } }
时间: 2024-11-05 20:32:47