I have no idea why the (char *)uint8_t array transform to NSString doesn't work. ivString always is (null)
- (IBAction)encryptPacketBtnTouchDown:(id)sender {
NSString *key = @"1234567890123456";
NSData *plain = [plainMessage.text dataUsingEncoding:NSUTF8StringEncoding];
uint8_t initialisationVector[16];
arc4random_buf(initialisationVector, 16);
NSString* ivString = [NSString stringWithUTF8String:(char *)initialisationVector];
NSData *cipherData = [plain AES128EncryptWithKey:key iv:ivString];
[asyncSocket writeData:cipherData withTimeout:-1.0 tag:0];
NSString* cipherString = [[NSString alloc] initWithBytes:[cipherData bytes]
length:[cipherData length]
encoding:NSASCIIStringEncoding];
}
cipherData NSData * 0x1edaf3a0 16 bytes
cipherString NSString * 0x00000000
initialisationVector uint8_t [16]
ivString NSString * 0x00000000
key NSString * 0x000d28c4 @"1234567890123456"
plain NSData * 0x1ed80760 9 bytes
P.S.
NSString* ivString = [[NSString alloc] initWithBytes:initialisationVector
length:16
encoding:NSUTF8StringEncoding];
This also won't works. Still got (null)
The method I am calling is :
- (NSData *)AES128Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv
{
char keyPtr[kCCKeySizeAES128 + 1];
memset(keyPtr, 0, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
char ivPtr[kCCBlockSizeAES128 + 1];
memset(ivPtr, 0, sizeof(ivPtr));
[iv getCString:ivPtr
maxLength:sizeof(ivPtr)
encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesCrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(operation,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
keyPtr,
kCCBlockSizeAES128,
ivPtr,
[self bytes],
dataLength,
buffer,
bufferSize,
&numBytesCrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
}
free(buffer);
return nil;
}
- (NSData *)AES128EncryptWithKey:(NSString *)key iv:(NSString *)iv
{
return [self AES128Operation:kCCEncrypt key:key iv:iv];
}
Finally, I got the answer!
I just need treat the uint8_t[] array as a char[] array. Then, transform the char[] array to NSString by below line:
NSString* ivString = [NSString stringWithCString:initialisationVector encoding:NSASCIIStringEncoding];
Result is: ivString NSString * 0x1d8489c0 @"¹U ¡hÌTÖÆáβÍ"