Search code examples
javaencryptionblowfishsecret-key

Blowfish file encryption without keygenerator


How do I encrypt my files without using the KeyGenerator using the Blowfish Algorithm?

here's part of my code

Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, key);
FileInputStream fis = new FileInputStream(plain);

FileOutputStream fos = new FileOutputStream(copy);
CipherOutputStream out2 = new CipherOutputStream(fos, cipher);
byte[] buffer = new byte[1024];
while (fis.read(buffer)>=0) {
    out2.write(buffer);
}

Solution

  • If you have a key you can provide it using the SecretKeySpec like this:

    byte[] key = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    SecretKey keySpec = new SecretKeySpec(key, "Blowfish");
    Cipher cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);