Java Reference
In-Depth Information
Example 6−5: TripleDES.java (continued)
// Check to see whether there is a provider that can do TripleDES
// encryption. If not, explicitly install the SunJCE provider.
try { Cipher c = Cipher.getInstance("DESede"); }
catch(Exception e) {
// An exception here probably means the JCE provider hasn't
// been permanently installed on this system by listing it
// in the $JAVA_HOME/jre/lib/security/java.security file.
// Therefore, we have to install the JCE provider explicitly.
System.err.println("Installing SunJCE provider.");
Provider sunjce = new com.sun.crypto.provider.SunJCE();
Security.addProvider(sunjce);
}
// This is where we'll read the key from or write it to
File keyfile = new File(args[1]);
// Now check the first arg to see what we're going to do
if (args[0].equals("-g")) { // Generate a key
System.out.print("Generating key. This may take some time...");
System.out.flush();
SecretKey key = generateKey();
writeKey(key, keyfile);
System.out.println("done.");
System.out.println("Secret key written to " + args[1] +
". Protect that file carefully!");
}
else if (args[0].equals("-e")) { // Encrypt stdin to stdout
SecretKey key = readKey(keyfile);
encrypt(key, System.in, System.out);
}
else if (args[0].equals("-d")) { // Decrypt stdin to stdout
SecretKey key = readKey(keyfile);
decrypt(key, System.in, System.out);
}
}
catch(Exception e) {
System.err.println(e);
System.err.println("Usage: java " + TripleDES.class.getName() +
" -d|-e|-g <keyfile>");
}
}
/** Generate a secret TripleDES encryption/decryption key */
public static SecretKey generateKey() throws NoSuchAlgorithmException {
// Get a key generator for Triple DES (a.k.a. DESede)
KeyGenerator keygen = KeyGenerator.getInstance("DESede");
// Use it to generate a key
return keygen.generateKey();
}
/** Save the specified TripleDES SecretKey to the specified file */
public static void writeKey(SecretKey key, File f)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException
{
// Convert the secret key to an array of bytes like this
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
DESedeKeySpec keyspec =
(DESedeKeySpec)keyfactory.getKeySpec(key, DESedeKeySpec.class);
Search WWH ::




Custom Search