Advertisement
Guest User

Untitled

a guest
Jun 21st, 2012
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  ViewController.m
  3. //  cryptoTest
  4. //
  5. //  Created by Corey Werner on 6/19/12.
  6. //  Copyright (c) 2012 appSTUDIO. All rights reserved.
  7. //
  8.  
  9. #import "ViewController.h"
  10.  
  11. @interface ViewController ()
  12.  
  13. @end
  14.  
  15. @implementation ViewController
  16. @synthesize txtFldDecrypt;
  17. @synthesize txtFldEncrypt;
  18.  
  19. - (void)viewDidLoad
  20. {
  21.     [super viewDidLoad];
  22.     // Do any additional setup after loading the view, typically from a nib.
  23. }
  24.  
  25. - (void)viewDidUnload
  26. {
  27.     [self setTxtFldEncrypt:nil];
  28.     [self setTxtFldDecrypt:nil];
  29.     [super viewDidUnload];
  30.     // Release any retained subviews of the main view.
  31. }
  32.  
  33. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
  34. {
  35.     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
  36. }
  37.  
  38. - (void)dealloc {
  39.     [txtFldEncrypt release];
  40.     [txtFldDecrypt release];
  41.     [super dealloc];
  42. }
  43. - (IBAction)encrypt:(id)sender
  44. {
  45.     [self.txtFldEncrypt resignFirstResponder];
  46.     NSString *_key = @"1234";
  47.    
  48. //    self.txtFldDecrypt.text = [self.txtFldEncrypt.text AES128EncryptWithKey:_key];
  49.    
  50.     NSData *_secretData = [self.txtFldEncrypt.text dataUsingEncoding:NSASCIIStringEncoding];
  51.    
  52.     NSLog(@"plaintext string: %@",[[NSString alloc] initWithData:_secretData encoding:NSASCIIStringEncoding]);
  53.    
  54.     CCOptions padding = kCCOptionPKCS7Padding;
  55.     NSData *encryptedData = [self encrypt:_secretData key:[self md5data:_key] padding:&padding];
  56.    
  57.     NSLog(@"encrypted data: %@", encryptedData);
  58.    
  59.     NSLog(@"encoded string ASCII: %@",[[NSString alloc] initWithData:encryptedData encoding:NSASCIIStringEncoding]);
  60.     NSLog(@"encoded string UTF8: %@",[[NSString alloc] initWithData:encryptedData encoding:NSUTF8StringEncoding]);
  61.    
  62.     NSLog(@"b64 ASCII: %@",[encryptedData base64EncodingWithLineLength:0]);
  63.     self.txtFldDecrypt.text = [encryptedData base64EncodingWithLineLength:0];
  64. }
  65. - (IBAction)decrypt:(id)sender
  66. {
  67.     [self.txtFldDecrypt resignFirstResponder];
  68.     NSString *_key = @"Secret Passphrase";
  69.     NSData* encryptedData = [NSData dataWithBase64EncodedString:self.txtFldDecrypt.text];
  70.     CCOptions padding = kCCOptionPKCS7Padding;
  71.     NSData* data = [self decrypt:encryptedData key:[self md5data:_key] padding:&padding];
  72.     NSString *str = [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
  73.     self.txtFldEncrypt.text = str;
  74. }
  75.  
  76. - (NSData *)encrypt:(NSData *)plainText key:(NSData *)aSymmetricKey padding:(CCOptions *)pkcs7
  77. {
  78.     return [self doCipher:plainText key:aSymmetricKey context:kCCEncrypt padding:pkcs7];
  79. }
  80.  
  81. - (NSData *)decrypt:(NSData *)plainText key:(NSData *)aSymmetricKey padding:(CCOptions *)pkcs7
  82. {
  83.     return [self doCipher:plainText key:aSymmetricKey context:kCCDecrypt padding:pkcs7];
  84. }
  85.  
  86. - (NSData *)doCipher:(NSData *)plainText key:(NSData *)aSymmetricKey
  87.              context:(CCOperation)encryptOrDecrypt padding:(CCOptions *)pkcs7
  88. {
  89.     CCCryptorStatus ccStatus = kCCSuccess;
  90.     // Symmetric crypto reference.
  91.     CCCryptorRef thisEncipher = NULL;
  92.     // Cipher Text container.
  93.     NSData * cipherOrPlainText = nil;
  94.     // Pointer to output buffer.
  95.     uint8_t * bufferPtr = NULL;
  96.     // Total size of the buffer.
  97.     size_t bufferPtrSize = 0;
  98.     // Remaining bytes to be performed on.
  99.     size_t remainingBytes = 0;
  100.     // Number of bytes moved to buffer.
  101.     size_t movedBytes = 0;
  102.     // Length of plainText buffer.
  103.     size_t plainTextBufferSize = 0;
  104.     // Placeholder for total written.
  105.     size_t totalBytesWritten = 0;
  106.     // A friendly helper pointer.
  107.     uint8_t * ptr;
  108.    
  109.     // Initialization vector; dummy in this case 0's.
  110.     uint8_t iv[kChosenCipherBlockSize];
  111.     memset((void *) iv, 0x0, (size_t) sizeof(iv));
  112.    
  113.     NSLog(@"doCipher: plaintext: %@", plainText);
  114.     NSLog(@"doCipher: key length: %d", [aSymmetricKey length]);
  115.    
  116.     //LOGGING_FACILITY(plainText != nil, @"PlainText object cannot be nil." );
  117.     //LOGGING_FACILITY(aSymmetricKey != nil, @"Symmetric key object cannot be nil." );
  118.     //LOGGING_FACILITY(pkcs7 != NULL, @"CCOptions * pkcs7 cannot be NULL." );
  119.     //LOGGING_FACILITY([aSymmetricKey length] == kChosenCipherKeySize, @"Disjoint choices for key size." );
  120.    
  121.     plainTextBufferSize = [plainText length];
  122.    
  123.     //LOGGING_FACILITY(plainTextBufferSize > 0, @"Empty plaintext passed in." );
  124.    
  125.     NSLog(@"pkcs7: %d", *pkcs7);
  126.     // We don't want to toss padding on if we don't need to
  127.     if(encryptOrDecrypt == kCCEncrypt) {
  128.         if(*pkcs7 != kCCOptionECBMode) {
  129.             if((plainTextBufferSize % kChosenCipherBlockSize) == 0) {
  130.                 *pkcs7 = 0x0000;
  131.             } else {
  132.                 *pkcs7 = kCCOptionPKCS7Padding;
  133.             }
  134.         }
  135.     } else if(encryptOrDecrypt != kCCDecrypt) {
  136.         NSLog(@"Invalid CCOperation parameter [%d] for cipher context.", *pkcs7 );
  137.     }
  138.    
  139.     // Create and Initialize the crypto reference.
  140.     ccStatus = CCCryptorCreate(encryptOrDecrypt,
  141.                                kCCAlgorithmAES128,
  142.                                *pkcs7,
  143.                                (const void *)[aSymmetricKey bytes],
  144.                                kChosenCipherKeySize,
  145.                                (const void *)iv,
  146.                                &thisEncipher
  147.                                );
  148.    
  149.     //LOGGING_FACILITY1( ccStatus == kCCSuccess, @"Problem creating the context, ccStatus == %d.", ccStatus );
  150.    
  151.     // Calculate byte block alignment for all calls through to and including final.
  152.     bufferPtrSize = CCCryptorGetOutputLength(thisEncipher, plainTextBufferSize, true);
  153.    
  154.     // Allocate buffer.
  155.     bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t) );
  156.    
  157.     // Zero out buffer.
  158.     memset((void *)bufferPtr, 0x0, bufferPtrSize);
  159.    
  160.     // Initialize some necessary book keeping.
  161.    
  162.     ptr = bufferPtr;
  163.    
  164.     // Set up initial size.
  165.     remainingBytes = bufferPtrSize;
  166.    
  167.     // Actually perform the encryption or decryption.
  168.     ccStatus = CCCryptorUpdate(thisEncipher,
  169.                                (const void *) [plainText bytes],
  170.                                plainTextBufferSize,
  171.                                ptr,
  172.                                remainingBytes,
  173.                                &movedBytes
  174.                                );
  175.    
  176.     //LOGGING_FACILITY1( ccStatus == kCCSuccess, @"Problem with CCCryptorUpdate, ccStatus == %d.", ccStatus );
  177.    
  178.     // Handle book keeping.
  179.     ptr += movedBytes;
  180.     remainingBytes -= movedBytes;
  181.     totalBytesWritten += movedBytes;
  182.    
  183.     /* From CommonCryptor.h:
  184.      
  185.      @enum      CCCryptorStatus
  186.      @abstract  Return values from CommonCryptor operations.
  187.      
  188.      @constant  kCCSuccess          Operation completed normally.
  189.      @constant  kCCParamError       Illegal parameter value.
  190.      @constant  kCCBufferTooSmall   Insufficent buffer provided for specified operation.
  191.      @constant  kCCMemoryFailure    Memory allocation failure.
  192.      @constant  kCCAlignmentError   Input size was not aligned properly.
  193.      @constant  kCCDecodeError      Input data did not decode or decrypt properly.
  194.      @constant  kCCUnimplemented    Function not implemented for the current algorithm.
  195.      
  196.      enum {
  197.      kCCSuccess          = 0,
  198.      kCCParamError       = -4300,
  199.      kCCBufferTooSmall   = -4301,
  200.      kCCMemoryFailure    = -4302,
  201.      kCCAlignmentError   = -4303,
  202.      kCCDecodeError      = -4304,
  203.      kCCUnimplemented    = -4305
  204.      };
  205.      typedef int32_t CCCryptorStatus;
  206.      */
  207.    
  208.     // Finalize everything to the output buffer.
  209.     ccStatus = CCCryptorFinal(thisEncipher,
  210.                               ptr,
  211.                               remainingBytes,
  212.                               &movedBytes
  213.                               );
  214.    
  215.     totalBytesWritten += movedBytes;
  216.    
  217.     if(thisEncipher) {
  218.         (void) CCCryptorRelease(thisEncipher);
  219.         thisEncipher = NULL;
  220.     }
  221.    
  222.     //LOGGING_FACILITY1( ccStatus == kCCSuccess, @"Problem with encipherment ccStatus == %d", ccStatus );
  223.    
  224.     if (ccStatus == kCCSuccess)
  225.         cipherOrPlainText = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)totalBytesWritten];
  226.     else
  227.         cipherOrPlainText = nil;
  228.    
  229.     if(bufferPtr) free(bufferPtr);
  230.    
  231.     return cipherOrPlainText;
  232.    
  233.     /*
  234.      Or the corresponding one-shot call:
  235.      
  236.      ccStatus = CCCrypt(    encryptOrDecrypt,
  237.      kCCAlgorithmAES128,
  238.      typeOfSymmetricOpts,
  239.      (const void *)[self getSymmetricKeyBytes],
  240.      kChosenCipherKeySize,
  241.      iv,
  242.      (const void *) [plainText bytes],
  243.      plainTextBufferSize,
  244.      (void *)bufferPtr,
  245.      bufferPtrSize,
  246.      &movedBytes
  247.      );
  248.      */
  249. }
  250.  
  251.  
  252. // this added by David
  253. - (NSData*) md5data: ( NSString *) str
  254. {
  255.     const char *cStr = [str UTF8String];
  256.     unsigned char result[CC_MD5_DIGEST_LENGTH];
  257.     CC_MD5( cStr, strlen(cStr), result );
  258.     NSString* temp = [NSString  stringWithFormat:
  259.                       @"02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
  260.                       result[0], result[1], result[2], result[3], result[4],
  261.                       result[5], result[6], result[7],
  262.                       result[8], result[9], result[10], result[11], result[12],
  263.                       result[13], result[14], result[15]
  264.                       ];
  265.     return  [NSData dataWithBytes:[temp UTF8String] length:[temp length]];
  266.    
  267. }
  268.  
  269. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement