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.

public class SealedPoint {<br />

}<br />

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

}<br />

String filename = "point.des";<br />

Point tdp = new Point(32, 45);<br />

try {<br />

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

ObjectOutputStream oout = new ObjectOutputStream(fout);<br />

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

// Create a key.<br />

byte[] desKeyData = {(byte) 0x90, (byte) 0x67, (byte) 0x3E,<br />

(byte) 0xE6, (byte) 0x42, (byte) 0x15, (byte) 0x7A, (byte) 0xA3 };<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/ECB/PKCS5Padding");<br />

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

SealedObject so = new SealedObject(tdp, des);<br />

oout.writeObject(so);<br />

oout.close();<br />

}<br />

catch (<strong>IO</strong>Exception e) { System.err.println(e); }<br />

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

Reading a sealed object from an object input stream is easy. You read it exactly as you read<br />

any other object from an object input stream. For example:<br />

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

ObjectInputStream oin = new ObjectInputStream(fin);<br />

SealedObject so = (SealedObject) oin.readObject();<br />

Once you've read the object, unsealing it to retrieve the original object is straightforward,<br />

provided you know the key. There are three getObject() methods that return the original<br />

object:<br />

public final Object getObject(Key key) throws <strong>IO</strong>Exception,<br />

ClassNotFoundException, NoSuchAlgorithmException, InvalidKeyException<br />

public final Object getObject(Cipher c) throws <strong>IO</strong>Exception,<br />

ClassNotFoundException, IllegalBlockSizeException, BadPaddingException<br />

public final Object getObject(Key key, String provider) throws <strong>IO</strong>Exception,<br />

ClassNotFoundException, NoSuchAlgorithmException,<br />

NoSuchProviderException,<br />

InvalidKeyException<br />

The first variant is the most useful, since it only requires the key. It does not require you to<br />

create and initialize a Cipher object. You will in general need to know the algorithm used in<br />

order to know what kind of key to create, but that information is available from the<br />

getAlgorithm() method:<br />

public final String getAlgorithm()<br />

265

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

Saved successfully!

Ooh no, something went wrong!