3

我有一个函数要求我将加密的 JSON 实例发送到 PHP 服务器进行验证。我在尝试启动并运行整个过程并弄乱我的脑袋以找出问题所在时遇到了问题。

-(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];        

}

该函数中使用的方法如下:

+(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;
    }

这是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;
}

以下是我的发现:

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

不知何故,我觉得问题出在编码上。有人可以指导我吗?我很茫然。

4

1 回答 1

1

在您的 PHP 代码中:

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

在您的 iOS 代码中:

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

需要明确的是,kCCOptionPKCS7Padding是 CBC 模式标志,而不是 ECB 模式标志。

我认为这里有两个错误:

  1. 您需要urlencode()(或等效的)来自 iOS 以防止+成为空格字符。
  2. 您正在加密 CBC 模式和解密 ECB 模式。这会给你不正确的数据。

您需要对算法进行以下更改:

加密

  1. 安全地生成一个 16 字节的随机字符串。
  2. 将其用作初始化向量 (IV)。
  3. 加密后计算IV和密文的HMAC-SHA256。
  4. 在您的消息中包含 IV 和 HMAC 输出。

解密

  1. 重新计算您收到的 IV 和密文的 HMAC-SHA256。
  2. 将其与给出的 HMAC 进行比较,使用hash_equals(). 如果失败,则抛出异常。
  3. 如果第 2 步通过,则使用 AES-CBC 模式解密(给出 IV)。
  4. 使用 openssl 而不是 mcrypt

或者,您可能希望切换到NChlorideSwift-Sodium进行加密并将 PHP 更新到 7.2+ 并使用这些sodium_*函数进行解密。

于 2018-12-16T19:29:49.793 回答