Search code examples
javablowfish

Encrypting in Java with BlowFish: result is too long


I must encrypt and decrypt using BlowFish the same secret using C, Perl and Java. While the C-pgm and the Perl give the same results, the resulting string in Java is too long. Here first encrypt and decrypt with a pgm written in C:

$ ./enc key Valentin
block: [Valentin]
0a2dc7c9bf82264d
$ ./dec key 0a2dc7c9bf82264d
Valentin

And now the same written in Java:

$ java -classpath . BlowFishTest key Valentin
length of pw: 8
length of crypted: 16
0a2dc7c9bf82264dd83df76a225413c1

Interestingly is that the first part of the result in Java contains the same hex values as from C, but is 16 bytes long.

The Java code is:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class BlowFishTest {

    public static void main(String[] args) throws Exception  {
    String key = args[0];
        String clear = args[1];

    encrypt(key, clear);
    }

    private static void encrypt(String key, String password) throws Exception {

    byte[] KeyData = key.getBytes("UTF-8");
    SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");
    Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, KS);

    byte[] pw = password.getBytes("UTF-8");
        System.out.println("length of pw: " + pw.length);

        byte[] crypted = cipher.doFinal(pw);
        System.out.println("length of crypted: " + crypted.length);
    StringBuilder sb = new StringBuilder();
        for (byte b : crypted) {
           sb.append(String.format("%02X", b));
        }
        System.out.println(sb.toString().toLowerCase());
    }

}

Solution

  • Using only Blowfish cipher Java implicitly means Blowfish/ECB/Pkcs5padding (this may be different depending on used framework). You should always specify cipher in form of algorithm/mode/padding. Blocksize is the cipher is 64 bit (8 bytes). So Java automatically adds one empty padding block.

    If you don't want to use any padding, you may specify Blowfish/ECB/NoPadding. I'd say you fortunately are encrypting data of a single block (8 bytes), try different lengths and you will see