NSValueTranformer to encrypt data

拟墨画扇 提交于 2019-12-08 00:35:18

问题


I want to encrypt some core-data columns with help of an NSValueTransformer. The idea is, that I use data-type transformable and define some transformer for my datatypes. Inside the transformation-methods I want to encrypt/ decrypt the value. I defined a transformer that does actually nothing - the crypto-stuff is currently not implemented.

@implementation StringCryptoTransformer

+ (Class)transformedValueClass { return [NSString class]; }


+ (BOOL)allowsReverseTransformation { return YES; }


- (NSString*)transformedValue:(id)value {

    NSLog(@"Transformer: %@",value);

    if([value isKindOfClass:[NSString class]]){
        return value;
    }
    return nil;
}     

- (NSString*)reverseTransformedValue:(id)value
{
    return value;
}

The method

- (NSString*)transformedValue:(id)value

gets called with a valid value but when fetching objects I get this error:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString bytes]: unrecognized selector sent to instance 0xf5859f0'

Any ideas what is wrong?

EDIT:

I realized that I have to convert to NSData and vice versa. Now It works fine

- (id)transformedValue:(id)value {

    NSData *data =  [((NSString*)value) dataUsingEncoding:NSUTF8StringEncoding];
    return [CryptoUtils encryptWithKey:self.key data:data];
}


- (id)reverseTransformedValue:(id)value
{
    NSData *data = [CryptoUtils decryptWithKey:self.key data:value];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

回答1:


I realized that I have to convert to NSData and vice versa. Now It works fine

- (id)transformedValue:(id)value {

    NSData *data =  [((NSString*)value) dataUsingEncoding:NSUTF8StringEncoding];
    return [CryptoUtils encryptWithKey:self.key data:data];
}    

- (id)reverseTransformedValue:(id)value
{
    NSData *data = [CryptoUtils decryptWithKey:self.key data:value];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}


来源:https://stackoverflow.com/questions/10685196/nsvaluetranformer-to-encrypt-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!