用java完成DES算法的实现
时间: 2024-03-12 08:46:20 浏览: 12
好的,以下是使用Java实现DES算法的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
public class DESUtil {
/**
* 生成DES密钥
*
* @return 密钥
* @throws Exception
*/
public static byte[] generateKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init(56);
SecretKey secretKey = keyGenerator.generateKey();
return secretKey.getEncoded();
}
/**
* DES加密
*
* @param data 待加密的数据
* @param key 密钥
* @return 加密后的数据
* @throws Exception
*/
public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
Key k = new SecretKeySpec(key, "DES");
cipher.init(Cipher.ENCRYPT_MODE, k);
return cipher.doFinal(data);
}
/**
* DES解密
*
* @param data 待解密的数据
* @param key 密钥
* @return 解密后的数据
* @throws Exception
*/
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
Key k = new SecretKeySpec(key, "DES");
cipher.init(Cipher.DECRYPT_MODE, k);
return cipher.doFinal(data);
}
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!"; // 待加密的数据
byte[] key = generateKey(); // 生成密钥
byte[] cipherText = encrypt(plainText.getBytes(StandardCharsets.UTF_8), key); // 加密
byte[] decryptedText = decrypt(cipherText, key); // 解密
System.out.println(new String(decryptedText, StandardCharsets.UTF_8)); // 输出解密后的数据
}
}
```
以上代码使用了Java标准库提供的`Cipher`类来进行加解密操作,其中`KeyGenerator`用于生成密钥,`SecretKeySpec`用于包装密钥,`Cipher`用于加解密操作。在使用时需要指定加密算法、工作模式和填充方式,例如示例代码中的`DES/ECB/PKCS5Padding`表示使用DES算法、ECB工作模式和PKCS5Padding填充方式。