import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Hex;
public class DESUtil {
/****
* 实例化密钥生成器
* @return
*/
public static byte[] initkey(){
KeyGenerator kg;
SecretKey secretkey=null;
try {
kg = KeyGenerator.getInstance("DES");
secretkey= kg.generateKey();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return secretkey.getEncoded();
}
/****
* 转化密钥
* @param key 二进制密钥
* @return 密钥
*/
public static Key tokey(byte[] key ){
SecretKey secretkey=null;
try {
DESKeySpec DESKeySpec=new DESKeySpec(key);
SecretKeyFactory keyfactory=SecretKeyFactory.getInstance("DES");
secretkey = keyfactory.generateSecret(DESKeySpec);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return secretkey;
}
/****
* 加密
* @param data 待加密数据
* @param key 密钥
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data,byte[] key) throws Exception{
Key k=tokey(key);
Cipher cipher=null;
//实例化
cipher=Cipher.getInstance("DES");
//初始化
cipher.init(Cipher.ENCRYPT_MODE, k);
return cipher.doFinal(data);
}
/****
* 解密
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] dencrypt(byte[] data,byte[] key) throws Exception{
Key k=tokey(key);
Cipher cipher=null;
//实例化
cipher=Cipher.getInstance("DES");
//初始化
cipher.init(Cipher.DECRYPT_MODE, k);
return cipher.doFinal(data);
}
public static void main(String[] args) {
String key = "this is a 24 byte key !!";
String message = "This is a test message";
try {
byte[] encrydata= DESUtil.encrypt(message.getBytes(), key.getBytes());
byte[] dencrydata =DESUtil.dencrypt(encrydata, key.getBytes());
Hex.encodeHexString(encrydata);
System.out.println("原文:"+message);
System.out.println("密文:"+Hex.encodeHexString(encrydata));
System.out.println("明文:"+new String(dencrydata));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
java加密解密技术--DES算法
最新推荐文章于 2020-12-03 15:55:52 发布
本文提供了一个 Java 中使用 DES 对数据进行加密和解密的完整示例。通过 KeyGenerator 和 SecretKeyFactory 实现了 DES 密钥的生成,并使用 Cipher 类完成了数据的加密与解密过程。
摘要由CSDN通过智能技术生成