- 1
新建一個java項目,項目標名稱為javades。
 
  - 2
打開這個javades文件,在此中界說一個靜態方式getkey,把des算法的key的8的字節生當作。
 private static SecretKey getkey(byte[] key){
        try {
            DESKeySpec ks=new DESKeySpec(key);
            SecretKeyFactory  kf=SecretKeyFactory.getInstance("des");
            SecretKey sk=kf.generateSecret(ks);
            return sk;
        } catch (InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException ex) {
            Logger.getLogger(Javades.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }
 
  - 3
界說一個解密方式:
 private static byte[] decrypt(byte[]data,String key){
        
        try {
            SecretKey sk=getkey(key.getBytes());
            Cipher ch=Cipher.getInstance("des");
            ch.init(Cipher.DECRYPT_MODE, sk);
            return ch.doFinal(data);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
            Logger.getLogger(Javades.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }
 
  - 4
界說加密方式:
    try {
            SecretKey sk=getkey(key.getBytes());
            Cipher ch = Cipher.getInstance("des");
            ch.init(Cipher.ENCRYPT_MODE, sk);
            return ch.doFinal(data);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
            Logger.getLogger(Javades.class.getName()).log(Level.SEVERE, null, ex);
        }
           
        return null;
    }
 
  - 5
在main方式中加密一個字符串息爭密一個字符串:
 String key="12345678";
       String data="abc123456890";
       System.err.println("data:"+data);
       byte[] jmdata=Javades.encrypt(data.getBytes(), key);
       System.err.println(Arrays.toString(jmdata));
       jm=Javades.decrypt(jm, pw);
       System.err.println(new String(jm));
 
  - 6
運行項目,成果把字符串des加密,還原字符串當作功。
 
  - 7
這個在對文件加密:
String key="12345678";
        try {
             File fi=new File("c:/data.txt");
            InputStream input = new FileInputStream(fi);
   
            byte[] data = new byte[input.available()];
            input.read(data);
            System.err.println("data:"+data);
             byte[] jmdata=Javades.encrypt(data, key);
            System.err.println("加密數據:"+Arrays.toString(jmdata));
            byte[] jmjm=Javades.decrypt(jmdata, key);
            System.err.println("解密數據:"+new String(jmjm,"UTF-8"));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Javades.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Javades.class.getName()).log(Level.SEVERE, null, ex);
        }
 
  - 8
運行項目,對文件byte[]的數據加密息爭密當作功。