DES加密和解密的方法



import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;


/**
* 使用DES加密和解密的方法
*/
public class CryptoTools {

private final byte[] DESkey = new byte[]{58, 21, 93, -100, 78, 4, -38, 32, 15, -89, 44, 90, 26, -6, -101, -112, 2, 94, 18, -52, 119, 35, -72, -69};// 设置密钥,略去
// private final byte[] DESIV = new byte[]{-121, 39, -10, -113, 36, 99, -89, 3, 42, 8, 62, 83, -72, 4, -47, 43, -111, 39, 112, 58, -83, 10, 41, -44};// 设置向量,略去
private final byte[] DESIV = new byte[]{58, 21, 93, 93, 93, 93, 93, 93};// 设置密钥,略去

private AlgorithmParameterSpec iv = null;// 加密算法的参数接口,IvParameterSpec是它的一个实现
private Key key = null;

public CryptoTools() throws Exception {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
// 设置密钥参数,得到密钥对象
key = keyFactory.generateSecret(new DESKeySpec(DESkey));// 得到密钥对象
iv = new IvParameterSpec(DESIV);// 设置向量
}

public String encode(String data) throws Exception {
Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式,给出密钥和向量
byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encode(pasByte);
}

public String decode(String data) throws Exception {
Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
deCipher.init(Cipher.DECRYPT_MODE, key, iv);
BASE64Decoder base64Decoder = new BASE64Decoder();

byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));

return new String(pasByte, "UTF-8");
}

public static void main(String[] args) {
try {
String test = "a1";
CryptoTools des = new CryptoTools();//自定义密钥
System.out.println("加密前的字符:" + test);
System.out.println("加密后的字符:" + des.encode(test));
System.out.println("解密后的字符:" + des.decode(des.encode(test)));
} catch (Exception e) {
e.printStackTrace();
}
}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值