⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileencryptor.java~59~

📁 使用PBE和三重DES加密文件
💻 JAVA~59~
字号:
package fileencryptor;import java.io.*;import java.security.*;import javax.crypto.*;import javax.crypto.spec.*;public class FileEncryptor{private static final String PBEALGORITHM="PBEWithMD5AndDES";private static final String ALGORITHM="DESede";private static final String OPMODE="DESede/CBC/PKCS5Padding";private static final int KEY_LENGTH=168;private static final int ITERATION=1000;private static final int SALT_LENGTH=8;private static final int IV_LENGTH=8;private static final int BUFFER_SIZE=4096;        /**         * get a cipher for PBE encrypt or decrypt         * @param mode cipher mode,it must be Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE         * @param salt salt         * @param iteration iteration         * @param password password         * @throws GeneralSecurityException         * @return Cipher         */        private Cipher getPBECipher(int mode,byte[] salt,int iteration,char[] password) throws GeneralSecurityException        {                PBEKeySpec pbekspec;                SecretKeyFactory kfactory;                SecretKey pbekey;                PBEParameterSpec pbeparam;                Cipher cipher;                pbekspec=new PBEKeySpec(password);                kfactory=SecretKeyFactory.getInstance(PBEALGORITHM);                pbekey=kfactory.generateSecret(pbekspec);                pbeparam=new PBEParameterSpec(salt,iteration);                cipher=Cipher.getInstance(PBEALGORITHM);                cipher.init(mode,pbekey,pbeparam);                return cipher;        }        /**         * get a cipher in encrypt or decrypt use         * @param mode cipher mode,it must be Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE         * @param key secrey key         * @param iv the initialization vector         * @throws GeneralSecurityException         * @return Cipher         */        private Cipher getCipher(int mode,SecretKey key,byte[] iv) throws GeneralSecurityException        {                Cipher cipher;                cipher=Cipher.getInstance(OPMODE);                cipher.init(mode,key,new IvParameterSpec(iv));                return cipher;        }        /**         * save secret key in file with PBE         * @param key secret key used to encrypt/decrypt file         * @param password the password used to encrypt secret key         * @param path file path         * @throws GeneralSecurityException         * @throws IOException         */        private void saveKey(SecretKey key,char[] password,String path) throws GeneralSecurityException,IOException        {                byte[] salt;                SecureRandom srandom;                Cipher pbecipher;                BufferedOutputStream out=null;                //create salt PBE needed                salt=new byte[SALT_LENGTH];                srandom=new SecureRandom();                srandom.nextBytes(salt);                pbecipher=getPBECipher(Cipher.ENCRYPT_MODE,salt,ITERATION,password);//get cipher for PBE use                try                {                        out=new BufferedOutputStream(new FileOutputStream(path));                        out.write(salt);//write salt into file                        out.write(pbecipher.doFinal(key.getEncoded()));//encrypt key and save it into file                        out.flush();                }                catch(IOException exc)                {                        throw exc;                }                finally                {                        try                        {                                if(out!=null) out.close();                        }                        catch(IOException exc2)                        {}                }        }        /**         * load and decrypt a secrey key from a file         * @param password password         * @param path file path         * @throws GeneralSecurityException         * @throws IOException         * @return SecretKey         */        private SecretKey loadKey(char[] password,String path) throws GeneralSecurityException,IOException        {                int b;                byte[] all,salt,bkey;                Cipher pbecipher;                BufferedInputStream in=null;                ByteArrayOutputStream content=null;                //read salt and key from file                try                {                        in=new BufferedInputStream(new FileInputStream(path));                        content=new ByteArrayOutputStream();                        for(;(b=in.read())!=-1;) content.write(b);                        all=content.toByteArray();                }                catch(IOException exc)                {                        throw exc;                }                finally                {                        try                        {                                if(in!=null) in.close();                        }                        catch(IOException exc)                        {}                        try                        {                                if(content!=null) content.close();                        }                        catch(IOException exc2)                        {}                }                //get salt                salt=new byte[SALT_LENGTH];                System.arraycopy(all,0,salt,0,SALT_LENGTH);                //get encrypted key                bkey=new byte[all.length-SALT_LENGTH];                System.arraycopy(all,salt.length,bkey,0,bkey.length);                pbecipher=getPBECipher(Cipher.DECRYPT_MODE,salt,ITERATION,password);//get cipher for PBE use                return new SecretKeySpec(pbecipher.doFinal(bkey),ALGORITHM);        }        /**         * get the secret key from file,if key file do not exists,create a new key and save it in file         * @param password password used to encrypt secret key         * @param path key file path         * @throws Exception         * @return SecretKey         */        private SecretKey getKey(char[] password,String path) throws GeneralSecurityException,IOException        {                File kpath;                KeyGenerator kgene;                SecretKey key;                kpath=new File(path);                if(kpath.exists()) return loadKey(password,path); //key exists                //key do not exists                else                {                        //create a new secret key                        kgene=KeyGenerator.getInstance(ALGORITHM);                        kgene.init(KEY_LENGTH);                        key=kgene.generateKey();                        saveKey(key,password,path);//save it                        return key;                }        }        /**         * encrypt or decrypt a file         * @param mode cipher mode,it must be Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE         * @param password password         * @param kpath key path         * @param inputpath file path         * @param outputpath the output file path         * @throws GeneralSecurityException         * @throws IOException         */        public void endecrypt(int mode,char[] password,String kpath,String inputpath,String outputpath) throws GeneralSecurityException,IOException        {                int length;                SecureRandom srandom;                SecretKey key;                Cipher cipher;                BufferedInputStream in=null;                BufferedOutputStream out=null;                CipherOutputStream cout=null;                byte[] buffer,iv;                try                {                        key=getKey(password,kpath);//decrypt key from key file                        in=new BufferedInputStream(new FileInputStream(inputpath));                        out=new BufferedOutputStream(new FileOutputStream(outputpath));                        iv=new byte[IV_LENGTH];                        //create a new random iv                        if(mode==Cipher.ENCRYPT_MODE)                        {                                srandom=new SecureRandom();                                srandom.nextBytes(iv);                                out.write(iv);//write iv into output file without encrypt                        }                        else if(mode==Cipher.DECRYPT_MODE) in.read(iv);//read iv                        cipher=getCipher(mode,key,iv);                        cout=new CipherOutputStream(out,cipher);                        buffer=new byte[BUFFER_SIZE];                        for(;(length=in.read(buffer))>0;) cout.write(buffer,0,length);                        cout.flush();                }                catch(IOException exc)                {                        throw exc;                }                finally                {                        try                        {                                if(in!=null) in.close();                        }                        catch(IOException exc2)                        {}                        try                        {                                if(cout!=null) cout.close();                        }                        catch(IOException exc3)                        {}                }        }        public void showHelp()        {                System.out.println("this application is used to encrypt or decrypt a file with TripleDES"+                                   " algorithm,the secret also encrypted with a password.");                System.out.println("usage:");                System.out.println("java -jar fileencryptor.jar [-e|-d] [input file path] [output file path] [secret key path] [password]");                System.out.println("-e: encrypt");                System.out.println("-d: decrypt");        }        public static void main(String args[]) throws GeneralSecurityException,IOException        {                FileEncryptor encryptor;                encryptor=new FileEncryptor();                if(args.length!=5) encryptor.showHelp();                else                {                        if(args[0].equals("-e")) encryptor.endecrypt(Cipher.ENCRYPT_MODE,args[4].toCharArray(),args[3],args[1],args[2]);                        else if(args[0].equals("-d")) encryptor.endecrypt(Cipher.DECRYPT_MODE,args[4].toCharArray(),args[3],args[1],args[2]);                        else encryptor.showHelp();                }        }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -