Symmetric Encryption
71
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128); // need to initialize with the keysize
Key key = keyGenerator.generateKey();
System.out.println("Done generating the key.");
// Create a cipher using that key to initialize it
Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plaintext = text.getBytes("UTF8");
// Print out the bytes of the plaintext
System.out.println("\nPlaintext: ");
for (int i=0;i<plaintext.length;i++) {
System.out.print(plaintext[i]+" ");
}
// Perform the actual encryption
byte[] ciphertext = cipher.doFinal(plaintext);
// Print out the ciphertext
System.out.println("\n\nCiphertext: ");
for (int i=0;i<ciphertext.length;i++) {
System.out.print(ciphertext[i]+" ");
}
// Re-initialize the cipher to decrypt mode
cipher.init(Cipher.DECRYPT_MODE, key);
// Perform the decryption
byte[] decryptedText = cipher.doFinal(ciphertext);
String output = new String(decryptedText,"UTF8");
System.out.println("\n\nDecrypted text: "+output);
}
}
Of course, if you run this program, you'll see the following output:
Generating a Blowfish key...
Done generating the key.
Plaintext:
72 101 108 108 111 87 111 114 108 100 33
Ciphertext:
21 -74 -74 12 32 103 -72 -18 -19 -51 67 28 31 -91 -26 -104
Decrypted text: HelloWorld!
Now let's look at a different method of encryption.