Source

JBSCrypto / JBSCrypto / JBSCrypto.m

Full commit
//  The MIT License (MIT)
//  Copyright (c) 2012 James Sumners
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to
//  deal in the Software without restriction, including without limitation the
//  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
//  sell copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
//  IN THE SOFTWARE.

#import "JBSCrypto.h"

@interface JBSCrypto()
+ (NSString *)dataToHexString:(NSData *)theData;
+ (NSData *)generateKeyData:(NSData *)fromData;
@end

@implementation JBSCrypto
#pragma mark - Decryption methods
// Adapted from http://pastie.org/426530
+ (NSData *)decryptData:(NSData *)theData withKey:(NSString *)key
{
  NSData *returnData = nil;
  char keyCStr[kCCKeySizeAES256+1];
  bzero(keyCStr, sizeof(keyCStr));
  
  [key
   getCString:keyCStr
   maxLength:sizeof(keyCStr)
   encoding:NSASCIIStringEncoding];
  
  NSUInteger dataLength = [theData length];
  size_t bufferSize = dataLength + kCCBlockSizeAES128;
  void *buffer = malloc(bufferSize);
  
  size_t bytesDecrypted = 0;
  CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                        kCCAlgorithmAES128,
                                        kCCOptionPKCS7Padding,
                                        keyCStr,
                                        kCCKeySizeAES256,
                                        NULL,
                                        [theData bytes],
                                        dataLength,
                                        buffer,
                                        bufferSize,
                                        &bytesDecrypted);
  
  if (cryptStatus == kCCSuccess) {
    returnData = [NSData dataWithBytes:buffer length:bytesDecrypted];
  }
  
  return returnData;
}

#pragma mark - Encryption methods
+ (NSData *)encryptData:(NSData *)theData withKey:(NSString *)key
{
  NSData *returnData = nil;
  char keyCStr[kCCKeySizeAES256+1];
  bzero(keyCStr, sizeof(keyCStr));
  
  [key
   getCString:keyCStr
   maxLength:sizeof(keyCStr)
   encoding:NSASCIIStringEncoding];
  
  NSUInteger dataLength = [theData length];
  size_t bufferSize = dataLength + kCCBlockSizeAES128;
  void *buffer = malloc(bufferSize);
  
  size_t bytesEncrypted = 0;
  CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                        kCCAlgorithmAES128,
                                        kCCOptionPKCS7Padding,
                                        keyCStr,
                                        kCCKeySizeAES256,
                                        NULL,
                                        [theData bytes],
                                        dataLength,
                                        buffer,
                                        bufferSize,
                                        &bytesEncrypted);
  
  if (cryptStatus == kCCSuccess) {
    returnData = [NSData dataWithBytes:buffer length:bytesEncrypted];
  }
  
  return returnData;
}

#pragma mark - Key generating methods
+ (NSString *)generateKey
{
  uint8_t randomBytes[1024];
  int result = SecRandomCopyBytes(kSecRandomDefault, 1024, randomBytes);
  NSString *returnString = nil;
  
  if (result == 0) {
    returnString = [self
                    generateKeyFromData:
                    [NSData dataWithBytes:randomBytes length:1024]];
  }
  
  return returnString;
}

+ (NSString *)generateKeyFromData:(NSData *)theData
{
  NSData *keyData = [self generateKeyData:theData];
  return [self dataToHexString:keyData];
}

+ (NSString *)generateKeyFromString:(NSString *)theString 
                       withEncoding:(NSStringEncoding)stringEncoding
{
  NSData *data = [theString dataUsingEncoding:stringEncoding];
  NSData *keyData = [self generateKeyData:data];
  
  return [self dataToHexString:keyData];
}

#pragma mark - Private methods
+ (NSString *)dataToHexString:(NSData *)theData
{
  NSMutableString *hexString = [NSMutableString stringWithCapacity:0];
  Byte *cstr = (unsigned char *)[theData bytes];
  for (int i = 0, j = (int)[theData length]; i < j; i += 1) {
    [hexString appendFormat:@"%02X", cstr[i]];
  }
  
  return hexString;
}

+ (NSData *)generateKeyData:(NSData *)fromData
{
  unsigned char messageDigest[CC_SHA256_DIGEST_LENGTH];
  CC_SHA256([fromData bytes], (CC_LONG)[fromData length], messageDigest);
  return [NSData dataWithBytes:messageDigest length:CC_SHA256_DIGEST_LENGTH];
}
@end