例程下载:
https://files.cnblogs.com/files/heyang78/ufo_base64_des_211003am.rar
需要导入的依赖:
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.15</version> </dependency>
程序:
package ufo; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; public class DES_Test { public static void main(String... args) { String original="Let’s Build a Giant Airship 青海长云暗雪山"; System.out.println("原文= "+original); try { // 生产密钥 KeyGenerator kgen = KeyGenerator.getInstance("DES"); kgen.init(56); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "DES");// 密钥,下面加密解密都要用到 System.out.println("密钥= "+Base64.encodeBase64String(key.getEncoded())); // 加密 Cipher cipherEncode = Cipher.getInstance("DES"); byte[] byteContent = original.getBytes(); cipherEncode.init(Cipher.ENCRYPT_MODE, key); byte[] EncodeResults = cipherEncode.doFinal(byteContent); System.out.println("密文= "+Base64.encodeBase64String(EncodeResults)); // 解密 Cipher cipherDecode = Cipher.getInstance("DES");// 创建密码器 cipherDecode.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器 byte[] DecodeResults = cipherDecode.doFinal(EncodeResults); System.out.println("解密后= "+new String(DecodeResults)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
输出:
原文= Let’s Build a Giant Airship 青海长云暗雪山 密钥= 2nAyzeNe6UA= 密文= 8OQw+fvxDTtlzLabEbfiJPgvJaPLTtDdWd0ALr1CDGetMpvTgEE+K2smBrhVfGBm 解密后= Let’s Build a Giant Airship 青海长云暗雪山