java调用AES算法产生密钥并加解密文件

        最近在做一个项目,要用到数据加密算法,所以就看了下《java加密与解密的艺术》这本书,最后就参考了下AES加密算法来加密文件,一是它加密标准高、密钥建立时间短、灵敏性好、内存需求低,二是因为javaAPI已经自带了AES算法,用起来很方便顺手,当然,这个还不算,密钥的产生还调用了Base64算法对AES产生的密钥进行了二次加密,确保密钥的安全可靠,大家有兴趣的话可以去看看《java加密与解密的艺术》一书,这里我贴上代码供参考:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.SecureRandom;
import java.util.Date;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class Test {
	
	private static final int ZERO = 0;
	private static final int ONE = 1;
	private static String derectory = "c:";
	private static File file1;
	private static String str = null;
	
	public static byte[] initKey() throws Exception{
		//实例化
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		//设置密钥长度
		kgen.init(128);
		//生成密钥
		SecretKey skey = kgen.generateKey();
		//返回密钥的二进制编码
		return skey.getEncoded();
	}
	
	public static void main(String[] args) {
		try {
			byte[] key = Test.initKey();
			str = Base64.encodeBase64String(key);
			System.out.println(str);
			File file = new File(derectory+"/"+"k.txt");		
			encryptfile(file,str);
			decriptfile(file1,str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 文件处理方法
	 * code为加密或者解密的判断条件
	 * key 加密密钥
	 */
	public static void doFile(int code, File file, String key) throws Exception{
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				file));
		byte[] bytIn = new byte[(int) file.length()];
		bis.read(bytIn);
		bis.close();
		// AES加密
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		kgen.init(128, new SecureRandom(key.getBytes()));
		SecretKey skey = kgen.generateKey();
		byte[] raw = skey.getEncoded();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		if(0 == code){
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		}else if(1 == code){
			cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		}		
		// 写文件
		byte[] bytOut = cipher.doFinal(bytIn);
		file1 = new File(derectory+"/"+new Date().getTime()+"."+file.getName().split("\\.")[1]);
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(file1));
		bos.write(bytOut);
		bos.close();
	}
	
	//文件加密
	public static void encryptfile(File file, String key) throws Exception {
		doFile(ZERO,file,key);
	}
	
	//文件解密
	public static void decriptfile(File file, String key) throws Exception{
		doFile(ONE,file,key);
	}
}

注:Base64是需要加入commons-codec-1.4.jar以上的包的,所以需要大家去下一个!这个算法加密的效率还是很可观的,如果有可以改进的地方望大家多赐教啊!

你可能感兴趣的:(java)