使用密码来加密解密
package com.test;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.OutputStream;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.KeyGenerator;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.PBEKeySpec;import javax.crypto.spec.PBEParameterSpec;public class CipherTest{public static void main(String[] args){try{//secretEncrypt();secretDecrypt();}catch (Exception e){// TODO Auto-generated catch blocke.printStackTrace();}}private static void secretEncrypt() throws Exception{Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");SecretKey key2 = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec("123456789".toCharArray()));PBEParameterSpec parameterSpec = new PBEParameterSpec(new byte[]{1,2,3,4,5,6,7,8},100);//加密cipher.init(Cipher.ENCRYPT_MODE, key2, parameterSpec);byte[] result = cipher.doFinal("aab".getBytes());OutputStream os = new FileOutputStream("secret_data");BufferedOutputStream bos = new BufferedOutputStream(os);bos.write(result);bos.close();os.close();System.out.println(new String(result));}private static void secretDecrypt() throws Exception{//解密Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");SecretKey key2 = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec("123456789".toCharArray()));PBEParameterSpec parameterSpec = new PBEParameterSpec(new byte[]{1,2,3,4,5,6,7,8},100);cipher.init(Cipher.DECRYPT_MODE, key2,parameterSpec);InputStream is = new FileInputStream("secret_data");BufferedInputStream bis = new BufferedInputStream(is);//ByteArrayOutputStream baos = new ByteArrayOutputStream();//方法一://byte[] rs = new byte[1024];//int length = 0;//while((length = bis.read(rs)) != -1){//baos.write(rs, 0, length);//}//方法二:byte[] rs = new byte[bis.available()];int length = bis.read(rs);int total = 0;while(total < bis.available()){total += length;length = bis.read(rs, total, bis.available() - total);}//System.out.println(new String(cipher.doFinal(baos.toByteArray())));System.out.println(new String(cipher.doFinal(rs)));//baos.close();bis.close();is.close();}}