03 Dec 2009 @ 1:08 PM 

encrypting and decrypting between different languages and character sets can be painful. It took me many hours of tweaking to get to a working robust solution.

The PHP code will encrypt and decrypt a string.

The java code will successfully decrypt a string encrypted by the PHP code.

Encrypt and decrypt in PHP:

function encryptString($pin)
{
    $cipher = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, '');
    // The block-size of the Blowfish algorithm is 64-bits, therefore our IV
    // is always 8 bytes:
    $iv =  '12345678';
    $key = encryptKey(); //32chars = 256bit encryption
    // The strengh of the encryption is determined by the length of the key
    // passed to mcrypt_generic_init
    if (mcrypt_generic_init($cipher, $key, $iv) != -1)
    {
        $cipherText = mcrypt_generic($cipher, $pin);
        mcrypt_generic_deinit($cipher);
        return $cipherText;
    } else
    {
        mcrypt_generic_deinit($cipher);
        return "";
    }
}
 
function decryptString($pin)
{
    $iv =  '12345678';
    $key = encryptKey();
    return mcrypt_cbc(MCRYPT_BLOWFISH, $pin, $ciphertext, MCRYPT_DECRYPT, $iv);
}
 
function hex2bin($h)
{
    //this function is the opposite of php's bin2hex
    if (!is_string($h)) return null;
    $r='';
    for ($a=0; $a<strlen($h); $a+=2) { $r.=chr(hexdec($h{$a}.$h{($a+1)})); }
    return $r;
}
 
//usage:
$encrypted_string = encryptString('Some text to encrypt');
$decrypted_string = decryptString($encrypted_string);

To decrypt in JAVA

private static String decryptBlowfish(String to_decrypt)
{
    try
    {
        String iv = "12345678";
        byte[] IVBytes = getBytes(iv);
        if (IVBytes == null)
        {
            return null;
        }
        IvParameterSpec IV = new IvParameterSpec(IVBytes);
        String strkey = "12345678901234567890123456789012"; //must be the same key we used to encrypt the data
        byte[] strkeyBytes = getBytes(strkey);
        if (strkeyBytes == null)
        {
            return null;
        }
        SecretKeySpec key = new SecretKeySpec(strkeyBytes, "Blowfish");
        try
        {
            Cipher cipher = Cipher.getInstance("Blowfish/CBC/NoPadding");
            try
            {
                cipher.init(Cipher.DECRYPT_MODE, key, IV);
                try
                {
                    byte[] encrypted = getBytes(to_decrypt);
                    if (encrypted == null)
                    {
                        return null;
                    }
                    byte[] decrypted = cipher.doFinal(encrypted);
                    return new String(decrypted);
                } catch(Exception e)
                {
                    errorMsg = "ERROR: decryptBlowfish(dofinal) : to_decrypt :" + to_decrypt + " : message : " + e;
                    return null;
                }
            }catch (Exception e)
            {
                errorMsg = "ERROR: decryptBlowfish(init) :" + e;
                return null;
            }
        }catch (Exception e)
        {
            errorMsg = "ERROR: decryptBlowfish(getInstance) :" + e;
            return null;
        }
    } catch (Exception e)
    {
        errorMsg = "ERROR: decryptBlowfish :" + e;
        return null;
    }
}
 
private static String hexToString(String input, int groupLength)
{
    try
    {
        StringBuilder sb = new StringBuilder(input.length() / groupLength);
        for (int i = 0; i < input.length() - groupLength + 1; i += groupLength)
        {
            String hex = input.substring(i, i + groupLength);
            sb.append((char) Integer.parseInt(hex, 16));
        }
 
        return sb.toString();
    } catch (Exception e)
    {
        errorMsg = "ERROR: hexToString :" + e;
        return null;
    }
}
 
private static byte[] getBytes(String toGet)
{
    try
    {
        byte[] retVal = new byte[toGet.length()];
        for (int i = 0; i < toGet.length(); i++)
        {
            char anychar = toGet.charAt(i);
            retVal[i] = (byte)anychar;
        }
        return retVal;
    }catch(Exception e)
    {
        errorMsg = "ERROR: getBytes :" + e;
        return null;
    }
}
 
 
//USAGE
String stringSignature = hexToString(signature, 2);
String decryptSignature = decryptBlowfish(stringSignature);
Posted By: Zayin
Last Edit: 03 Dec 2009 @ 01:08 PM

EmailPermalink
Tags
Tags: , ,
Categories: java, php


 

Responses to this post » (11 Total)

 
  1. zayinkrige says:

    New Blog Post -> Blowfish encryption between PHP & Java – http://www.zayinkrige.com/blowfish-encry

  2. Jason says:

    Where is the encryptKey() function defined in the php code?

  3. Zayin says:

    ecnryptKey() is just a function that returns the key you use to encrypt your data with.

    here is a sample

    function encryptKey()
    {
    return ‘my 32char key that i use to enc’;
    }

  4. karyn says:

    Dear sir..

    I’m karyn and now I still do my school assigment about encryption message with blowfish in java(j2me).. please help me…I really need ur help

    thanks…

  5. adil says:

    String stringSignature = hexToString(signature, 2);
    in hexToString method what il be the value for signature??!!

  6. Zayin says:

    signature is the string you wish to decode

    eg : 68656c6c6f20776f726c64 = “hello world”

  7. adil says:

    Hi Zayin

    Thanks for the reply, i have a question

    when passing ” 68656c6c6f20776f726c64″ signature in hexToString(signature, 2);
    method it returns “hello world”

    but stringSignature have now “hello world ” and you are passing that in String decryptSignature = decryptBlowfish(stringSignature);

    how it is going to decrypt it is already decrypted by the hexToString(signature, 2); method ? how decryptBlowfish method will work for decryption? we have to pass it encrypted string

  8. adil says:

    and when i am encrypting “hello world” using php encryption code getting this T=ë¤ʁ¬z%ªÍ~A data, now how to decrypt this using your java code

  9. Zayin says:

    firstly convert it to hex – something like this – 543deba4131dca817fac7a25aacd7e41

    secondly, my hello world was probably a bad example, as you wouldnt send unencrypted text (like I did), but rather an encrypted string (like this 543deba4131dca817fac7a25aacd7e41)

    I hope this helps :)

  10. john says:

    where is your key here????
    mcrypt_cbc(MCRYPT_BLOWFISH, $pin, $ciphertext, MCRYPT_DECRYPT, $iv);

  11. Zayin says:

    $pin is the key

Post a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.


 Last 50 Posts
 Back
Change Theme...
  • Users » 1
  • Posts/Pages » 38
  • Comments » 61
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

Links



    No Child Pages.

Portfolio



    No Child Pages.