Friday, 6 April 2012

HMac with SHA256

+(NSString*)getHMAC_SHA256WithBase64Encoding:(NSString*)stringToSign
{
    NSString *key = kSecrectKey;
    NSString *data = stringToSign;
   
    const char *cKey  = [key cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cData = [stringToSign cStringUsingEncoding:NSUTF8StringEncoding];
   
    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
   
    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
   
    //1
//    const unsigned int hex_len = CC_SHA256_DIGEST_LENGTH*2+2;
//        char hex[hex_len];
//        for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
//            snprintf(&hex[i*2], hex_len-i*2, "%02x", cHMAC[i]);
//        }
//    NSData *HMAC = [[NSData alloc] initWithBytes:hex length:strlen(hex)];
//    NSString *hash = [Base64 encode:HMAC];
   
   
    //2.
    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
    NSString *hash = [HMAC base64Encoding];
   
   
   
    //3.
//    NSString *hash;
//   
//    NSMutableString* output = [NSMutableString   stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
//   
//    for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
//        [output appendFormat:@"%02x", cHMAC[i]];
//    hash = output;
//   
   
    //4. amazaon
//    CCHmacContext context;
//    const char    *keyCString = [key cStringUsingEncoding:NSASCIIStringEncoding];
//    NSData *d = [data dataUsingEncoding:NSASCIIStringEncoding];
//    CCHmacInit(&context, kCCHmacAlgSHA256, keyCString, strlen(keyCString));
//    CCHmacUpdate(&context, [d bytes], [d length]);
//   
//    // Both SHA1 and SHA256 will fit in here
//    unsigned char digestRaw[CC_SHA256_DIGEST_LENGTH];
//    int digestLength = CC_SHA256_DIGEST_LENGTH;   
//    CCHmacFinal(&context, digestRaw);
//   
//    NSData *digestData = [NSData dataWithBytes:digestRaw length:digestLength];
//   
//   NSString *hash = [digestData base64Encoding];

    //5. amazon
//    CCHmacContext context;
//    const char    *keyCString = [key cStringUsingEncoding:NSASCIIStringEncoding];
//    NSData *d = [data dataUsingEncoding:NSASCIIStringEncoding];
//    CCHmacInit(&context, kCCHmacAlgSHA256, keyCString, strlen(keyCString));
//    CCHmacUpdate(&context, [d bytes], [d length]);
//   
//    unsigned char digestRaw[CC_SHA256_DIGEST_LENGTH];
//    int           digestLength = CC_SHA256_DIGEST_LENGTH;
//   
//    CCHmacFinal(&context, digestRaw);
//   
//    NSData *HMAC = [[NSData alloc] initWithBytes:digestRaw length:digestLength];
//    NSString *hash = [HMAC base64Encoding];
   
   
    //6.
//    const unsigned int blockSize = CC_SHA256_BLOCK_BYTES;
//    char ipad[blockSize], opad[blockSize], keypad[blockSize];
//    unsigned int keyLen = strlen(cKey);
//    CC_SHA256_CTX ctxt;
//    if(keyLen > blockSize) {
//       
//        CC_SHA256_Init(&ctxt);
//        CC_SHA256_Update(&ctxt, cKey, keyLen);
//        CC_SHA256_Final((unsigned char *)keypad, &ctxt);
//        keyLen = CC_SHA256_DIGEST_LENGTH;
//    } else {
//        memcpy(keypad, cKey, keyLen);
//    }
//    memset(ipad, 0x36, blockSize);
//    memset(opad, 0x5c, blockSize);
//   
//    int i;
//    for(i = 0; i < keyLen; i++) {
//        ipad[i] ^= keypad[i];
//        opad[i] ^= keypad[i];
//    }
//   
//    CC_SHA256_Init(&ctxt);
//    CC_SHA256_Update(&ctxt, ipad, blockSize);
//    CC_SHA256_Update(&ctxt, cData, strlen(cData));
//    unsigned char sha256[CC_SHA256_DIGEST_LENGTH];
//    CC_SHA256_Final(sha256, &ctxt);
//   
//    CC_SHA256_Init(&ctxt);
//    CC_SHA256_Update(&ctxt, opad, blockSize);
//    CC_SHA256_Update(&ctxt, sha256, CC_SHA256_DIGEST_LENGTH);
//    CC_SHA256_Final(sha256, &ctxt);
//   
//    const unsigned int hex_len = CC_SHA256_DIGEST_LENGTH*2+2;
//    char hex[hex_len];
//    for(i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
//        snprintf(&hex[i*2], hex_len-i*2, "%02x", sha256[i]);
//    }
//   
//    NSData *HMAC = [[NSData alloc] initWithBytes:hex length:strlen(hex)];
//    NSString *hash = [Base64 encode:HMAC];
//    [HMAC release];
   
    return hash;
   
}

Wednesday, 7 March 2012

Read the asset from the Library and get decompres

In the above post the size of the asset file is too big so here is another way to decompress the file
This is also taken from the stack over flow,

http://stackoverflow.com/questions/5687341/iphoneprogrammatically-compressing-recorded-video-to-share



- (void)convertVideoToLowQuailtyWithInputURL:(NSURL*)inputURL 
                                   outputURL:(NSURL*)outputURL 
                                     handler:(void (^)(AVAssetExportSession*))handler
{
    [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetLowQuality];
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeQuickTimeMovie;
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void
     {
         handler(exportSession);
         [exportSession release];
     }];
}

Export movie/image asset file into the disk


This is taken from the stack overflow and slightly modified 

- (BOOL) exportDataToURL: (NSString*) filePath error: (NSError**) error andAsset:(ALAsset*)asset
{
    NSError **errorInternal = nil;
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    if (!handle) {
        return NO;
    }
    
    static const NSUInteger BufferSize = 1024*1024;

    ALAssetRepresentation *rep = [asset defaultRepresentation];
    uint8_t *buffer = calloc(BufferSize, sizeof(*buffer));
    NSUInteger offset = 0, bytesRead = 0;
    
    do {
        @try {
            bytesRead = [rep getBytes:buffer fromOffset:offset length:BufferSize error:error];
            [handle writeData:[NSData dataWithBytesNoCopy:buffer length:bytesRead freeWhenDone:NO]];
            offset += bytesRead;
        } @catch (NSException *exception) {
            free(buffer);
            
            return NO;
        }
    } while (bytesRead > 0);
    
    free(buffer);
    return YES;
}

Read the file from assets-library and write into ur custom file


Although u can see many same solutions available same as given below...

This method take the Asset and fileName to create that file into the tempdirectory. 
It returns the path of the tempdirectory/file where it stores the 


This is the same as reading a file from the Assets library (Photo library). 


-(NSString*) writeVideoFileIntoTemp:(NSString*)fileName andAsset:(ALAsset*)asset
{
    NSString * tmpfile = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];

        
        ALAssetRepresentation * rep = [asset defaultRepresentation];
        
        NSUInteger size = [rep size];
        const int bufferSize = 1024*1024; // or use 8192 size as read from other posts 
        
        NSLog(@"Writing to %@",tmpfile);
        FILE* f = fopen([tmpfile cStringUsingEncoding:1], "wb+");
        if (f == NULL) {
            NSLog(@"Can not create tmp file.");
            return;
        }
        
        Byte * buffer = (Byte*)malloc(bufferSize);
        int read = 0, offset = 0, written = 0;
        NSError* err;
        if (size != 0) {
            do {
                read = [rep getBytes:buffer
                          fromOffset:offset
                              length:bufferSize 
                               error:&err];
                written = fwrite(buffer, sizeof(char), read, f);
                offset += read;
            } while (read != 0);
            
            
        }
        fclose(f);
    return tmpfile;
}