dsaob80228 2012-10-11 15:05
浏览 221
已采纳

iOS base64编码返回与php不同的结果

I'm building an iOS app making use of our own web service but am having some issues when base64 encoding data within iOS and trying to compare it with the same data encoded using PHP base64_encode() function.

iOS side:

/*
 * Generating a hash within an NSData object, which then I try to base64 encode
 *  making use of the Base64 library included with RestKit.
 */
const char *cKey  = [private_key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [password cStringUsingEncoding:NSASCIIStringEncoding];  
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];   
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);  
NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
NSString *myHash = [HMAC base64EncodedString];

PHP Side:

$hash = hash_hmac('sha256',$data,$key);
$encoded_hash = base64_encode($hash);

And the output looks like:

iOS HMAC: <3ae3bbed 508b62aa 9bd8e92e 357e1467 e888cd3d a1ad5aa2 7692db23 5415eb0d>
iOS myHash: OuO77VCLYqqb2OkuNX4UZ+iIzT2hrVqidpLbI1QV6w0=

PHP hash: 3ae3bbed508b62aa9bd8e92e357e1467e888cd3da1ad5aa27692db235415eb0d
PHP encoded_hash: M2FlM2JiZWQ1MDhiNjJhYTliZDhlOTJlMzU3ZTE0NjdlODg4Y2QzZGExYWQ1YWEyNzY5MmRiMjM1NDE1ZWIwZA==

As you can see, when comparing iOS' HMAC and PHP Hash they contain the same characters, but once you base64 encode this, the result is not the same.

  • 写回答

1条回答 默认 最新

  • doujindou4356 2012-10-11 15:27
    关注

    Your iOS one is correct.

    The PHP one is the string 3ae3bbed508b62aa9bd8e92e357e1467e888cd3da1ad5aa27692db235415eb0d base-64 encoded. i.e. the bit stream being encoded here is those ASCII characters. So the first 3 is 0x33, the a is 0x61, etc. So you're encoding 0x3361... actually. Does that make sense?

    For the PHP you want:

    $hash = hash_hmac('sha256',$data,$key,true);
    $encoded_hash = base64_encode($hash);
    

    That tells hash_hmac to return the raw output rather than a hex string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥15 this signal is connected to multiple drivers怎么解决
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus