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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

import javax.crypto.*;<br />

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

public class FileEncryptor {<br />

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

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

System.err.println("Usage: java FileEncryptor filename password");<br />

return;<br />

}<br />

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

String password = args[1];<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(args[0]);<br />

FileOutputStream fout = new FileOutputStream(args[0] + ".des");<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 />

// Use Data Encryption Standard.<br />

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

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

// Write the initialization vector onto the output.<br />

byte[] iv = des.getIV();<br />

DataOutputStream dout = new DataOutputStream(fout);<br />

dout.writeInt(iv.length);<br />

dout.write(iv);<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) dout.write(output);<br />

}<br />

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

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

fin.close();<br />

dout.flush();<br />

dout.close();<br />

}<br />

catch (InvalidKeySpecException e) {System.err.println(e);}<br />

catch (InvalidKeyException e) {System.err.println(e);}<br />

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

218

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

Saved successfully!

Ooh no, something went wrong!