Encryption with BlowFish in Java

StefanE picture StefanE · Mar 9, 2011 · Viewed 48.5k times · Source

Following code works fine for me to encrypt a string with the BlowFish encryption.

          // create a key generator based upon the Blowfish cipher
    KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");

    // create a key
    SecretKey secretkey = keygenerator.generateKey();

    // create a cipher based upon Blowfish
    Cipher cipher = Cipher.getInstance("Blowfish");

    // initialise cipher to with secret key
    cipher.init(Cipher.ENCRYPT_MODE, secretkey);

    // get the text to encrypt
    String inputText = "MyTextToEncrypt";

    // encrypt message
    byte[] encrypted = cipher.doFinal(inputText.getBytes());

If I want to define my own secret key, how do I do that?

Answer

Erik picture Erik · Mar 9, 2011
String Key = "Something";
byte[] KeyData = Key.getBytes();
SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, KS);