//
//  NSString+SHA1Base64.m
//  VisIVOMobile
//
//  Created by Costantino Pistagna on 11/04/12.
//  Copyright (c) 2012 iPhoneSmartApps.org. All rights reserved.
//

#import "NSString+SHA1Base64.h"
#import <CommonCrypto/CommonHMAC.h>


@implementation NSString (SHA1Base64)

#pragma mark -
#pragma mark Calculate SHA1 Base 64
- (unsigned char *)sha1 {
    unsigned char *result = calloc(1, (CC_SHA1_DIGEST_LENGTH+1)*sizeof(unsigned char));

    char *c_baseString=(char *)[self UTF8String];
    CC_SHA1(c_baseString, strlen(c_baseString), result);
    return result;
}

- (unsigned char *)sha1:(NSString *)baseString result:(unsigned char *)result {
    char *c_baseString=(char *)[baseString UTF8String];
    CC_SHA1(c_baseString, strlen(c_baseString), result);
    return result;
}

- (NSString *)base64:(unsigned char *)result {
    NSString *passwd=[[NSString alloc] init];
    static const unsigned char cb64[65]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for (int i=0; i<CC_SHA1_DIGEST_LENGTH; i+=3) {
        passwd=[passwd stringByAppendingFormat:@"%c%c%c%c",
                cb64[(result[i] &0xFC)>>2],
                cb64[((result[i] & 0x03) << 4)
                     | ((result[i + 1] & 0xF0) >> 4)],
                cb64[((result[i + 1] & 0x0F) << 2)
                     | ((result[i + 2] & 0xC0) >> 6)],
                cb64[result[i+2]&0x3F]
                ];            
    }
    return passwd;
}

- (NSString *)hexadecimalRepresentation:(unsigned char *)result {
    NSString *passwd=[[NSString alloc] init];
    for (int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        passwd=[passwd stringByAppendingFormat:@"%02x", result[i]];
    }
    return passwd;
}

- (NSString *)B64SHA1 {
    unsigned char *result = [self sha1];
    NSString *retString = [self base64:result];
    free(result);
    return retString;
}

- (NSString *)HexSHA1 {
    unsigned char *result = [self sha1];
    NSString *retString = [self hexadecimalRepresentation:result];
    free(result);
    return retString;
}

- (NSString *)B64SHA1URLEncoded {
    unsigned char *result = [self sha1];
    NSString *retString = [self base64:result];
    free(result);
    NSString *retString2 = [retString substringToIndex:[retString length]-2];
    NSString *retString3 = [retString2 stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
    return retString3;
}

@end
