-2

Can anyone convert the below code to Objective-C?

Server has the code below implemented and I have to do the same thing on client side.

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;
        }
Gustav
  • 53,498
  • 7
  • 29
  • 55
Jay
  • 153
  • 2
  • 13
  • 2
    http://stackoverflow.com/q/8458917/528131 - May be a duplicate unless my crypto knowledge is insufficient – Machinarius Jun 26 '15 at 12:23
  • 1
    [SO Answer](http://stackoverflow.com/a/30389207/451475) for HmacSHA512 can be easily converted to HmacSHA256, just change all instances of 512 to 256. – zaph Jun 26 '15 at 12:27

1 Answers1

0

SO Answer for HmacSHA512 can be easily converted to HmacSHA256, just change all instances of 512 to 256 and add Base64 encoding:

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

Test:

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);

Output:

hamcData: <f1279694 14df8ed4 1865b99a 96a524d3 941d3773 35faf0d2 b3e7aaaa 6d135186>
base64HmacString: 8SeWlBTfjtQYZbmalqUk05QdN3M1+vDSs+eqqm0TUYY=
Community
  • 1
  • 1
zaph
  • 111,848
  • 21
  • 189
  • 228