I have used RNCryptor in my objective-c project to encrypt and decrypt a plist data file. Now I am recreating the project in Swift. When I try to decrypt the plist data in swift project which was created in objective-c project, it always throw "Decryption error: unknownHeader". I am using the same app identifier so that I can access the same plist file which was stored in App's Document's directory. Could someone advise what I am doing wrong? Here is my code:
Objective C - Encrypting and Saving to directory:
- (void)savePasswordlistItems {
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:items forKey:@"MyKey"];
[archiver finishEncoding];
NSError *error;
NSData *encryptedData = [RNEncryptor encryptData:data
withSettings:kRNCryptorAES256Settings
password:MY_SECRET_KEY
error:&error];
[encryptedData writeToFile:[self dataFilePath] atomically:YES];
}
Objective C - Decrypting, decoding, adding to NSmutableArray:
- (void)loadPasswordlistItems {
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
NSError *error;
NSData *decryptedData = [RNDecryptor decryptData:data
withPassword:MY_SECRET_KEY
error:&error];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData: decryptedData];
items = [unarchiver decodeObjectForKey:@"MyKey"];
[unarchiver finishDecoding];
}
else
{
items = [[NSMutableArray alloc] initWithCapacity:20];
}
}
Swift - Decrypting, decoding and adding to NSMutableArray:
func loadPasswordlistItems() {
let path = dataFilePath()
if FileManager.default.fileExists(atPath: path) {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path))
do {
let decryptedData = try RNCryptor.decrypt(data: data, withPassword: Constants.MY_SECRET_KEY)
let unarchiver = try NSKeyedUnarchiver(forReadingFrom: decryptedData)
items = (unarchiver.decodeObject(forKey: "MyKey") as! NSMutableArray)
unarchiver.finishDecoding()
} catch {
// Handle decryption error
print("Decryption error: \(error)")
}
} catch {
// Handle reading data from file error
print("Error reading data from file: \(error)")
}
} else {
items = []
}
}
Swift - Encoding, Encrypting and writing to Directory (I haven't test this as I could not decrypt the existing plist file):
func savePasswordlistItems() {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
archiver.encode(items, forKey: "MyKey")
archiver.finishEncoding()
let encryptedFile = RNCryptor.encrypt(data: data as Data, withPassword: Constants.MY_SECRET_KEY)
do {
try encryptedFile.write(to: URL(fileURLWithPath: dataFilePath()), options: .atomic)
} catch {
print(error)
}
}