des算法代码 java_java实现DES算法

本文介绍如何在Java中实现DES加密算法,包括加密和解密过程。使用了Cipher、DESKeySpec、SecretKeyFactory等类进行操作,并提供了完整的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

importjava.util.UUID;importjavax.crypto.Cipher;importjavax.crypto.SecretKey;importjavax.crypto.SecretKeyFactory;importjavax.crypto.spec.DESKeySpec;importjavax.crypto.spec.IvParameterSpec;

public classDESUtil {private static final String PASSWORD_CRYPT_KEY =UUID.randomUUID()

.toString().replace("-", "").toUpperCase().substring(0, 8);public static String decrypt(String message, String key) throwsException {byte[] bytesrc =convertHexString(message);

Cipher cipher= Cipher.getInstance("DES/CBC/PKCS5Padding");

DESKeySpec desKeySpec= new DESKeySpec(key.getBytes("UTF-8"));

SecretKeyFactory keyFactory= SecretKeyFactory.getInstance("DES");

SecretKey secretKey=keyFactory.generateSecret(desKeySpec);

IvParameterSpec iv= new IvParameterSpec(key.getBytes("UTF-8"));

cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);byte[] retByte =cipher.doFinal(bytesrc);return newString(retByte);

}public static byte[] encrypt(String message, String key) throwsException {

Cipher cipher= Cipher.getInstance("DES/CBC/PKCS5Padding");

DESKeySpec desKeySpec= new DESKeySpec(key.getBytes("UTF-8"));

SecretKeyFactory keyFactory= SecretKeyFactory.getInstance("DES");

SecretKey secretKey=keyFactory.generateSecret(desKeySpec);

IvParameterSpec iv= new IvParameterSpec(key.getBytes("UTF-8"));

cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);return cipher.doFinal(message.getBytes("UTF-8"));

}public staticString encrypt(String value) {

String result= "";try{

value= java.net.URLEncoder.encode(value, "utf-8");

result=toHexString(encrypt(value, PASSWORD_CRYPT_KEY))

.toUpperCase();

}catch(Exception ex) {

ex.printStackTrace();return "";

}returnresult;

}public static byte[] convertHexString(String ss) {byte digest[] = new byte[ss.length() / 2];for (int i = 0; i < digest.length; i++) {

String byteString= ss.substring(2 * i, 2 * i + 2);int byteValue = Integer.parseInt(byteString, 16);

digest[i]= (byte) byteValue;

}returndigest;

}public static String toHexString(byteb[]) {

StringBuffer hexString= newStringBuffer();for (int i = 0; i < b.length; i++) {

String plainText= Integer.toHexString(0xff &b[i]);if (plainText.length() < 2)

plainText= "0" +plainText;

hexString.append(plainText);

}returnhexString.toString();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值