NSValueTranformer to encrypt data

1.2k views Asked by At

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

There are 1 answers

0
netshark1000 On BEST ANSWER

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];
}