下面是使用jdk提供的加密类库进行DES加密样例
1 public class TestDES { 2 3 //SecretKey 负责保存对称密钥 4 private SecretKey deskey; 5 //Cipher负责完成加密或解密工作 6 private Cipher c; 7 8 public TestDES() throws NoSuchAlgorithmException, NoSuchPaddingException { 9 Security.addProvider(new com.sun.crypto.provider.SunJCE()); 10 //实例化支持DES算法的密钥生成器(算法名称命名需按规定,否则抛出异常) 11 KeyGenerator keygen = KeyGenerator.getInstance("DES"); 12 //生成密钥 13 deskey = keygen.generateKey(); 14 //生成Cipher对象,指定其支持的DES算法 15 c = Cipher.getInstance("DES"); 16 } 17 18 19 public byte[] encrypt(String str) throws InvalidKeyException, 20 IllegalBlockSizeException, BadPaddingException { 21 // 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式 22 c.init(Cipher.ENCRYPT_MODE, deskey); 23 byte[] src = str.getBytes(); 24 // 加密,结果保存进cipherByte 25 byte[] cipherByte = c.doFinal(src); 26 return cipherByte; 27 } 28 public byte[] encrypt(byte[] src) throws InvalidKeyException, 29 IllegalBlockSizeException, BadPaddingException { 30 // 根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式 31 c.init(Cipher.ENCRYPT_MODE, deskey); 32 // 加密,结果保存进cipherByte 33 byte[] cipherByte = c.doFinal(src); 34 return cipherByte; 35 } 36 public byte[] decrypt(byte[] buff) throws InvalidKeyException, 37 IllegalBlockSizeException, BadPaddingException { 38 // 根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示加密模式 39 c.init(Cipher.DECRYPT_MODE, deskey); 40 byte[] cipherByte = c.doFinal(buff); 41 return cipherByte; 42 } 43 44 public static void main(String[] args) throws Exception { 45 TestDES de1 = new TestDES(); 46 byte[] bytes = new byte[]{'z', 'h', 'a', 'n', 'g', '\2', '\2', '\3'}; 47 byte[] encontent = de1.encrypt(bytes); 48 byte[] decontent = de1.decrypt(encontent); 49 System.out.println("明文是:" + new String(decontent)); 50 } 51 }