javacryptographyencryptionblowfish

Decrypting in Java with Blowfish


Hullo,

I am encrypting and decrypting in Java with Blowfish.

The encryption works fine, but the decryption fails.

Here is my Java code for decrypting :

String encryptedString = … ;
String decryptedString = null;
SecretKeySpec key = new SecretKeySpec(myKey.getBytes(), "Blowfish");
Cipher cipher;
try {
    cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decrypted = cipher.doFinal(encryptedString.getBytes());
    decryptedString = new String(decrypted, Charset.forName("UTF-8"));
} [ catch Exceptions … ]

I get an exception :

Exception. javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher

Can you tell me how to make this simply work ? Thank you.

The input I give comes from my encryption Java code, + encoding in Base64, and I decode it from Base64 just before giving it to this decrypting operation.


Solution

  • Now I have the solution !

    First, there were some problems with Unicode, so I have put ISO-8859-1 everywhere. Including in the Base64 encoding and decoding.

    Then, I have juggled with the variants.

    Here is my Java code which works for Blowfish decryption :

    String encryptedString = … ;
    String decryptedString = null;
    SecretKeySpec key = new SecretKeySpec(myKey.getBytes(CHARSET_ISO_8859_1), "Blowfish");
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decrypted = cipher.doFinal(encryptedString.getBytes(CHARSET_ISO_8859_1));
        decryptedString = new String(decrypted, CHARSET_ISO_8859_1);
    } [ catch Exceptions … ]
    

    Note that I have replaced "Blowfish" with "Blowfish/ECB/PKCS5Padding" for getting the Cipher instance, but, if you do the same for the key, it fails.

    The key myKey has to be a Latin-1 string of 8 characters. This makes a key of 128 bits. The Blowfish algorithm allows bigger keys, but they fail in Java because of the USA export restriction in the JRE — the USA allow encryption but not stronger than what the NSA can break.

    The CHARSET_ISO_8859_1 is a constant defined like this :

    final Charset CHARSET_ISO_8859_1 = Charset.forName("ISO-8859-1");
    

    And Charset is java.nio.charset.Charset.

    Last but not least, I have changed my encryption Java code accordingly.