// 字符串進行 DES 加密和解密

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

?

public class DesedeStrDemo {???

??? static void getDecrypt() throws Exception {

?????? /****************** 加密 ******************/

?????? String APSecret = "dddddd" ; // 密鑰字符串

?????? String info = "iamzzb" ; // 加密字符串

??????

?????? byte [] key = new byte [24]; // 密鑰預存放字節數組

?????? byte [] APSecretB = APSecret.getBytes();

?????? int keylen = APSecretB. length ;

?????? if (keylen > 24)

?????????? keylen = 24;

?????? System.arraycopy(APSecretB, 0, key, 0, keylen);? // 密鑰格式化為字節數組 , 并復制到 key??

?????? SecretKey deskey = new SecretKeySpec(key, "DESede" ); // 生成秘密(對稱)密鑰

?????? Cipher c = Cipher.getInstance( "DESede/ECB/PKCS5Padding" ); // 提供了針對加密和解密的密碼 cipher 功能

?????? c.init(Cipher. ENCRYPT_MODE , deskey); // 用密鑰初始化此 cipher

?????? byte info_new[] = c.doFinal(info.getBytes()); // 結束多部分加密操作

??????

?????? /****************** 解密 ******************/ ???

?????? Cipher cc = Cipher.getInstance( "DESede/ECB/PKCS5Padding" ); // 提供了針對加密和解密的密碼 cipher 功能

?????? cc.init(Cipher. DECRYPT_MODE , deskey); // 用密鑰初始化此 cipher

?????? byte info_old[] = cc.doFinal(info_new); // 結束多部分解密操作

?????? String info_olds = new String(info_old);

?????? System. out .println(info_olds);?

??????

??? }??

??? public static void main(String[] args) throws Exception {

?????? getDecrypt();

??? }

}

?