程序:
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 DESede_Test { public static void main(String... args) { String original="Let’s Build a Giant Airship 青海长云暗雪山"; System.out.println("原文= "+original); try { // 生产密钥 KeyGenerator kgen = KeyGenerator.getInstance("DESede"); kgen.init(168); //112 或168 SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "DESede");// 密钥,下面加密解密都要用到 System.out.println("密钥= "+Base64.encodeBase64String(key.getEncoded())); // 加密 Cipher cipherEncode = Cipher.getInstance("DESede"); 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("DESede");// 创建密码器 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 青海长云暗雪山 密钥= JvETf/fvSj34Q6QCvPTgq9mnGci17Aur 密文= 7AnmFkcOIZrGj0uedu1j+J2ElY0J52JWL93EuNYfx8QFR2xLfAv6QXewazk8wG5G 解密后= Let’s Build a Giant Airship 青海长云暗雪山
END