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: