<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    隨筆-86  評論-33  文章-0  trackbacks-0
    資源讀取類
    package com.crypto.encrypt;

    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.BufferedOutputStream;
    import java.io.IOException;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.ResourceBundle;
    import java.util.Locale;

      
    /**
       * 資源讀取類
       
    */
    public class Util {

      
    private static ResourceBundle resources=null;
      
    /**
       * 初始化資源
       
    */
      
    static {
            
    new Util();
        }


      
    public Util() {
        resources 
    = ResourceBundle.getBundle(
              
    "resource.algorithm",
              Locale.getDefault());
      }
      
    /**
       * 讀取源文件內(nèi)容
       * 
    @param filename String 文件路徑
       * 
    @throws IOException
       * 
    @return byte[] 文件內(nèi)容
       
    */
      
    public static byte[] readFile(String filename) throws IOException {

        File file 
    =new File(filename);
        
    if(filename==null || filename.equals(""))
        {
          
    throw new NullPointerException("無效的文件路徑");
        }
        
    long len = file.length();
        
    byte[] bytes = new byte[(int)len];

        BufferedInputStream bufferedInputStream
    =new BufferedInputStream(new FileInputStream(file));
        
    int r = bufferedInputStream.read( bytes );
        
    if (r != len)
          
    throw new IOException("讀取文件不正確");
        bufferedInputStream.close();

        
    return bytes;

      }

      
    /**
       * 將加密的數(shù)據(jù)寫入文件
       * 
    @param data byte[]
       * 
    @throws IOException
       
    */
      
    public static void writeFile(byte[] data,String filename) throws IOException {
        File file 
    =new File(filename);
        file.getParentFile().mkdirs();
        BufferedOutputStream bufferedOutputStream
    =new BufferedOutputStream(new FileOutputStream(file));
        bufferedOutputStream.write(data);
        bufferedOutputStream.close();

      }

      
    /**
       * 從jar文件里讀取class
       * 
    @param filename String
       * 
    @throws IOException
       * 
    @return byte[]
       
    */
      
    public byte[] readFileJar(String filename) throws IOException {
        BufferedInputStream bufferedInputStream
    =new BufferedInputStream(getClass().getResource(filename).openStream());
        
    int len=bufferedInputStream.available();
        
    byte[] bytes=new byte[len];
        
    int r=bufferedInputStream.read(bytes);
        
    if(len!=r)
        {
          bytes
    =null;
          
    throw new IOException("讀取文件不正確");
        }
        bufferedInputStream.close();
        
    return bytes;
      }

      
    /**
       * 獲得密碼生成法則
       * 
    @return String
       
    */
      
    public static String getAlgorithm()
      {
          
    return resources.getString("algorithm");
      }
      
    /**
       * 獲得值
       * 
    @param skey String
       * 
    @return String
       
    */
      
    public static String getValue(String skey)
      {
        
    return resources.getString(skey);
      }
    }

    生成密鑰
    package com.crypto.encrypt;

    import java.security.SecureRandom;
    import javax.crypto.KeyGenerator;
    import java.security.NoSuchAlgorithmException;
    import javax.crypto.SecretKey;
    import java.io.*;

    public class CreateKey {
      String filename
    ="";
      
    public CreateKey() {

      }

      
    /**
       * 獲得密匙字節(jié)內(nèi)容
       * 
    @throws IOException
       * 
    @return byte[]
       
    */
      
    public byte[] getKeyByte() throws IOException {
        
    byte[] bytes=Util.readFile(filename);
        
    return bytes;
      }

      
    public void CreateKeyFile(String filename) throws IOException,
          NoSuchAlgorithmException {
        
    this.filename=filename;
        
    if(filename==null || filename.equals(""))
        {
          
    throw new NullPointerException("無效的文件路徑");
        }
        createKey();
      }

      
    /**
       * 生成密匙
       * 
    @throws NoSuchAlgorithmException
       * 
    @throws IOException
       
    */
      
    private void createKey() throws NoSuchAlgorithmException, IOException {
        SecureRandom secureRandom 
    = new SecureRandom();
        
    // 為我們選擇的DES算法生成一個KeyGenerator對象
        KeyGenerator kg = KeyGenerator.getInstance(Util.getValue("algorithm"));
        kg.init(secureRandom);
        
    // 生成密鑰
        SecretKey key = kg.generateKey();
        
    // 將密鑰數(shù)據(jù)保存為文件供以后使用
        Util.writeFile(key.getEncoded(),filename);
      }

      
    /**
       * 獲得密匙文件路徑
       * 
    @return String
       
    */
      
    public String getKeyFilePath()
      {
        
    return filename;
      }
    }

    加密
    package com.crypto.encrypt;

    import java.security.SecureRandom;
    import java.io.*;
    import javax.crypto.spec.DESKeySpec;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.Cipher;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.spec.InvalidKeySpecException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import java.lang.reflect.Constructor;
    import java.security.spec.KeySpec;
    import java.lang.reflect.InvocationTargetException;

    public class EncryptData {

      
    private String keyfile=null;

      
    public EncryptData() {
      }

      
    public EncryptData(String keyfile) {
        
    this.keyfile=keyfile;
      }

      
    /**
       * 加密文件
       * 
    @param filename String 源路徑
       * 
    @param filenamekey String 加密后的路徑
       
    */
      
    public void createEncryptData(String filename,String filenamekey) throws
          IllegalStateException, IllegalBlockSizeException, BadPaddingException,
          NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException,
          InvalidKeyException, IOException, InstantiationException,
          IllegalAccessException, IllegalArgumentException,
          InvocationTargetException, NoSuchMethodException, SecurityException,
          ClassNotFoundException, IllegalStateException, IllegalBlockSizeException,
          BadPaddingException, NoSuchPaddingException, InvalidKeySpecException,
          NoSuchAlgorithmException, InvalidKeyException, IOException {
        
    //驗證keyfile
        if(keyfile==null || keyfile.equals(""))
        {
          
    throw new NullPointerException("無效的key文件路徑");
        }

        encryptData(filename,filenamekey);
      }

      
    /**
       * 加密類文件
       * 
    @param filename String 原始的類文件
       * 
    @param encryptfile String 加密后的類文件
       
    */
      
    private void encryptData(String filename,String encryptfile) throws IOException, InvalidKeyException,
          NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
          NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException,
          IllegalStateException, ClassNotFoundException, SecurityException,
          NoSuchMethodException, InvocationTargetException,
          IllegalArgumentException, IllegalAccessException, InstantiationException {

        
    //載入待加密的文件
        byte data[]=Util.readFile(filename);
        
    // 執(zhí)行加密操作
        byte encryptedClassData[] = getencryptData(data);
        
    // 保存加密后的文件,覆蓋原有的類文件。
        Util.writeFile(encryptedClassData,encryptfile);
      }
      
    /**
       * 直接獲得加密數(shù)據(jù)
       * 
    @param bytes byte[]
       * 
    @return byte[]
       
    */
      
    public byte[] createEncryptData(byte[] bytes) throws IllegalStateException,
          IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
          NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException,
          InstantiationException, IllegalAccessException, IllegalArgumentException,
          InvocationTargetException, NoSuchMethodException, SecurityException,
          ClassNotFoundException, IOException {
        bytes
    =getencryptData(bytes);
        
    return bytes;
      }

              
    /**
               * 加密業(yè)務(wù)方法
               * 
    @param bytes byte[] 待加密數(shù)據(jù)
               * 
    @return byte[] 加密后數(shù)據(jù)
               
    */
          
    private byte[] getencryptData(byte[] bytes) throws IOException,
          ClassNotFoundException, SecurityException, NoSuchMethodException,
          InvocationTargetException, IllegalArgumentException,
          IllegalAccessException, InstantiationException, NoSuchAlgorithmException,
          InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException,
          InvalidKeyException, BadPaddingException, IllegalBlockSizeException,
          IllegalStateException {
        
    // 產(chǎn)生一個可信任的隨機數(shù)源
        SecureRandom sr = new SecureRandom();
        
    //從密鑰文件key Filename中得到密鑰數(shù)據(jù)
        byte[] rawKeyData = Util.readFile(keyfile);
        
    // 從原始密鑰數(shù)據(jù)創(chuàng)建DESKeySpec對象
        Class classkeyspec=Class.forName(Util.getValue("keyspec"));
        Constructor constructor 
    = classkeyspec.getConstructor(new Class[]{byte[].class});
        KeySpec dks 
    = (KeySpec)constructor.newInstance(new Object[]{rawKeyData});
        
    // 創(chuàng)建一個密鑰工廠,然后用它把DESKeySpec轉(zhuǎn)換成SecretKey對象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Util.getAlgorithm());
        SecretKey key 
    = keyFactory.generateSecret(dks);
        
    // Cipher對象實際完成加密操作
        Cipher cipher = Cipher.getInstance(Util.getAlgorithm());
        
    // 用密鑰初始化Cipher對象
        cipher.init(Cipher.ENCRYPT_MODE, key, sr);
        
    // 執(zhí)行加密操作
        bytes = cipher.doFinal(bytes);
        
    // 返回字節(jié)數(shù)組
        return bytes;
      }
      
    /**
       * 設(shè)置key文件路徑
       * 
    @param keyfile String
       
    */
      
    public void setKeyFile(String keyfile)
      {
        
    this.keyfile=keyfile;
      }
    }

    解密
    package com.crypto.encrypt;

    import java.security.SecureRandom;
    import javax.crypto.spec.DESKeySpec;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.SecretKey;
    import javax.crypto.Cipher;
    import java.io.IOException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.spec.InvalidKeySpecException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import java.security.spec.KeySpec;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.io.ByteArrayInputStream;

    public class UnEncryptData {

      
    private String keyfile="";

      
    public UnEncryptData() {}

      
    public UnEncryptData(String keyfile) {this.keyfile=keyfile;}

      
    public void createUnEncryptData(String encryptfile,String filename) throws
          IllegalStateException, IllegalBlockSizeException, BadPaddingException,
          NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException,
          InvalidKeyException, IOException, NoSuchMethodException,
          SecurityException, InstantiationException, IllegalAccessException,
          IllegalArgumentException, InvocationTargetException,
          ClassNotFoundException, IllegalStateException, IllegalBlockSizeException,
          BadPaddingException, NoSuchPaddingException, InvalidKeySpecException,
          NoSuchAlgorithmException, InvalidKeyException, IOException {
        
    //驗證keyfile
        if(keyfile==null || keyfile.equals("")){
          
    throw new NullPointerException("無效的key文件路徑");
        }
        unEncryptData(encryptfile,filename);
      }
      
    /**
       * 解密類文件
       * 
    @param encryptfile String 經(jīng)過加密的文件
       * 
    @param filename String 解密后的文件
       
    */
      
    private void unEncryptData(String encryptfile,String filename) throws
          IOException, IllegalStateException, IllegalBlockSizeException,
          BadPaddingException, InvalidKeyException, NoSuchPaddingException,
          InvalidKeySpecException, NoSuchAlgorithmException, InstantiationException,
          IllegalAccessException, IllegalArgumentException,
          InvocationTargetException, NoSuchMethodException, SecurityException,
          ClassNotFoundException, IOException {
        
    // 獲得經(jīng)過加密的數(shù)據(jù)
        byte[] data = Util.readFile(encryptfile);
        
    //執(zhí)行解密操作
        byte decryptedData[] = getunEncryptData(data);
        
    // 然后將解密后的數(shù)據(jù)轉(zhuǎn)化成原來的類文件。
        Util.writeFile(decryptedData,filename);
      }
      
    /**
       * 解密字節(jié)數(shù)組
       * 
    @param bytes byte[]
       * 
    @return byte[]
       
    */
      
    public byte[] createUnEncryptData(byte[] bytes) throws IllegalStateException,
          IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
          NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException,
          InstantiationException, IllegalAccessException, IllegalArgumentException,
          InvocationTargetException, NoSuchMethodException, SecurityException,
          ClassNotFoundException, IOException {
        bytes 
    = getunEncryptData(bytes);
        
    return bytes;
      }
      
    /**
       *
       * 
    @param bytes byte[]
       * 
    @return byte[]
       
    */
      
    private byte[] getunEncryptData(byte[] bytes) throws IOException,
          ClassNotFoundException, SecurityException, NoSuchMethodException,
          InvocationTargetException, IllegalArgumentException,
          IllegalAccessException, InstantiationException, NoSuchAlgorithmException,
          InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException,
          InvalidKeyException, BadPaddingException, IllegalBlockSizeException,
          IllegalStateException {
        
    // 生成一個可信任的隨機數(shù)源
        SecureRandom sr = new SecureRandom();
        
    // 從密鑰文件中獲取原始密鑰數(shù)據(jù)
        byte[] rawKeyData = Util.readFile(keyfile);
        
    // 創(chuàng)建一個DESKeySpec對象
        Class classkeyspec=Class.forName(Util.getValue("keyspec"));
        Constructor constructor 
    = classkeyspec.getConstructor(new Class[]{byte[].class});
        KeySpec dks 
    = (KeySpec) constructor.newInstance(new Object[]{rawKeyData}); //new DESKeySpec(rawKeyData);
        
    // 創(chuàng)建一個密鑰工廠,然后用它把DESKeySpec對象轉(zhuǎn)換成Secret Key對象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Util.getAlgorithm());
        SecretKey key 
    = keyFactory.generateSecret(dks);
        
    // Cipher對象實際完成解密操作
        Cipher cipher = Cipher.getInstance(Util.getAlgorithm());
        
    // 用密鑰初始化Cipher對象
        cipher.init(Cipher.DECRYPT_MODE, key, sr);
        
    // 獲得經(jīng)過加密的數(shù)據(jù)
        
    //執(zhí)行解密操作
        bytes = cipher.doFinal(bytes);
        
    // 然后將解密后的數(shù)據(jù)轉(zhuǎn)化成原來的類文件。
        return bytes;
      }
      
    public void setKeyFile(String keyfile){this.keyfile=keyfile;}
    }

    algorithm.properties資源文件
    algorithm=DES
    keyspec
    =javax.crypto.spec.DESKeySpec
    keypath
    =src/resource/key


    測試類

    package com.crypto.encrypt;

    import java.security.*;

    import java.io.*;
    import java.lang.reflect.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.*;
    import javax.crypto.*;
    import sun.security.provider.MD5;

    public class TestEncrypt {
        
    public TestEncrypt() {
        }

        
    /**
         * 創(chuàng)建KEY
         * 
    @param keyPath String 生成密鑰路徑
         
    */
        
    public void createKey(String keyPath){
            CreateKey ck 
    = new CreateKey();
            
    try {
                ck.CreateKeyFile(keyPath);
            } 
    catch (NoSuchAlgorithmException ex) {ex.printStackTrace();
            } 
    catch (IOException ex) {ex.printStackTrace();
            }
        }

        
    /**
         * 加密
         * 
    @param sourcePath String 待加密文件路徑
         * 
    @param distinationPath String 文件加密后保存路徑
         * 
    @param keyPath String 密匙文件路徑
         
    */
        
    public void encrypt(String sourcePath,String distinationPath,String keyPath){
            EncryptData enc 
    = new EncryptData(keyPath);
            
    try {
                enc.createEncryptData(sourcePath, distinationPath);
            } 
    catch (ClassNotFoundException ex) {ex.printStackTrace();
            } 
    catch (SecurityException ex) {ex.printStackTrace();
            } 
    catch (NoSuchMethodException ex) {ex.printStackTrace();
            } 
    catch (InvocationTargetException ex) {ex.printStackTrace();
            } 
    catch (IllegalArgumentException ex) {ex.printStackTrace();
            } 
    catch (IllegalAccessException ex) {ex.printStackTrace();
            } 
    catch (InstantiationException ex) {ex.printStackTrace();
            } 
    catch (IOException ex) {ex.printStackTrace();
            } 
    catch (InvalidKeyException ex) {ex.printStackTrace();
            } 
    catch (NoSuchAlgorithmException ex) {ex.printStackTrace();
            } 
    catch (InvalidKeySpecException ex) {ex.printStackTrace();
            } 
    catch (NoSuchPaddingException ex) {ex.printStackTrace();
            } 
    catch (BadPaddingException ex) {ex.printStackTrace();
            } 
    catch (IllegalBlockSizeException ex) {ex.printStackTrace();
            } 
    catch (IllegalStateException ex) {ex.printStackTrace();
            }
        }

        
    /**
         * 解密文件
         * 
    @param sourcePath String 待解密文件路徑
         * 
    @param distinationPath String  解密后文件路徑
         * 
    @param keyPath String 密鑰路徑
         
    */
        
    public void unEncrypt(String sourcePath,String distinationPath,String keyPath){
           UnEncryptData unEnc 
    = new UnEncryptData(keyPath);
        
    try {
            unEnc.createUnEncryptData(sourcePath,distinationPath);
        } 
    catch (ClassNotFoundException ex) {ex.printStackTrace();
        } 
    catch (InvocationTargetException ex) {ex.printStackTrace();
        } 
    catch (IllegalArgumentException ex) {ex.printStackTrace();
        } 
    catch (IllegalAccessException ex) {ex.printStackTrace();
        } 
    catch (InstantiationException ex) {ex.printStackTrace();
        } 
    catch (SecurityException ex) {ex.printStackTrace();
        } 
    catch (NoSuchMethodException ex) {ex.printStackTrace();
        } 
    catch (IOException ex) {ex.printStackTrace();
        } 
    catch (InvalidKeyException ex) {ex.printStackTrace();
        } 
    catch (NoSuchAlgorithmException ex) {ex.printStackTrace();
        } 
    catch (InvalidKeySpecException ex) {ex.printStackTrace();
        } 
    catch (NoSuchPaddingException ex) {ex.printStackTrace();
        } 
    catch (BadPaddingException ex) {ex.printStackTrace();
        } 
    catch (IllegalBlockSizeException ex) {ex.printStackTrace();
        } 
    catch (IllegalStateException ex) {ex.printStackTrace();
        }
        }

        
    public static void main(String[] args) {
            TestEncrypt e 
    = new TestEncrypt();
            e.createKey(
    "classes\\resource\\key1");
            e.encrypt(
    "classes\\resource\\a.txt","classes\\resource\\ena.txt","classes\\resource\\key1");
            e.unEncrypt(
    "classes\\resource\\ena.txt","classes\\resource\\una.txt","classes\\resource\\key1");
        }
    }
    posted on 2006-05-19 09:23 Derek.Guo 閱讀(1416) 評論(1)  編輯  收藏 所屬分類: Java

    評論:
    # re: DES加密 2010-05-21 14:25 | woxiangbo
    為什么我運行會出異常呢?
    我已經(jīng)手動船槳了這兩個文件啊
    java.io.FileNotFoundException: classes\resource\a.txt (系統(tǒng)找不到指定的文件。)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at com.crypto.encrypt.Util.readFile(Util.java:44)
    at com.crypto.encrypt.EncryptData.encryptData(EncryptData.java:67)
    at com.crypto.encrypt.EncryptData.createEncryptData(EncryptData.java:50)
    at com.crypto.encrypt.TestEncrypt.encrypt(TestEncrypt.java:48)
    at com.crypto.encrypt.TestEncrypt.main(TestEncrypt.java:105)
    java.io.FileNotFoundException: classes\resource\ena.txt (系統(tǒng)找不到指定的文件。)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at com.crypto.encrypt.Util.readFile(Util.java:44)
    at com.crypto.encrypt.UnEncryptData.unEncryptData(UnEncryptData.java:55)
    at com.crypto.encrypt.UnEncryptData.createUnEncryptData(UnEncryptData.java:40)
    at com.crypto.encrypt.TestEncrypt.unEncrypt(TestEncrypt.java:96)
    at com.crypto.encrypt.TestEncrypt.main(TestEncrypt.java:106)  回復  更多評論
      
    MSN:envoydada@hotmail.com QQ:34935442
    主站蜘蛛池模板: 国产免费网站看v片在线| 亚洲第一男人天堂| 黄色网页在线免费观看| 国产成人啪精品视频免费网| 亚洲人成高清在线播放| 国产啪精品视频网免费| 亚洲区视频在线观看| 大学生一级毛片免费看| 亚洲性色AV日韩在线观看| 成人毛片18岁女人毛片免费看| 亚洲国产成人91精品| 在线看片人成视频免费无遮挡| 久久精品国产亚洲AV蜜臀色欲| 久久WWW色情成人免费观看| 亚洲免费福利视频| 日韩成人免费在线| 成年网站免费入口在线观看| 亚洲日韩欧洲乱码AV夜夜摸| 在线观看免费播放av片| 亚洲无限乱码一二三四区| 我要看免费的毛片| av电影在线免费看| 久久精品国产亚洲av高清漫画 | 亚洲va在线va天堂va888www| 日本免费一区二区三区| 亚洲www在线观看| 亚洲第一区精品日韩在线播放| a级毛片在线免费| 亚洲丰满熟女一区二区v| 国产成人免费片在线观看| 国产免费久久精品丫丫| 亚洲日本国产乱码va在线观看| 国产片免费福利片永久| 日韩精品无码免费专区午夜不卡| 亚洲高清免费在线观看| 四只虎免费永久观看| 久久国产精品2020免费m3u8| 亚洲娇小性xxxx色| 亚洲精品色午夜无码专区日韩| 97人妻无码一区二区精品免费| 猫咪免费人成在线网站 |