Advertisement
Guest User

Untitled

a guest
Apr 13th, 2012
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. CCCrypt encryption result issue
  2. @implementation NSData (AES256)
  3.  
  4. - (NSData *)AES256EncryptWithKey:(NSString *)key
  5. {
  6. char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
  7. bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
  8.  
  9. // fetch key data
  10. [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
  11.  
  12. NSUInteger dataLength = [self length];
  13.  
  14. size_t bufferSize = dataLength + kCCBlockSizeAES128;
  15. void *buffer = malloc(bufferSize);
  16.  
  17. size_t numBytesEncrypted = 0;
  18. CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
  19. keyPtr, kCCKeySizeAES256,
  20. NULL /* initialization vector (optional) */,
  21. [self bytes], dataLength, /* input */
  22. buffer, bufferSize, /* output */
  23. &numBytesEncrypted);
  24. if (cryptStatus == kCCSuccess) {
  25. return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
  26. }
  27.  
  28. free(buffer); //free the buffer;
  29. return nil;
  30. }
  31.  
  32. - (NSData *)AES256DecryptWithKey:(NSString *)key {
  33. char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
  34. bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
  35.  
  36. // fetch key data
  37. [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
  38.  
  39. NSUInteger dataLength = [self length];
  40.  
  41. size_t bufferSize = dataLength + kCCBlockSizeAES128;
  42. void *buffer = malloc(bufferSize);
  43.  
  44. size_t numBytesDecrypted = 0;
  45. CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
  46. keyPtr, kCCKeySizeAES256,
  47. NULL /* initialization vector (optional) */,
  48. [self bytes], dataLength, /* input */
  49. buffer, bufferSize, /* output */
  50. &numBytesDecrypted);
  51.  
  52. if (cryptStatus == kCCSuccess) {
  53. //the returned NSData takes ownership of the buffer and will free it on deallocation
  54. return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
  55. }
  56.  
  57. free(buffer); //free the buffer;
  58. return nil;
  59. }
  60.  
  61. NSString decryptedString = [[NSString alloc]initWithData:decryptedData];
  62.  
  63. NSData *data = [NSData dataByBase64DecodingString:decryptedString];
  64.  
  65. decryptedString = [data dataUsingEncoding:NSUTF8StrinEncoding];
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement