`
jiuyuehe
  • 浏览: 181289 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

使用DES 加密方式对文件进行加密!!!

阅读更多
DES加密由于在java中非常方便使用,而且性能不错,所以非常流行!!!
使用DES 首先需要密钥。。2种方法:第一自己设置

//自己设置
private final static String encodeKey ="moomaia";

  
	private Key getKey() throws Exception {
		// 创建一个空的8位字节数组(默认值为0)
		byte[] arrBTmp = encodeKey.getBytes();
		System.out.println(arrBTmp.length);
		byte[] arrB = new byte[8];
		// 将原始字节数组转换为8位
		for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
			arrB[i] = arrBTmp[i];
		}
		// 生成密钥
		
		System.out.println(arrB.length);
		Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
		return key;
	}
    




第二种:系统生成:
 private void createKey() {
        try {
            // 得到密钥的实例 以什么方式加密。加密的方式比较多。
            KeyGenerator kg = KeyGenerator.getInstance("DES");
            kg.init(56);
            
            SecretKey key = kg.generateKey();
            // 将生成的密钥对象写入文件。
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                    new FileOutputStream(new File("e:\\key.obj")));
            objectOutputStream.writeObject(key);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 /**
     * @param KeyFilePath
     *            密钥Key对象的路径。注意使用该方法的时候,确保你已经生成了密钥。
     * @return
     * @Description 从文件中读出Key,用于加密使用。
     */
    private static Key getKey(String KeyFilePath) {
        Key key = null;
        try {
            // 将生成的密钥对象从文件中读取出来,然后再强制转换成一个密钥对象。
            ObjectInputStream objectInputStream = new ObjectInputStream(
                    new FileInputStream(new File(KeyFilePath)));
            key = (Key) objectInputStream.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return key;
    }



有了密钥之后开始对文件加密:详情见代码:【酷毙程序员,一切都在代码中】


 /**
     * 
     * 字符串加密  ---byte[]
     * @param source
     * @return 放回一个byte数组,为什么不放回字符串,是因为解密的时候要传入这个byte数组才能进行解密,如果解密的时候传入的是字符串
     *         那么就会出错,愿意是编码的问题。
     * @throws Exception 
     * @Description 将传入的字符串进行加密 下面写了将这种byte数组转换成字符串的方法。直接在调用就行了。
     */
    public  String encrypt(String source) throws Exception {
    	byte[] target =null;
    	File srcFile = new File(source);
    	System.out.println(srcFile.getCanonicalPath());
    	if(!srcFile.exists()){
    		System.out.println("文件不存在");
    	}
    	String newName = srcFile.getAbsolutePath()+".m";
    	FileInputStream fis = new FileInputStream(srcFile);
    	int fileSize = fis.available();
    	FileOutputStream fos = new FileOutputStream(new File(newName));
    	
    	Key key = getKey();
        try {
        	Cipher cipher = Cipher.getInstance("DES");
        	cipher.init(Cipher.ENCRYPT_MODE, key);
        	byte[] buf = new byte[fileSize];
        	System.out.println(fileSize);
        	int c = 0;
        	while((c=fis.read(buf))!=-1){
        		target = cipher.doFinal(buf);
        		//base64encoder.encode(target,fos);
        		fos.write(target);
        	}
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return newName;
    }


当然也可分成小点方法:代码就好的看点

把解密分开写:


/**
     * 解密----byte[]
     * @param source
     *            加密后的byte数组。可用加密方法encrypt(“String”)生成即可
     * @return 解密后的字符串。
     * @throws Exception 
     * @Description 解密算法。
     */
    public  byte[] decrypt(byte[] source) {
        byte[] dissect = null;
        try {
            Key key = getKey();
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);// 使用私钥解密
            dissect = cipher.doFinal(source);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return dissect;
    }
    
    
    /**从File ---->byte[]
     * @return
     * @Description 由于加密之前采用了编码的格式 所以现在采用特点的方式读出来 ,然后得到用一个byte[]用于解码。
     */
    public byte[] getByteFromFile(){
        //BASE64Decoder base64decoder = new BASE64Decoder();
    	 byte[] encodeByte =null;
        try {
           // encodeByte = base64decoder.decodeBuffer(new FileInputStream(new File("D:\\t.txt")));
            FileInputStream fis =new FileInputStream(new File("D:\\ch03.pdf.m"));
            int fileSize = fis.available();
            encodeByte = new byte[fileSize];
            fis.read(encodeByte);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return encodeByte;
    }
    
    /**
     * 写入文件
     * @param b
     * @param filePath
     * @Description 将指定的字节写入到文件中。
     */
    public  void writeByteToFile(byte[] b, String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream fileOutputStream;
        try {
            fileOutputStream = new FileOutputStream(file);
            
            fileOutputStream.write(b);
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


测试代码:速度相当之快,DES>>base64encode.估计也是流行原因之一

 public static void main(String[] args) throws Exception {
    	
    	DESofFile desf= new DESofFile();
    	//desf.createKey();
    	Date times = new Date();
    	long start = times.getTime();
    		desf.encrypt("d:\\ch03.pdf");
    		desf.writeByteToFile(desf.decrypt(desf.getByteFromFile()), "d:\\ch03-9.pdf");
    	Date times2 = new Date();
    	long end =times2.getTime();
    	
    	System.out.println(end - start);
    }



引用

本人菜鸟。错误的地方虚心请教!!谢谢
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics