package jce;
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.BadPaddingException; import java.security.Key; import java.security.Security; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; public class DESCryptoTest { public static void main(String[] args) { //此为动态加载的办法; //静态加载方法为:编辑文件<java-home>\jre\lib\security\java.security //JDK1.4及以上版本已带JCE //Security.addProvider(new com.sun.crypto.provider.SunJCE()); try { //产生密钥(key)生成器生成密钥 KeyGenerator kg = KeyGenerator.getInstance("DES"); Key key = kg.generateKey(); //产生加密器(Cipher) Cipher cipher = Cipher.getInstance("DES");
byte[] data = "Hello World!".getBytes(); System.out.println("Original data : " + new String(data));
cipher.init(Cipher.ENCRYPT_MODE, key); byte[] result = cipher.doFinal(data); System.out.println("Encrypted data: " + new String(result));
cipher.init(Cipher.DECRYPT_MODE, key); byte[] original = cipher.doFinal(result); System.out.println("Decrypted data: " + new String(original)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } } }
|