23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Example 10.7. FileDecryptor<br />

import java.io.*;<br />

import java.security.*;<br />

import java.security.spec.*;<br />

import javax.crypto.*;<br />

import javax.crypto.spec.*;<br />

public class FileDecryptor {<br />

public static void main(String[] args) {<br />

if (args.length != 3) {<br />

System.err.println("Usage: java FileDecryptor infile outfile<br />

password");<br />

return;<br />

}<br />

String infile = args[0];<br />

String outfile = args[1];<br />

String password = args[2];<br />

if (password.length() < 8 ) {<br />

System.err.println("Password must be at least eight characters<br />

long");<br />

}<br />

try {<br />

FileInputStream fin = new FileInputStream(infile);<br />

FileOutputStream fout = new FileOutputStream(outfile);<br />

// Create a key.<br />

byte[] desKeyData = password.getBytes();<br />

DESKeySpec desKeySpec = new DESKeySpec(desKeyData);<br />

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");<br />

SecretKey desKey = keyFactory.generateSecret(desKeySpec);<br />

// Read the initialization vector.<br />

DataInputStream din = new DataInputStream(fin);<br />

int ivSize = din.readInt();<br />

byte[] iv = new byte[ivSize];<br />

din.readFully(iv);<br />

IvParameterSpec ivps = new IvParameterSpec(iv);<br />

// Use Data Encryption Standard.<br />

Cipher des = Cipher.getInstance("DES/CBC/PKCS5Padding");<br />

des.init(Cipher.DECRYPT_MODE, desKey, ivps);<br />

byte[] input = new byte[64];<br />

while (true) {<br />

int bytesRead = fin.read(input);<br />

if (bytesRead == -1) break;<br />

byte[] output = des.update(input, 0, bytesRead);<br />

if (output != null) fout.write(output);<br />

}<br />

byte[] output = des.doFinal();<br />

if (output != null) fout.write(output);<br />

fin.close();<br />

fout.flush();<br />

fout.close();<br />

<strong>Java</strong> I/O<br />

220

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!