这是我使用 RNCryptor 加密/解密我发送到 Web 服务的 JSON 字符串的方法。我正在使用静态 IV 变量,这可能是不好的做法,但请不要专注于此。这是我的做法:
注意:我使用的是 Matt Gallagher 的 NSData+Base64 类别,可在此处找到(在页面底部)
-(NSString*)encryptString:(NSString*)plaintext withKey:(NSString*)key error:(NSError**)error{
NSData *data = [plaintext dataUsingEncoding:NSUTF8StringEncoding];
NSData *encryptionKey = [NSData dataFromBase64String:key];
NSData *IV = [NSData dataFromBase64String:ENCRYPTION_IV];
RNCryptorEngine *engine = [[RNCryptorEngine alloc] initWithOperation:kCCEncrypt settings:kRNCryptorAES256Settings key:encryptionKey IV:IV error:error];
[engine addData:data error:error];
NSData *encryptedData = [engine finishWithError:error];
NSString *based64Encrypted = [encryptedData base64EncodedString];
NSLog(@"Encrytped: %@", based64Encrypted);
return based64Encrypted;
}
-(NSString*) decryptString:(NSString*)cipherText withKey:(NSString*)key error:(NSError**)error;{
NSData *data = [NSData dataFromBase64String:cipherText];
NSData *encryptionKey = [NSData dataFromBase64String:key];
NSData *IV = [NSData dataFromBase64String:ENCRYPTION_IV];
RNCryptorEngine *engine = [[RNCryptorEngine alloc] initWithOperation:kCCDecrypt settings:kRNCryptorAES256Settings key:encryptionKey IV:IV error:error];
[engine addData:data error:error];
NSData *decryptedData = [engine finishWithError:error];
NSString *decryptedString = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
NSLog(@"Decrypted: %@", decryptedString);
return decryptedString;
}
当我使用类似的字符串时,hello world
它可以正常工作。当我像我想象的那样使用一个字符串时{"username":"developer","password":"abcdefG*12"}
,它与编码有关,但我真的知道该使用什么。
当我加密该字符串时,我得到一个 base64 字符串,当我尝试解密时,我得到一个空字符串。
更新
更奇怪的是,它仅在字符串为 json 格式时失败,我认为这是我首先尝试的原因:
由于json 字符串中的 ,它看起来失败了。:
,但经过进一步调查,如果我破坏了任何 JSON 要求,
,它就会停止工作。它适用于但是,所以我不确定我做错了什么。无论哪种方式,我认为我们可以重新设计当前流程{
}
RNEncryptor
更新 2
这是我调用这些方法的地方:
NSDictionary *credentials = @{@"username":@"developer",@"password":@"abcdefG*12"};
NSString *jsonString = [ credentials JSONStringWithOptions:JKSerializeOptionNone error:&error];
NSLog(@"json string: %@", jsonString); //OUTPUTS: {"username":"developer","password":"abcdefG*12"}
CCGEncryption *encryptionObject = [[CCGEncryption alloc] init]; //THIS IS THE OBJECT WHERE THE encrypt/decrypt methods are
NSString *encrypted = [encryptionObject encryptString:jsonString withKey:ENCRYPTION_KEY error:&error];
if(error){
NSLog(@"Error:%@", error); //NO ERROR
}
NSString *decrypted = [encryptionObject decryptString:encrypted withKey:ENCRYPTION_KEY error:&error];
if(error){
NSLog(@"Error:%@", error); //NO ERROR
}
NSLog(@"decrypted: %@", decrypted); //OUTPUT: decrypted: