DES

package com.security.test;


import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;


import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;


import com.sun.crypto.provider.SunJCE;


/**
 * @author 佚名
 * @info des生成56为秘钥+8为奇偶校验位 共64位
 *       DES算法把64位的明文输入块变为64位的密文输出块,它所使用的密钥也是64位,其算法主要分为两步: 1)初始置换
 *       其功能是把输入的64位数据块按位重新组合,并把输出分为L0、R0两部分,每部分各长3
 *       2位,其置换规则为将输入的第58位换到第一位,第50位换到第2位
 *       ……依此类推,最后一位是原来的第7位。L0、R0则是换位输出后的两部分,L0是输出的左32位
 *       ,R0是右32位,例:设置换前的输入值为D1D2D3
 *       ……D64,则经过初始置换后的结果为:L0=D58D50……D8;R0=D57D49……D7。 2)逆置换
 *       经过16次迭代运算后,得到L16、R16,将此作为输入,进行逆置换,逆置换正好是初始置换的逆运算,由此即得到密文输出。
 */
public class DES {


// KeyGenerator 提供对称密钥生成器的功能,支持各种算法
private KeyGenerator keygen;
// SecretKey 负责保存对称密钥
private SecretKey deskey;
// Cipher负责完成加密或解密工作
private Cipher c;
// 该字节数组负责保存加密的结果
private byte[] cipherByte;


public DES() throws NoSuchAlgorithmException, NoSuchPaddingException {
Security.addProvider(new SunJCE());
// 实例化支持DES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
keygen = KeyGenerator.getInstance("DES");
// 生成密钥
deskey = keygen.generateKey();
// 生成Cipher对象,指定其支持的DES算法
c = Cipher.getInstance("DES");
}


/**
* 对字符串加密
*/
public byte[] jiami(String str) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
// 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
c.init(Cipher.ENCRYPT_MODE, deskey);
byte[] src = str.getBytes();
// 加密,结果保存进cipherByte
cipherByte = c.doFinal(src);
return cipherByte;
}


/**
* 对字符串解密
*/
public byte[] jiemi(byte[] buff) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
// 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示加密模式
c.init(Cipher.DECRYPT_MODE, deskey);
cipherByte = c.doFinal(buff);
return cipherByte;
}


/**
* test
*/
public static void main(String[] args) throws Exception {
DES des = new DES();
String msg = "张三是好人";
System.out.println("明文是:" + msg);
byte[] encontent = des.jiami(msg);
byte[] decontent = des.jiemi(encontent);
System.out.println("加密后:" + new String(encontent));
System.out.println("解密后:" + new String(decontent));
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值