Search code examples
javac++encryptionblowfish

why am i seeing inconsistencies between two blowfish implementations?


I am encrypting "06.93308" using the key "rubicon" first with javax.crypto.spec.SecretKeySpec and another in C++ using openSSL. However both are giving me different encrypted values. The java version gives me hex A834BDD6C3478B8C whilst the OpenSSL gives me D06D7CB756744903 which is considerably different. The aim is to get the same result as the java equivalent. Any ideas on what i am doing wrong?

the java code is as follows:

char[] password = new char[] { 'r', 'u', 'b', 'i', 'c', 'o', 'n' };
byte[] raw = encrypt(password,"06.93308" );

    private static byte[] encrypt(char[] password, String plaintext) throws Exception {
            byte[] bytes = new byte[password.length];
            for (int i = 0; i < password.length; ++i) {
                    bytes[i] = (byte) password[i];
            }
            SecretKeySpec skeySpec = new SecretKeySpec(bytes, "Blowfish");
            Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(plaintext.getBytes());
            return encrypted;
    }

the c++ side is as follows:

   CBlowFish oBlowFish((byte *)"rubicon", 8);

   char encryptedPrice[17] = "\0\0\0\0\0\0\0\0";
   char myBidPrice[] = "06.93308";
   encrypt(myBidPrice,encryptedPrice);


    void encrypt(char bidPrice[],char encryptedPrice[])
    {
        oBlowFish.Encrypt((unsigned char*)bidPrice, (unsigned char*)encryptedPrice,8 );
    }

this is the openSSL code which gives me the same result as the above C++ code

#define SIZE 16

unsigned char *out = (unsigned char *)calloc(SIZE+1, sizeof(char));
BF_KEY *key = (BF_KEY *)calloc(1, sizeof(BF_KEY));
BF_set_key(key, SIZE, (const unsigned char*)"rubicon" );
BF_ecb_encrypt(in, out, key, BF_ENCRYPT);
printf("%s\n",out);

Solution

  • "rubicon" is not 16 bytes long. You'll have to adjust SIZE accordingly.