Guest User

Untitled

a guest
May 20th, 2018
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. // CryptoViewController.m
  2.  
  3. #import "CryptoViewController.h"
  4. #import <CommonCrypto/CommonCryptor.h>
  5.  
  6. @interface NSData (Crypto)
  7. - (NSData *) cipher: (CCOperation) operation withKey: (NSData *) key;
  8. - (NSData *) cipherUsingAES128: (NSData *) key;
  9. - (NSData *) decipherUsingAES128: (NSData *) key;
  10. @end
  11.  
  12. @implementation NSData (Crypto)
  13.  
  14. - (NSData *) cipherUsingAES128: (NSData *) key {
  15. return [self cipher: kCCEncrypt withKey: key];
  16.  
  17. }
  18.  
  19. - (NSData *) decipherUsingAES128: (NSData *) key {
  20. return [self cipher: kCCDecrypt withKey: key];
  21. }
  22.  
  23. - (NSData *) cipher: (CCOperation) operation withKey: (NSData *) key
  24. {
  25. int plainTextBlockSize = ([self length] + kCCBlockSizeAES128) & ~(kCCBlockSizeAES128 - 1);
  26.  
  27. unsigned char plainText[plainTextBlockSize];
  28. bzero(plainText, plainTextBlockSize);
  29.  
  30. size_t plainTextLength;
  31.  
  32.  
  33. CCCryptorStatus status = CCCrypt(operation,
  34. kCCAlgorithmAES128,
  35. kCCOptionECBMode,
  36. [key bytes],
  37. kCCKeySizeAES128,
  38. NULL,
  39. [self bytes],
  40. [self length],
  41. plainText,
  42. plainTextBlockSize,
  43. &plainTextLength
  44. );
  45.  
  46. if (status == kCCSuccess) {
  47. return [NSData dataWithBytes: plainText length: plainTextLength];
  48. } else {
  49. return nil;
  50. }
  51. }
  52.  
  53. @end
  54.  
  55. @implementation CryptoViewController
  56.  
  57. - (void) testWithData: (NSData*) plain
  58. {
  59. NSData* key = [NSData dataWithBytes: "0123456789abcdef" length: 16];
  60.  
  61. NSData* encrypted = [plain cipherUsingAES128: key];
  62. NSData* decrypted = [encrypted decipherUsingAES128: key];
  63.  
  64. NSLog(@" Original length = %d", [plain length]);
  65. NSLog(@" Encrypted length = %d", [encrypted length]);
  66. NSLog(@" Decrypted length = %d", [decrypted length]);
  67.  
  68. if ([plain length] != [decrypted length]) {
  69. NSLog(@" Fail");
  70. }
  71. }
  72.  
  73. - (void) viewDidLoad
  74. {
  75. NSLog(@"Testing with content shorter than the block size");
  76. [self testWithData: [NSData dataWithBytes: "Hi!" length: 3]];
  77.  
  78. NSLog(@"Testing with content equal to the block size");
  79. [self testWithData: [NSData dataWithBytes: "01234567890abcdef" length: 16]];
  80.  
  81. NSLog(@"Testing with content equal to a multiple block size");
  82. [self testWithData: [NSData dataWithBytes: "01234567890abcdef01234567890abcdef01234567890abcdef" length: 3*16]];
  83.  
  84. NSLog(@"Testing with content longer than the block size");
  85. [self testWithData: [NSData dataWithBytes: "This plaintext is longer than the block size" length: 44]];
  86. }
  87.  
  88. @end
Add Comment
Please, Sign In to add comment