1. Kayako Download customers: we will continue to develop and support Kayako Download beyond July 2017, alongside the new Kayako for existing customers.

    Find out more.

  2. The forum you are viewing relates to Kayako Classic. If you signed up or upgraded to the new Kayako (after the 4th July 2016), the information in this thread may not apply to you. You can visit the forums for the new Kayako here.

Cocoa (iOS & Mac) Methods for Generating a Salt and Signature

Discussion in 'Developing, APIs and extending' started by Pete Johnson, Jul 7, 2011.

  1. Pete Johnson

    Pete Johnson New Member

    In case anyone is interested, here are 2 Cocoa methods - one creates a Salt and the other creates a Signature based on a salt.

    Code:
    -(NSUInteger)GenerateSalt
    {
        // random number (change the modulus to the length you'd like)
        NSUInteger r = arc4random() % 100000;
        return r;
    }
    
    -(NSString *)GenerateSignatureUsingSalt:(NSUInteger)salt
    {
        /*
         Make sure you import:
         #import <CommonCrypto/CommonHMAC.h>
         */
    
        NSString *key = SECRET_KEY;                                        // define your Secret Key string
        NSString *data = [NSString stringWithFormat:@"%u", salt];        // convert your random number
    
        const char *cKey  = [key cStringUsingEncoding:NSUTF8StringEncoding];
        const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding];
    
        unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
    
        // Hash the salt with the secret key
        CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    
        // Create a data structure
        NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
                                              length:sizeof(cHMAC)];
    
        // Base64 Encode the signature
        NSString *hash = [HMAC base64Encoding];
    
        // create a valid URL
        NSString * signatureURL = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                       (CFStringRef)hash,
                                                                                       NULL,
                                                                                       (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                                                       kCFStringEncodingUTF8 );
    
    
        return signatureURL;
    
    }
    
     
    Jamie Edwards likes this.
  2. Jamie Edwards

    Jamie Edwards Staff Member

    Fantastic, thank you for sharing these. Do you mind if I put them on our Wiki?
     
  3. Pete Johnson

    Pete Johnson New Member

    No problem.
     

Share This Page