Java Reference
In-Depth Information
Example 6−5: TripleDES.java (continued)
byte[] rawkey = keyspec.getKey();
// Write the raw key to the file
FileOutputStream out = new FileOutputStream(f);
out.write(rawkey);
out.close();
}
/** Read a TripleDES secret key from the specified file */
public static SecretKey readKey(File f)
throws IOException, NoSuchAlgorithmException,
InvalidKeyException, InvalidKeySpecException
{
// Read the raw bytes from the keyfile
DataInputStream in = new DataInputStream(new FileInputStream(f));
byte[] rawkey = new byte[(int)f.length()];
in.readFully(rawkey);
in.close();
// Convert the raw bytes to a secret key like this
DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
SecretKey key = keyfactory.generateSecret(keyspec);
return key;
}
/**
* Use the specified TripleDES key to encrypt bytes from the input stream
* and write them to the output stream. This method uses
* CipherOutputStream to perform the encryption and write bytes at the
* same time.
**/
public static void encrypt(SecretKey key, InputStream in, OutputStream out)
throws NoSuchAlgorithmException, InvalidKeyException,
NoSuchPaddingException, IOException
{
// Create and initialize the encryption engine
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, key);
// Create a special output stream to do the work for us
CipherOutputStream cos = new CipherOutputStream(out, cipher);
// Read from the input and write to the encrypting output stream
byte[] buffer = new byte[2048];
int bytesRead;
while((bytesRead = in.read(buffer)) != -1) {
cos.write(buffer, 0, bytesRead);
}
cos.close();
// For extra security, don't leave any plaintext hanging around memory.
java.util.Arrays.fill(buffer, (byte) 0);
}
/**
* Use the specified TripleDES key to decrypt bytes ready from the input
* stream and write them to the output stream. This method uses
Search WWH ::




Custom Search