Skip to content

Instantly share code, notes, and snippets.

@adamjuhasz
Created October 22, 2014 22:08
Show Gist options
  • Save adamjuhasz/1250fb4ad5495f597b93 to your computer and use it in GitHub Desktop.
Save adamjuhasz/1250fb4ad5495f597b93 to your computer and use it in GitHub Desktop.
Easy Data Encryption
#import <Foundation/Foundation.h>
@interface MomentEncrypter : NSValueTransformer
@property NSData *key;
@property NSData *iv;
- (void)setKeyAndIVWith:(NSString*)password;
@end
#import "MomentEncrypter.h"
#import <CocoaSecurity/CocoaSecurity.h>
@implementation MomentEncrypter
+ (BOOL)allowsReverseTransformation
{
return YES;
}
+ (Class)transformedValueClass
{
return NSData.class;
}
- (id)init
{
self = [super init];
if (self) {
[self setKeyAndIVWith:@"password"];
}
return self;
}
- (id)transformedValue:(id)dataIn
{
//encrypt string
CocoaSecurityResult *encrypted = [CocoaSecurity aesEncryptWithData:dataIn key:self.key iv:self.iv];
NSData *enctypedData = encrypted.data;
return enctypedData;
}
- (id)reverseTransformedValue:(id)dataIn
{
CocoaSecurityResult *decryptedResult = [CocoaSecurity aesDecryptWithData:dataIn key:self.key iv:self.iv];
NSData *decryptedData = decryptedResult.data;
return decryptedData;
}
- (void)setKeyAndIVWith:(NSString *)password
{
CocoaSecurityResult *keyIV = [CocoaSecurity sha384:password];
self.key = [keyIV.data subdataWithRange:NSMakeRange(0, 32)];
self.iv = [keyIV.data subdataWithRange:NSMakeRange(32, 16)];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment