When files are uploaded and downloaded, the files are encrypted.
1. Define Key
// encrypt the required key object Private Static Key key;
2, initialize the key (encryption and decryption method Getkey ("XX") in the same xx)
/*** Generate key based on parameters*/ Public Static voidGetKey (String strkey) {Try{keygenerator Generator= Keygenerator.getinstance ("DES"); Generator.init (NewSecureRandom (Strkey.getbytes ())); Key=Generator.generatekey (); } Catch(Exception e) {Throw NewRuntimeException ("Error Initializing Sqlmap class. Cause: "+e); }}
3. Encryption
/*** Encryption of files *@paramSrcfile *@throwsException*/ Public Static voidEncfile (File srcfile)throwsException {if(!srcfile.exists ()) { Throw NewWarnexception ("file does not exist!) "); } String fileName=Srcfile.getabsolutepath (); inti = Filename.lastindexof (".")); if(i>0) {FileName= filename.substring (0, i); } File encfile=NewFile (fileName); GetKey ( "AAAA"); Cipher Cipher= Cipher.getinstance ("DES"); Cipher.init (Cipher.encrypt_mode,key); InputStream is=NewFileInputStream (srcfile); CipherOutputStream out=NewCipherOutputStream (NewFileOutputStream (encfile), cipher); Ioutils.copylarge (is, out); Is.close (); Out.flush (); Out.close (); Srcfile.delete ();}
4. Decryption
/*** Decryption *@paramSrcfile *@paramsuffix *@return * @throwsException*/ Public StaticFileInputStream decfile (File srcfile,string suffix)throwsException {fileinputstream fis=NULL; if(!srcfile.exists ()) { Throw NewWarnexception ("file does not exist!) "); } String fileName= Srcfile.getabsolutepath () + "." +suffix; File Decfile=NewFile (fileName); GetKey ( "AAAA"); Cipher Cipher= Cipher.getinstance ("DES"); Cipher.init (Cipher.decrypt_mode, key); InputStream is=NewFileInputStream (srcfile); OutputStream out=NewFileOutputStream (Decfile); CipherOutputStream Cos=NewCipherOutputStream (out, cipher); byte[] buffer =New byte[1024]; intlength; while(length = is.read (buffer)) >= 0) {cos.write (buffer,0, length); } FIS=NewFileInputStream (Decfile); Cos.close (); Out.close (); Is.close (); returnfis;}
Upload and download file encryption