我不知道为什么 (char *)uint8_t 数组转换为 NSString 不起作用。ivString 始终为 (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 字节
密码字符串 NSString * 0x00000000
初始化向量 uint8_t [16]
ivString NSString * 0x00000000
键 NSString * 0x000d28c4 @"1234567890123456"
普通 NSData * 0x1ed80760 9 字节
附言
NSString* ivString = [[NSString alloc] initWithBytes:initialisationVector
length:16
encoding:NSUTF8StringEncoding];
这也行不通。仍然得到(空)
我调用的方法是:
- (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];
}