package des; import javax.crypto.*; import javax.crypto.spec.*; import org.apache.commons.codec.binary.*; public class DesTest { private static final String key = "ae3712e83f0831ee8277f795bfed995e"; private static final String iv = "1234567812345678"; private static byte[] build3DesKey(String keyStr) throws Exception { byte[] key = new byte[24]; byte[] keyBytes = Hex.decodeHex(keyStr.toCharArray()); if(keyBytes.length < key.length) { System.arraycopy(keyBytes, 0, key, 0, keyBytes.length); System.arraycopy(keyBytes, 0, key, 16, 8); } else System.arraycopy(keyBytes, 0, key, 0, key.length); return key; } private static Cipher getCipher(int mode) throws Exception { SecretKey deskey = new SecretKeySpec(build3DesKey(key), "DESede"); IvParameterSpec ivObj = new IvParameterSpec(Hex.decodeHex(iv.toCharArray())); Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(mode, deskey, ivObj); return cipher; } public static void main(String[] args) throws Exception { Cipher encrypt = getCipher(Cipher.ENCRYPT_MODE); Cipher decrypt = getCipher(Cipher.DECRYPT_MODE); String content = "secret"; String ciphertext = String.valueOf(Hex.encodeHex(encrypt.doFinal(content.getBytes()))); System.out.println(ciphertext); String plaintext = new String(decrypt.doFinal(Hex.decodeHex(ciphertext.toCharArray()))); System.out.println(plaintext); } }