dongmi1872 2013-07-30 05:54
浏览 124

将IOS中的加密J​​SON数据发送到PHP进行解密

I have a function which requires me to send a encrypted JSON instance to a PHP server for validation. I have a problem trying to get the whole process up and running and messing my head to find out where the problem is.

-(void) sendData:(NSString*)theweb{  
        //preparing sample json        
        NSMutableDictionary * dict = [[NSMutableDictionary alloc]init];
        [dict setObject:@"test" forKey:@"example"];
        [dict setObject:@"1" forKey:@"p"];
        [dict setObject:@"yourPostMessage" forKey:@"test"];
        [dict setObject:@"isNotReal" forKey:@"this"];

        //json creation
        NSData* data2 = [JSONBuilder toJSON:dict];

        NSString * jsonstring = [[NSString alloc]initWithData:data2 encoding:NSUTF8StringEncoding];

        //creating a dummy sha256 hash for aes256 key.
        NSString * string3 = [self sha256HashFor:@"hello"];

        //trimming hash to 32 character key.
        string3 = [string3 substringToIndex:32];

        //encrypting data to aes256
        data2 = [data2 AES256EncryptWithKey:string3];

        NSString * b64= [data2 base64EncodedString];

        NSString *post = [NSString stringWithFormat:@"theRealData=%@",b64];
        NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];

        requestObj = nil;

        //NSMutableRequest
        requestObj = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:theweb]];

        NSString *postLength =  [NSString stringWithFormat:@"%d", [postData length]];

        [requestObj setValue:@"application/x-www-form-urlencoded;charset=charset=us-ascii" forHTTPHeaderField:@"Content-Type"];

        [requestObj setValue:postLength forHTTPHeaderField:@"Content-Length"];

        [requestObj setHTTPMethod:@"POST"];
        [requestObj setHTTPBody:postData];

        //calling a new NSURLConnection
        conn = nil;
        conn = [NSURLConnection connectionWithRequest:requestObj delegate:self];

        [conn start];        

}

The methods used in this function are as follows:

+(NSData*)toJSON :(NSMutableDictionary*)dictionary
{
    NSError* error = nil;
    id result = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error];
    if (error != nil) return nil;
    return result;
}

-(NSString*)sha256HashFor:(NSString*)input
{
    const char* str = [input UTF8String];
    unsigned char result[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(str, strlen(str), result);

    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2];
    for(int i = 0; i<CC_SHA256_DIGEST_LENGTH; i++)
    {
        [ret appendFormat:@"%02x",result[i]];
    }
    return ret;
}

- (NSData *)AES256EncryptWithKey:(NSString *)key {
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];

    //See the doc: For block ciphers, the output size will always be less than or
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                      keyPtr, kCCKeySizeAES256,
                                      NULL /* initialization vector (optional) */,
                                      [self bytes], dataLength, /* input */
                                      buffer, bufferSize, /* output */
                                      &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
    //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }

    free(buffer); //free the buffer;
    return nil;
    }

Here's the code on php:

function decrypt_data($data, $key) {
    //$padded_key = $key . str_repeat(chr(0x00), 16); // Argh!
    //var_dump($padded_key);

    var_dump(base64_decode($data,true));

    $result = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($data), 'ecb');


    var_dump($result);
    // Yetch - $result ends up being padded with 0x0b's (vertical tab).
    $result2 = rtrim($result, chr(0x0b));
    return $result2;
}

Here are my findings:

Output of Base64 string(Gotten on both sides):
    UalnWmRiMQv8z4mEm+6B3HFSbiDwWcK1LYPhk6jDq+DiwYzvxqoZuDnlJUAjWbX6sQepiL8fb8/JQ0NXhQocglIcJN759AbpVSsbiXmwL78=
Output of vardump on base64_decode on PHP side:
    BOOL(false)
Output of vardump on $result: none

Somehow I have this feeling that the problem lies with the encoding. Could someone guide me on this? I am at a loss.

  • 写回答

1条回答 默认 最新

  • dongxia5394 2018-12-16 19:29
    关注

    In your PHP code:

    $result = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($data), 'ecb');
    

    In your iOS code:

    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                      keyPtr, kCCKeySizeAES256,
                                      NULL /* initialization vector (optional) */,
                                      [self bytes], dataLength, /* input */
                                      buffer, bufferSize, /* output */
                                      &numBytesEncrypted);
    

    To be clear, kCCOptionPKCS7Padding is a CBC mode flag, not an ECB mode flag.

    I think there are two bugs here:

    1. You need to urlencode() (or equivalent) from iOS to prevent + from becoming a space character.
    2. You're encrypting CBC mode and decrypting ECB mode. This is going to give you incorrect data.

    You'll want to make the following changes to your algorithm:

    Encryption

    1. Generate a 16-byte random string, securely.
    2. Use this as the Initialization Vector (IV).
    3. After encrypting, calculate the HMAC-SHA256 of the IV and ciphertext.
    4. Include the IV and HMAC output in your message.

    Decryption

    1. Recalculate the HMAC-SHA256 of the IV and ciphertext you've received.
    2. Compare it with the HMAC given, using hash_equals(). If it fails, throw an exception.
    3. If step 2 passes, decrypt using AES-CBC mode (with the IV given).
    4. Use openssl instead of mcrypt.

    Alternatively, you may want to switch to NAChloride or Swift-Sodium for encryption and update PHP to 7.2+ and use the sodium_* functions for decryption.

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类