Java Reference
In-Depth Information
Example 6−5: TripleDES.java (continued)
* uses Cipher directly to show how it can be done without
* CipherInputStream and CipherOutputStream.
**/
public static void decrypt(SecretKey key, InputStream in, OutputStream out)
throws NoSuchAlgorithmException, InvalidKeyException, IOException,
IllegalBlockSizeException, NoSuchPaddingException,
BadPaddingException
{
// Create and initialize the decryption engine
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.DECRYPT_MODE, key);
// Read bytes, decrypt, and write them out.
byte[] buffer = new byte[2048];
int bytesRead;
while((bytesRead = in.read(buffer)) != -1) {
out.write(cipher.update(buffer, 0, bytesRead));
}
// Write out the final bunch of decrypted bytes
out.write(cipher.doFinal());
out.flush();
}
}
Exercises
6-1. Write a PasswordManager class that associates usernames with passwords and
has methods for creating and deleting username/password pairs, changing
the password associated with a username, and authenticating a user by verify-
ing a supplied password. PasswordManager should store the usernames and
passwords in a file (or in a database, if you've already read Chapter 17,
Database Access with SQL ).
Note, however, that the class should not store the passwords as plain text as
that would allow an intruder who broke into the PasswordManager system to
obtain full access to all passwords. To prevent this, it is common to use a
one-way function to encrypt passwords. Message digests, such as those used
in Example 6-4, provide exactly this kind of a one-way function. Computing a
message digest for a password is relatively easy, but going in the opposite
direction from digest to password is very difficult or impossible.
Design the PasswordManager class so that instead of storing the actual pass-
word, it stores only a message digest of the password. To verify a user's pass-
word, your class should compute a digest for the supplied password and
compare it to the stored digest. If the digests match, you can assume that the
passwords match also. (There is actually an infinitesimally small chance that
two different passwords will produce the same message digest, but you can
disregard this possibility.)
Search WWH ::




Custom Search