PBE对称加密的实现

public class PbeEncrypter {
    Cipher ecipher;
    Cipher dcipher;
    //盐
    byte[] salt = { (byte) 0x29, (byte) 0xCB, (byte) 0xD7, (byte) 0x28, (byte) 0x56, (byte) 0x3D,(byte) 0xEE, (byte) 0x05 };

    public PbeEncrypter(String parshkey) throws Exception {
        //迭代次数
        int iterationCount = 3;
        KeySpec keySpec = new PBEKeySpec(parshkey.toCharArray(), salt, iterationCount);
        SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        ecipher = Cipher.getInstance(key.getAlgorithm());
        dcipher = Cipher.getInstance(key.getAlgorithm());
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
        ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    }

    //加密方法
    public String encrypt(String str) throws Exception {
        str = new String(str.getBytes(), "UTF-8");
        return Base64.encodeBase64String(ecipher.doFinal(str.getBytes()));
    }

    //解密方法
    public String decrypt(String str) throws Exception {
        return new String(dcipher.doFinal(Base64.decodeBase64(str)),"UTF-8");
    }

    //调用方法
    public static void main(String[] args) throws Exception {
        //key : 36CE91A3CD88512E0A15033325D80859
        PbeEncrypter desEncrypter = new PbeEncrypter("98f3139d2e61042556d7e6d4a6818069de9f5b9a");
        //str为加密前的参数字符串

        String str = "12345678";
        System.out.println(desEncrypter.encrypt(str));
        System.out.println(desEncrypter.decrypt("0SVp7urHWduuyaPIneETrQ=="));
    }
}

 

转载于:https://my.oschina.net/iioschina/blog/737947

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值