Search code examples
phpiosobjective-ccryptographyblowfish

Random generated PHP IV is not working perfectly in IOS


The problem is the base 64 encoded iv(in PHP) doesn't match when decoded in IOS

The scenario is I am using Blowfish Algorithm CBC mode . Simply server(PHP) generate a random cryptographic IV and encoded base64 format , send to IOS . The Problem is here when-time I try to decode , the decoded results are not correct always . Sometime it generates correct and rest of time error.

Here is my PHP code.

public function ivGenerator()
{
    $ivSize = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
    echo base64_encode($iv);

}

Here is two result set of ivGenerator which i will use later for decoding

bTpkpLxMbNo=
aIvJeujxW7w=

Here is my IOS code .

NSString *ecodedIVString = @"bTpkpLxMbNo=";    
NSData *ecodedIVData= [[NSData alloc] initWithBase64EncodedString:ecodedIVString options:0];
NSString *decodeIVString = [[NSString alloc] initWithData:ecodedIVData encoding:NSASCIIStringEncoding];
NSLog(@"decodeIVString  %@" , decodeIVString); // m:d¤¼LlÚ   //its correct 

If I use ,

NSString *ecodedIVString = @"aIvJeujxW7w="; 

Then the result is hÉzèñ[¼ , but the actual result should be h‹Ézèñ[¼

I have tried

  NSWindowsCP1252StringEncoding , NSISOLatin1StringEncoding ,      NSUTF8StringEncoding 

But all of them are unable to generate accurate result (approx. 10 test I have found it).

Thanks in advance !


Solution

  • You should print out the result in hexadecimals and then perform a comparison.

    It seems that the encoding on both platforms is the same (something you should not take for granted) so you get the same characters back. However, it isn't sure that the font or font version you are using shows the characters. It could also be that one platform shows an character for unknown encoding sequences, and the other doesn't show anything at all.

    This brings us to the basic issue: if you decode random byte values then you may encounter byte sequences that do not translate to a character. So comparing binary strings by converting them to a printable string is no good. Instead you need to directly compare the bytes (e.g. by saving the IV to iv.bin files) or by translating them into hexadecimals.

    It's extremely likely that the IV's are identical, despite the fact that the printout is different.