Decrypting in Java with Blowfish

后端 未结 6 2006
独厮守ぢ
独厮守ぢ 2021-02-06 18:41

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 :

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-06 19:32

    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.

提交回复
热议问题