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.

}<br />

}<br />

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

}<br />

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

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

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

catch (NoSuchAlgorithmException e) {<br />

System.err.println(e);<br />

e.printStackTrace();<br />

}<br />

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

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

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

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

Let's investigate some of the methods used in Examples Example 10.6 and Example 10.7 in<br />

more detail.<br />

10.5.1 init( )<br />

Before a Cipher object can encrypt or decrypt data, it requires four things:<br />

• The mode to operate in [8]<br />

• A key<br />

• Algorithm parameters, e.g., an initialization vector<br />

• A source of randomness<br />

The init() method prepares the cipher by providing these four quantities or reasonable<br />

defaults. There are six overloaded variants:<br />

public final void init(int opmode, Key key) throws InvalidKeyException<br />

public final void init(int opmode, Key key, SecureRandom random)<br />

throws InvalidKeyException<br />

public final void init(int opmode, Key key, AlgorithmParameterSpec params)<br />

throws InvalidKeyException, InvalidAlgorithmParameterException<br />

public final void init(int opmode, Key key, AlgorithmParameterSpec params,<br />

SecureRandom random) throws InvalidKeyException,<br />

InvalidAlgorithmParameterException<br />

public final void init(int opmode, Key key, AlgorithmParameters params)<br />

throws InvalidKeyException, InvalidAlgorithmParameterException<br />

public final void init(int opmode, Key key, AlgorithmParameters params,<br />

SecureRandom random) throws InvalidKeyException,<br />

InvalidAlgorithmParameterException<br />

You can reuse a cipher object by invoking its init() method a second time. If you do, all<br />

previous information in the object is lost.<br />

10.5.1.1 Mode<br />

The mode determines whether this cipher is used for encryption or decryption. The mode<br />

argument has two possible values, which are both mnemonic constants defined by the Cipher<br />

class: Cipher.ENCRYPT_MODE and Cipher.DECRYPT_MODE .<br />

8 This is the mode the cipher should operate in; that is, encryption or decryption; this is not a block cipher mode.<br />

221

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

Saved successfully!

Ooh no, something went wrong!