1. 程式人生 > >DES加密演算法的java實現(基於java類庫)

DES加密演算法的java實現(基於java類庫)

嗯嗯........這個是我新開的部落格上的第一篇的文章,這裡小白希望自己的技術能夠一天比一天好(p≧w≦q),加油!

好吧,現在來一個基於java類庫的DES加密演算法的實現吧~網上不少的程式碼要不執行有問題,要不就是簡簡單單內建一個固定的加密字串就簡單完事了。好吧,我承認我現在是為懶人服務的,不過這裡面還是有一點點需要解決的問題的啊!

注意的問題,在儲存檔案的時候,不要把它轉為String在存到檔案裡面去,因為在轉為String的時候,byte型別會發生變化,所以我是直接儲存byte的,而且前面要生成一個DES key,方便不同文件之間的加解密。


先附上原始碼

//因為樓主經常跨平臺,MAC、Windows兩邊跑,中文容易亂碼,所以英文註釋哦



這個有一個問題,就是在加密完成,解密後會丟掉換行符。。。

import java.util.Scanner;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;

import java.util.*;
import java.awt.*;
import java.io.*;
import java.math.*;

public class DES_N {
	String password="95880228";
	String algorithm="DES";
	SecretKey DESkey;
	public byte[] decryptFun(byte[] cipertext){
		try{
			
			//use the ciper text in a byte type from the father function
			if(!(new File("DESkey.dat")).exists()){
				System.out.println("can not find the DES key!");
				return null;
			}
			else{
				ObjectInputStream in = new ObjectInputStream(new FileInputStream("DESkey.dat"));
				DESkey = (SecretKey)in.readObject();
				in.close();
			}
			Cipher cipher = Cipher.getInstance(algorithm);
			cipher.init(Cipher.DECRYPT_MODE, DESkey);
			//System.out.println("decrypt string:"+cipertext.toString());
			return  cipher.doFinal(cipertext);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	public byte[] encrypt(String input)
	{
		try{
			BufferedReader in_clear = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
			StringBuffer content = new StringBuffer();
			String s="";
			while((s=in_clear.readLine())!=null){
				content.append(s);
			}
			in_clear.close();
			
			String cleartext=content.toString();
			if(!(new File("DESkey.dat")).exists()){
				System.out.println("creating DES key");
				KeyGenerator keygen=KeyGenerator.getInstance(algorithm);
				DESkey = keygen.generateKey();
				
				ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("DESkey.dat"));
				outputStream.writeObject(DESkey);
				outputStream.close();
			}
			else{
				System.out.println("read DES key");
				ObjectInputStream in = new ObjectInputStream(new FileInputStream("DESkey.dat"));
				DESkey = (SecretKey)in.readObject();
				in.close();
			}
			Cipher c1=Cipher.getInstance(algorithm);
			c1.init(Cipher.ENCRYPT_MODE, DESkey);
			
			return c1.doFinal(cleartext.getBytes());
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	
	
	public byte[] encryptFun(String inputfile) {
		try{
			BufferedReader in_clear = new BufferedReader(new InputStreamReader(new FileInputStream(inputfile)));
			StringBuffer content = new StringBuffer();
			String s="";
			while((s=in_clear.readLine())!=null){
				content.append(s);
			}
			in_clear.close();
			String cleartext=content.toString();
			//get the content from a document
			
			SecureRandom random = new SecureRandom();
			DESKeySpec deskey = new DESKeySpec(password.getBytes());
			
			//creat a key factory 
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey secrekey=keyFactory.generateSecret(deskey);
			
			//use ciper object to encrypt
			Cipher cipher=Cipher.getInstance(algorithm);
			cipher.init(Cipher.ENCRYPT_MODE, secrekey,random);
			
			return cipher.doFinal(cleartext.getBytes());
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	
	public byte[] readInbyte(String inputname)
	{
		try{
			File file = new File(inputname);
			FileInputStream in = new FileInputStream(file);
			long filesize = file.length();
			byte[] readin = new byte[(int)filesize];
			
			int offset=0;
			int numRead=0;
			
			while(offset<readin.length&&(numRead = in.read(readin, offset, readin.length-offset))>=0){
				offset+=numRead;
			}
			if(offset!=readin.length){
				throw new IOException("can not read completely of file :"+file.getName());
			}
			in.close();
			return readin;
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		System.out.println("Please select the running mode:");
		System.out.println("1.encrypt");
		System.out.println("2.decrypt");
		DES_N des=new DES_N();
		Scanner scanner = new Scanner(System.in);
		int mode;
		mode = scanner.nextInt();
		switch (mode) {
		case 1:{
			System.out.println("Input the encrypt file name");
			scanner.nextLine();
			String input=scanner.nextLine();
			System.out.println("Input the ciper file name");
			String cipername=scanner.nextLine();
			byte[] ciper = des.encrypt(input);
			//System.out.println(ciper.toString());
			System.out.println(ciper);
			
			//write the byte from the ciper into a document
			try{
				FileOutputStream out = new FileOutputStream(new File(cipername));
				out.write(ciper);
				out.close();
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			System.out.println("des decrypt"+new String(des.decryptFun(ciper)));
			break;
		
		}
			case 2:{
			System.out.println("Input the decrypt file");
			scanner.nextLine();
			String input = scanner.nextLine();
			System.out.println("Input the plain text name");
			String outname = scanner.nextLine();
			
			byte[] clear = des.readInbyte(input);
			clear = des.decryptFun(clear);
			System.out.println("decrypt content:  "+new String(clear));
			try{
				FileOutputStream outputStream = new FileOutputStream(new File(outname));
				outputStream.write(clear);
				outputStream.close();
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			break;
		}
		default:
			break;
		}
	}	
}