将C#HMACSHA256转换为Objective-C

时间:2015-06-26 12:19:58

标签: ios objective-c iphone

任何人都可以将以下代码转换为Objective-C吗?

服务器已经实现了以下代码,我必须在客户端执行相同的操作。

private string Signature()
        {
            string publicKey    = PUBLICKEY;
            string secretKey    = PRIVATEKEY;
            string email        = YOUREMAIL;

            if (String.IsNullOrWhiteSpace(secretKey) || String.IsNullOrWhiteSpace(publicKey))
                return "";

            string signature;
            var secretBytes = Encoding.UTF8.GetBytes(secretKey);
            var valueBytes = Encoding.UTF8.GetBytes(publicKey);

            using (var hmac = new HMACSHA256(secretBytes))
            {
                var hash = hmac.ComputeHash(valueBytes);
                signature = Convert.ToBase64String(hash);
            }

            string authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(email + ":" + signature));

            return authInfo;
        }

1 个答案:

答案 0 :(得分:0)

HpcSHA512的

SO Answer可以很容易地转换为HmacSHA256,只需将512的所有实例更改为256并添加Base64编码:

+ (NSData *)doHmacSha256:(NSData *)dataIn
                     key:(NSData *)key
{
    NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];

    CCHmac( kCCHmacAlgSHA256,
            key.bytes,
            key.length,
            dataIn.bytes,
            dataIn.length,
            macOut.mutableBytes);

    return macOut;
}

测试:

NSData *keyData  = [@"MyTestKey" dataUsingEncoding:NSASCIIStringEncoding];
NSData *data     = [@"Now is the time for all good computers to come to the aid of their masters." dataUsingEncoding:NSASCIIStringEncoding];
NSData *hamcData = [Test doHmacSha256:data key:keyData]; // Where "Test" is the class "doHmacSha256" is defined in.
NSLog(@"hamcData: %@", hamcData);

NSString *base64HmacString = [hamcData base64EncodedStringWithOptions:0];
NSLog(@"base64HmacString: %@", base64HmacString);

输出:

hamcData: <f1279694 14df8ed4 1865b99a 96a524d3 941d3773 35faf0d2 b3e7aaaa 6d135186>
base64HmacString: 8SeWlBTfjtQYZbmalqUk05QdN3M1+vDSs+eqqm0TUYY=