前言
以下内容源自《【网络安全】》
仅供学习交流使用
推荐
无
实验 DES算法的实现
代码
package s1; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import java.security.SecureRandom; import java.util.Base64; public class DES { private static final String ALGORITHM = "DES"; private static final String TRANSFORMATION = "DES/ECB/PKCS5Padding"; public static void main(String[] args) throws Exception { String plainText = "Hello, world!"; // 要加密的明文 // 生成随机密钥 SecretKey secretKey = generateRandomKey(); // 加密明文 byte[] cipherText = encrypt(plainText.getBytes(), secretKey); // 将密文转换为 Base64 编码字符串 String encodedCipherText = Base64.getEncoder().encodeToString(cipherText); System.out.println("密文:" + encodedCipherText); // 解密密文 byte[] decryptedText = decrypt(Base64.getDecoder().decode(encodedCipherText), secretKey); System.out.println("解密后的明文:" + new String(decryptedText)); } /** * 生成随机密钥 */ public static SecretKey generateRandomKey() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM); SecureRandom secureRandom = new SecureRandom(); keyGenerator.init(secureRandom); return keyGenerator.generateKey(); } /** * 使用指定的密钥加密数据 */ public static byte[] encrypt(byte[] data, SecretKey key) throws Exception { Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(data); } /** * 使用指定的密钥解密数据 */ public static byte[] decrypt(byte[] data, SecretKey key) throws Exception { Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(data); } }
结果
密文:JKakqXhz5BZ7wktQm/xNLA== 解密后的明文:Hello, world!
最后
祝大家逢考必过
点赞收藏关注哦