2

我的应用程序和服务器之间存在通信问题。我正在使用 RNCryptor 加密一条消息,然后我将其 base64 编码并在请求中传输到服务器。这是在 DATA 标头和 http 正文中作为发布数据完成的。我认为我在如何通过 POST 转换和传输 base64 编码消息时犯了一个错误。

如果我通过标头收到加密消息,它每次都能完美解密。但是,如果我通过 POST 数据接收消息,我会得到不同的结果。大多数情况下,它会失败,否则它会部分解密(前几个字母),大约 20 次成功解密中有 1 次。

目标c代码是:

- (NSString *)sendEncryptedTestMessage:(NSString *)address{
    NSString* messageContent    = @"Hello my name is Bob.";
    NSError * error             = nil;
    NSString* responseString2   = nil;

    NSData*   postData = [RNEncryptor encryptData:[messageContent dataUsingEncoding:NSUTF8StringEncoding]
                                    withSettings:kRNCryptorAES256Settings
                                        password:@"123456"
                                           error:&error];

    NSString* messageServer     = [NSString base64forData:postData];
    NSString* postMessage       = [@"message=" stringByAppendingString:messageServer];
              postData          = [postMessage dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; // problem here I think

    NSString* postLength        = [NSString stringWithFormat:@"%ld",(unsigned long)[postData length]];

    NSURL*    URLToRequest      = [NSURL URLWithString:address];

    NSMutableURLRequest* semisystem = [[[NSMutableURLRequest alloc] initWithURL:URLToRequest] autorelease];

    [semisystem setHTTPMethod:@"POST"];

    [semisystem setHTTPBody:postData];
    [semisystem setValue:postLength                           forHTTPHeaderField:@"Content-Length"];
    [semisystem setValue:self.activationURL                   forHTTPHeaderField:@"EncryptionKey"];
    [semisystem setValue:messageServer                        forHTTPHeaderField:@"data"];

    NSURLResponse* response;
    NSData* data = [NSURLConnection sendSynchronousRequest:semisystem
                                         returningResponse:&response
                                                     error:&error];

    responseString2 = [NSString stringWithFormat:@"%.*s", (int)[data length], [data bytes]];
    return responseString2;
}

PHP代码:

function decrypt2($b64_data,$password)
    {
           // back to binary
            //$bin_data = mb_convert_encoding($b64_data, "UTF-8", "BASE64");
            $bin_data = base64_decode($b64_data);
            // extract salt
            $salt = substr($bin_data, 2, 8);
            // extract HMAC salt
            $hmac_salt = substr($bin_data, 10, 8);
            // extract IV
            $iv = substr($bin_data, 18, 16);
            // extract data
            $data = substr($bin_data, 34, strlen($bin_data) - 34 - 32);
            $dataWithoutHMAC = chr(2).chr(1).$salt.$hmac_salt.$iv.$data;
            // extract HMAC
            $hmac = substr($bin_data, strlen($bin_data) - 32);
            // make HMAC key
            $hmac_key = pbkdf2('SHA1', $password, $hmac_salt, 10000, 32, true);
            // make HMAC hash
            $hmac_hash = hash_hmac('sha256', $dataWithoutHMAC , $hmac_key, true);
            // check if HMAC hash matches HMAC
            if($hmac_hash != $hmac) {
                echo "HMAC mismatch".$nl.$nl.$nl;
               // return false;
            }
            // make data key
            $key = pbkdf2('SHA1', $password, $salt, 10000, 32, true);
            // decrypt
            $ret = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);      
        return $ret;
    }
$passkey = "123456";

$messageBase64                  = $_POST['message'];// THIS barely works
$messageBase64              = $_SERVER['HTTP_DATA'];// THIS WORKS
$message                = decrypt2($messageBase64,$passkey);

提前谢谢了!

4

3 回答 3

3

我知道这是一个老问题,但是很长一段时间我都使用相同的解决方案,问题是我们在向服务器发出请求之前没有正确编码 url。文档说:

  According to RFC 3986, the reserved characters in a URL are:
  reserved    = gen-delims / sub-delims
  gen-delims  = ":" / "/" / "?" / "#" / "[" / "]" / "@"
  sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
              / "*" / "+" / "," / ";" / "="

这里是如何编码字符串:/

CFStringRef encodedString =
    CFURLCreateStringByAddingPercentEscapes(
    kCFAllocatorDefault,
    (__bridge CFStringRef)(originalString),
    NULL,
    CFSTR(":/?#[]@!$&'()*+,;="),kCFStringEncodingUTF8);

并再次获取字符串:

    NSString* stringEncoded = CFBridgingRelease
   (CFURLCreateWithString(kCFAllocatorDefault, encodedString, NULL));

我认为这是我们能做的最好的事情,因为我们确保字符串将被正确编码,并且在请求期间符号不会被其他东西替换。这里是参考:

http://developer.apple.com/library/ios/#documentation/CoreFoundation/Reference/CFURLRef/Reference/reference.html#//apple_ref/c/func/CFURLCreateStringByAddingPercentEscapes

http://developer.apple.com/library/ios/#documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/WorkingWithHTTPAndHTTPSRequests/WorkingWithHTTPAndHTTPSRequests.html

于 2013-07-12T23:11:07.487 回答
2

我刚刚找到了解决方案。在请求期间,“+”符号被服务器解释为空格,从而破坏了 base64 代码。以下行解决了这个问题:

postMessage       = [postMessage stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
于 2013-02-12T21:30:46.517 回答
-1

您可以在此网址中检查您的编码/解码字符串

http://meyerweb.com/eric/tools/dencoder/

当您按下编码按钮时,您可以看到“+”更改为“%2B”。

于 2014-02-07T17:38:31.933 回答