OneCompiler

blowfish own

94

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class BlowfishEncryption {

public static void main(String[] args) throws Exception {
    String text = "Hello world";

    // 1. Create your own secret key (must be 4 to 56 bytes for Blowfish)
    String myKey = "mySecretKey"; // You can change this!
    byte[] keyData = myKey.getBytes();
    SecretKey secretKey = new SecretKeySpec(keyData, "Blowfish");

    // 2. Initialize Cipher
    Cipher cipher = Cipher.getInstance("Blowfish");

    // 3. Encrypt
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    byte[] encrypted = cipher.doFinal(text.getBytes());
    String encryptedText = Base64.getEncoder().encodeToString(encrypted);

    // 4. Decrypt
    cipher.init(Cipher.DECRYPT_MODE, secretKey);
    byte[] decrypted = cipher.doFinal(encrypted);
    String decryptedText = new String(decrypted);

    // 5. Output
    System.out.println("Original Text : " + text);
    System.out.println("Encrypted Text: " + encryptedText);
    System.out.println("Decrypted Text: " + decryptedText);
}

}