Created
February 26, 2015 07:30
-
-
Save jcayzac/b3e07899ed8e227cbb08 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSData *msg = [@"This is a message" dataUsingEncoding:NSUTF8StringEncoding]; | |
NSData *key = [@"the password" dataUsingEncoding:NSUTF8StringEncoding]; | |
NSLog(@"Unencrypted message: [%@]", msg); | |
uint8_t iv[kCCBlockSizeAES128]; | |
if (SecRandomCopyBytes(kSecRandomDefault, sizeof(iv), iv)) | |
{ | |
// ERROR | |
NSLog(@"Can't generate IV"); | |
} | |
size_t retSize = 0; | |
CCCryptorStatus result = CCCrypt(kCCEncrypt, | |
kCCAlgorithmAES, | |
kCCOptionPKCS7Padding, | |
key.bytes, | |
key.length, | |
iv, | |
msg.bytes, | |
msg.length, | |
0, | |
0, | |
&retSize); | |
if (result != kCCBufferTooSmall) | |
{ | |
// ERROR | |
NSLog(@"Can't get encrypted size"); | |
} | |
NSMutableData *data = [NSMutableData.alloc initWithLength:retSize + sizeof(iv)]; | |
result = CCCrypt(kCCEncrypt, | |
kCCAlgorithmAES, | |
kCCOptionPKCS7Padding, | |
key.bytes, | |
key.length, | |
iv, | |
msg.bytes, | |
msg.length, | |
(uint8_t *)data.mutableBytes + sizeof(iv), | |
retSize, | |
&retSize); | |
if (result != kCCSuccess) | |
{ | |
// ERROR | |
NSLog(@"Can't encrypt!"); | |
} | |
// ------- | |
if (data.length < kCCBlockSizeAES128) | |
{ | |
// ERROR | |
NSLog(@"Bad data"); | |
} | |
size_t decryptedSize = 0; | |
CCCryptorStatus decryptionResult = CCCrypt(kCCDecrypt, | |
kCCAlgorithmAES, | |
kCCOptionPKCS7Padding, | |
key.bytes, | |
key.length, | |
data.bytes, | |
(uint8_t *)data.bytes + kCCBlockSizeAES128, | |
data.length - kCCBlockSizeAES128, | |
0, | |
0, | |
&decryptedSize); | |
if (decryptionResult != kCCBufferTooSmall) | |
{ | |
// ERROR | |
NSLog(@"Can't get decrypted size"); | |
} | |
NSMutableData *decryptedData = [NSMutableData.alloc initWithLength:decryptedSize]; | |
decryptionResult = CCCrypt(kCCDecrypt, | |
kCCAlgorithmAES, | |
kCCOptionPKCS7Padding, | |
key.bytes, | |
key.length, | |
data.bytes, | |
(uint8_t *)data.bytes + kCCBlockSizeAES128, | |
data.length - kCCBlockSizeAES128, | |
decryptedData.mutableBytes, | |
decryptedSize, | |
&decryptedSize); | |
if (decryptionResult != kCCSuccess) | |
{ | |
// ERROR | |
NSLog(@"Can't decrypt"); | |
} | |
NSLog(@"Decrypted message: [%@]", decryptedData); | |
// Booh: | |
// 2015-02-26 16:29:24.244 Foo[58451:6269388] Unencrypted message: [<54686973 20697320 61206d65 73736167 65>] | |
// 2015-02-26 16:29:24.435 Foo[58451:6269388] Decrypted message: [<00000000 00000000 00000000 00000000 00a04f5d ff7f0000 0c521705 01000000>] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment