EXERCISE – 7
Using Java Cryptography, encrypt the text “Hello world” using Blowfish. Create your own key using Java keytool.
Step 1: Generate Blowfish Secret Key
Open Command Prompt and move to your working directory (Example: Desktop):
cd Desktop
Now execute the following command:
keytool -genseckey -alias blowfishKey -keyalg Blowfish -keysize 128 -storetype JCEKS -keystore blowfish.jceks -storepass 123456 -keypass 123456
Explanation:
- -genseckey
→ Generates a secret key - -alias blowfishKey
→ Name of the key - -keyalg Blowfish
→ Algorithm name - -keysize 128
→ 128-bit key - -storetype JCEKS
→ Required to store secret keys - -keystore blowfish.jceks
→ File name of keystore - -storepass 123456
→ Keystore password - -keypass 123456
→ Key password
After running this command, a file named blowfish.jceks will be created in your folder. This file stores the secret key securely.
Step 2: Create Java Program
Create a new Java file named:
BlowfishEncrypt.java
Paste the following code inside the file:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Base64;
public class BlowfishEncrypt {
public static void main(String[] args) {
try {
String text = "Hello world";
// Load the keystore
KeyStore ks = KeyStore.getInstance("JCEKS");
FileInputStream fis = new FileInputStream("blowfish.jceks");
ks.load(fis, "123456".toCharArray());
// Retrieve the secret key
SecretKey key = (SecretKey) ks.getKey("blowfishKey", "123456".toCharArray());
// Create cipher object
Cipher cipher = Cipher.getInstance("Blowfish");
// Initialize cipher for encryption
cipher.init(Cipher.ENCRYPT_MODE, key);
// Encrypt the text
byte[] encrypted = cipher.doFinal(text.getBytes("UTF-8"));
// Convert encrypted bytes to Base64 string
String encryptedText = Base64.getEncoder().encodeToString(encrypted);
System.out.println("Original Text : " + text);
System.out.println("Encrypted Text : " + encryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step 3: Compile the Program
javac BlowfishEncrypt.java
If no errors appear, the program compiled successfully.
Step 4: Run the Program
java BlowfishEncrypt
Sample Output:
Original Text : Hello world Encrypted Text : qK8Jz5hM3V4kLw==
Note: The encrypted text will be different on each system depending on the generated key.
Result
- Blowfish secret key generated successfully
- Text encrypted using Blowfish algorithm
- Encrypted output displayed in Base64 format