我想加密我生成的Zip文件,其中包含一个文件在它里面。我想用密码加密它。这是我第一次使用Encryption。我做了我自己的research,我似乎理解但不清楚它是如何工作的。有谁能提供一个清晰的例子,一个好的encrypting的方法,向我解释一下,我如何实现它,或者给予一个例子。你的帮助将不胜感激。
Encryption
research
encrypting
dtcbnfnu1#
我是这样使用CipherOutputStream的:
CipherOutputStream
public static void encryptAndClose(FileInputStream fis, FileOutputStream fos) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { // Length is 16 byte SecretKeySpec sks = new SecretKeySpec("1234567890123456".getBytes(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream for encoding CipherOutputStream cos = new CipherOutputStream(fos, cipher); //wrap output with buffer stream BufferedOutputStream bos = new BufferedOutputStream(cos); //wrap input with buffer stream BufferedInputStream bis = new BufferedInputStream(fis); // Write bytes int b; byte[] d = new byte[8]; while((b = bis.read(d)) != -1) { bos.write(d, 0, b); } // Flush and close streams. bos.flush(); bos.close(); bis.close(); } public static void decryptAndClose(FileInputStream fis, FileOutputStream fos) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { SecretKeySpec sks = new SecretKeySpec("1234567890123456".getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sks); CipherInputStream cis = new CipherInputStream(fis, cipher); //wrap input with buffer stream BufferedInputStream bis = new BufferedInputStream(cis); //wrap output with buffer stream BufferedOutputStream bos = new BufferedOutputStream(fos); int b; byte[] d = new byte[8]; while((b = bis.read(d)) != -1) { bos.write(d, 0, b); } bos.flush(); bos.close(); bis.close(); }
我是这样使用它的:
File output= new File(outDir, outFilename); File input= new File(inDir, inFilename); if (input.exists()) { FileInputStream inStream = new FileInputStream(input); FileOutputStream outStream = new FileOutputStream(output); encryptAndClose(inStream, outStream); }
1条答案
按热度按时间dtcbnfnu1#
我是这样使用
CipherOutputStream
的:我是这样使用它的: