3

I rewrite an C program with MCRYPT in Java / Scala, but I get different decoded strings for Java and C.

What am I doing wrong?

char * decode(char *string) {
    MCRYPT mcrypt_blowfish;
    mcrypt_blowfish = mcrypt_module_open("blowfish-compat", NULL, "ecb", NULL);
    unsigned char hardKey[] = { 0xEF, 0x3A, 0xB2, 0x9C, 0xD1, 0x9F, 0x0C, 0xAC, 0x57, 0x59, 0xC7, 0xAB, 0xD1, 0x2C, 0xC9, 0x2B, 0xA3, 0xFE, 0x0A, 0xFE, 0xBF, 0x96, 0x0D, 0x63, 0xFE, 0xBD, 0x0F, 0x45};
    mcrypt_generic_init(mcrypt_blowfish, hardKey, 28, NULL);
    mdecrypt_generic(mcrypt_blowfish, string, 512);
    mcrypt_generic_deinit(mcrypt_blowfish);
    mcrypt_module_close(mcrypt_blowfish);
    string[512] = 0;

    return string;
}

Scala Code

def decode (string: String ): String = {

    val keyBytes: Array[Char] = Array[Char](0xEF, 0x3A, 0xB2, 0x9C, 0xD1, 0x9F, 0x0C, 0xAC, 0x57, 0x59, 0xC7, 0xAB, 0xD1, 0x2C, 0xC9, 0x2B,0xA3, 0xFE, 0x0A, 0xFE, 0xBF, 0x96, 0x0D, 0x63,0xFE, 0xBD, 0x0F, 0x45)

    val cipher: Cipher = Cipher.getInstance("Blowfish/ECB/NoPadding")
    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(new String (keyBytes).getBytes, "Blowfish"))

    new String(cipher.doFinal(string.getBytes.reverse))
}
  • 2
    Not sure if it will help, but maybe try declaring `keyBytes` as `Array[Byte]`, (since `Char` in Java/Scala is a 2-byte unicode character) and pass it directly in `new SecretKeySpec(...)`. For values bigger than 0x7F you may need to cast it to byte: `0x80.toByte`, since all numbers are signed on JVM. – adamwy Jan 20 '17 at 09:59
  • Converting a key from `byte[]` to `String` and vice versa: http://stackoverflow.com/questions/5355466/converting-secret-key-into-a-string-and-vice-versa – Klas Lindbäck Jan 20 '17 at 10:05
  • Blowfish is no longer considered secure, it is superseded by AES. Blowfish should not be used in new work and updated when possible in old work. Even the author of Blowfish and TwoFish uses AES. – zaph Jan 20 '17 at 12:32

0 Answers0