3DES是继DESeasy被破解后的DES加密升级版。它属于对称加密。
可指定24位长度的密钥,在java API中也有事实上现。代码例如以下:
/** * 3DES 的Java SDK API 实现 * @author dxd * 201406917 */ public class DES3 { private static final String Algorithm = "DESede";// 定义 加密算法,可用 //keybyte为加密密钥,长度为24字节 //src为被加密的数据缓冲区(源) public static byte[] encryptMode(byte[] keybyte, byte[] src) { try { //生成密钥 SecretKey deskey = new SecretKeySpec(keybyte, Algorithm); //加密 Cipher c1 = Cipher.getInstance(Algorithm); c1.init(Cipher.ENCRYPT_MODE, deskey); return c1.doFinal(src); } catch (java.security.NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (javax.crypto.NoSuchPaddingException e2) { e2.printStackTrace(); } catch (java.lang.Exception e3) { e3.printStackTrace(); } return null; } //keybyte为加密密钥。长度为24字节 //src为加密后的缓冲区 public static byte[] decryptMode(byte[] keybyte, byte[] src) { try { //生成密钥 SecretKey deskey = new SecretKeySpec(keybyte, Algorithm); //解密 Cipher c1 = Cipher.getInstance(Algorithm); c1.init(Cipher.DECRYPT_MODE, deskey); return c1.doFinal(src); } catch (java.security.NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (javax.crypto.NoSuchPaddingException e2) { e2.printStackTrace(); } catch (java.lang.Exception e3) { e3.printStackTrace(); } return null; } //转换成十六进制字符串 public static String byte2hex(byte[] b) { String hs=""; String stmp=""; for (int n=0;n<b.length;n++) { stmp=(java.lang.Integer.toHexString(b[n] & 0XFF)); if (stmp.length()==1) hs=hs+"0"+stmp; else hs=hs+stmp; if (n<b.length-1) hs=hs+":"; } return hs.toUpperCase(); } }调用时能够:
byte[] keydata = { (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08, (byte) 0x09, (byte) 0x0a, (byte) 0x0b, (byte) 0x0c, (byte) 0x0d, (byte) 0x0e, (byte) 0x0f, (byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, }; String src = "3DES加密算法" ; byte[] encoded = DES3.encryptMode(keydata, src.getBytes()); System.out.println("DES3-->Encoded = " + new String(encoded));则能够计算出原文src加密后的密文。