Looking for right approach to saving data with Keychain and data encryption - Swift 5 - swift

My app stores user's sensitive data and I wonder what is general/proper/the most secure way to secure the data.
My approach now is saving encoded data into Keychain, more specifically but simply :
I am encoding/decoding custom types in array with PropertyList
Then pass these to Keychain. I am using a wrapper called KeychainAccess thanks to Kishikawa Katsumi.
Retrieve data from Keychain then decode it to display on tableview.
Below is my code bits :
extension UserInformation {
static let propertyListEncoder = PropertyListEncoder()
static let propertyListDecoder = PropertyListDecoder()
static let keychain = Keychain(service: "com.xxxxx.DataSaving-App")
static func saveToKeychain(userInfo: [UserInformation]) {
let data = try? propertyListEncoder.encode(userInfo)
if let savingData = data {
dump(userInfo)
keychain[data: "encodedUserInfo"] = NSData(data: savingData) as Data
}
}
static func loadFromKeychain() -> [UserInformation]? {
guard let retrievedData = keychain[data: "encodedUserInfo"] else {
return nil }
let data = try? propertyListDecoder.decode(Array<UserInformation>.self, from: retrievedData)
return data
}
}
Above works fine and no problem found so far. However, I am not sure to use PropertyListEncoder is right way to encode/decode. Please kindly see below specified questions and giving advice to me should be very grateful.
Would above approach be secure enough?
Is PropertyListEncoder/Decoder just doing ENCODING/DECODING, NOT SAVING DATA TO ANY, like plist or any storage where is vulnerable?
If any other measure is needed, is encrypting data with Common Swift then passing it to Keychain making sense?
I spent few weeks to find detail solution but no luck yet. Please help a new developer.

Property list encoding is not encryption. It's plain text (possibly in binary format); it is just a form of serialization. The "encryption" in your example consists of the fact that the information is hidden in the keychain. And the keychain is generally regarded as sufficiently secure.

Related

I want to store formatted text in Realm Swift database

noob swift guy here.
I have this UITextView where the user writes something. I need to store his "note" to the database with all the formated text in it. That means if it has bold, I need to display it as bold later.
This text should be stored in local Realm Swift Database. Any solutions how can I achieve that? I head about "Markdown", but I didn't understand how can that be useful.
Much thanks! Have a great day!
Realm only stores ascii text and cannot directly store any formatting properties like BOLD, and that's true for most databases.
If you want to store formatted strings, one option is to archive it to a Data type, which Realm fully supports. Then, when reading data back in, unarchive it from Data back to a formatted string. (formatted strings are often called Rich Text or in code: attributedStrings)
The below code is macOS but iOS will be similar
A quick example - here's a class to hold a some attributed string data
class MyAttrStringClass: Object {
#Persisted var attrStringData: Data!
}
Suppose we have a (rich) text field with the following text
Hello, World
To store the class with the attributed string in Realm:
let s = self.myRichTextField.attributedStringValue
let data = try! NSKeyedArchiver.archivedData(withRootObject: s, requiringSecureCoding: false)
let myObject = MyAttrStringClass()
myObject.attrStringData = data
try! realm.write {
realm.add(myObject)
}
then when reading back from Realm and displaying the attributed string in that same field
let myObject = realm.objects(MyAttrStringClass.self).first!
let data = myObject.attrStringData!
let s = try! NSKeyedUnarchiver.unarchivedObject(ofClass: NSAttributedString.self, from: data)
self.myRichTextField.attributedStringValue = s!
Note: there's no error checking in the above. Please protect your code by safely unwrapping optionals.

Can Codable APIs be used to decode data encoded with NSKeyedArchiver.archivedData?

I'm converting a codebase from using NSCoding to using Codable. I have run into an issue when trying to restore data encoded with NSCoding. I have an object that was encoded with the code:
let encodedUser = NSKeyedArchiver.archivedData(withRootObject: user)
let userDefaults = UserDefaults.standard
userDefaults.set(encodedUser, forKey: userKey)
userDefaults.synchronize()
It was previously being decoded with the code:
if let encodedUser = UserDefaults.standard.data(forKey: userKey) {
if let user = NSKeyedUnarchiver.unarchiveObject(with: encodedUser) as? User {
\\ do stuff
}
}
After updating the User object to be Codable, I attempted to update the archive/unarchive code to use PropertyListDecoder because I saw that archivedData(withRootObject:) returns data formatted as NSPropertyListBinaryFormat_v1_0. When running this code:
if let encodedUser = UserDefaults.standard.data(forKey: userKey) {
let user = try! PropertyListDecoder().decode(User.self, from: encodedUser)
\\ do stuff
}
I get a keyNotFound error for the first key I'm looking for, and breakpointing in my init(from: Decoder), I can see that the container has no keys. I also tried to use PropertyListSerialization.propertyList(from:options:format) to see if I could pass that result into PropertyListDecoder, but that function gave me an NSCFDictionary, which is structured in a really strange way but does appear to contain all the data I'm looking for.
So is it possible to decode an object using Codable APIs if it was encoded with NSKeyedArchiver.archivedData(withRootObject:)? How can I achieve this?
I decided that the answer is almost certainly no, you cannot use Codable to decode what NSCoding encoded. I wanted to get rid of all the NSCoding cruft in my codebase, and settled on a migration path where I have both protocols implemented in the critical data models to convert stored data from NSCoding to Codable formats, and I will remove NSCoding in the future when enough of my users have updated.

Retrieving NSOrderedSet from Core Data and casting it to entity managedObjectSubclasss

Im making a Fitness app to learn Core data, and I have found that I need to let the user store every performed workout as a WorkoutLog item, and in there, there should be a series of ExerciseLogs which represents performances of that exercise (it contains each lift and also a reference to the actual exercise design).
Problem is that after a while i realize that i need to have these ordered, so that the next time i want to show the user their workout, the order that the exercisese were performed should be the same.
So I checked "ordered" in the top right of the image there, and now my code is in dire need of an update. I have tried to read as much as I could about working with NSOrderedSet and how to fetch them from core data and then manipulate them, but I havent really found much of use to me. (I have no experice in objective-c)
For example my code that used to be:
static func deleteWorkoutLog(_ workoutLogToDelete: WorkoutLog) {
guard let exerciseLogsToDelete = workoutLogToDelete.loggedExercises as? Set<ExerciseLog> else {
print("error unwrapping logged exercises in deleteWorkoutLog")
return
}
I get the error: .../DatabaseFacade.swift:84:77: Cast from 'NSOrderedSet?' to unrelated type 'Set' always fails
So what ive learned about sets and core data no longer seems applicable.
Im far from an expert in programming, but im very eager to learn how to get access to the loggedExercises instances.
TLDR; Is there a way to cast NSOrderedSet to something I can work with? How do we usually work with NSManagedSets from core data? Do we cast them to Arrays or MutableSets? I would very much appreciate an example or two on how to get started with retrieving and using these ordered sets!
Thanks
For anyone else wondering how to get started with orderedSets in core data:
After setting my the WorkoutLog.loggedExercises "to-many" relationship to be ordered, I managed to access them through the mutableOrderedSetValue function like this:
static func deleteWorkoutLog(_ workoutLogToDelete: WorkoutLog) {
let orderedExerciseLogs: NSMutableOrderedSet = workoutLogToDelete.mutableOrderedSetValue(forKey: "loggedExercises")
let exerciseLogsToDelete = orderedExerciseLogs.array
for exerciseLog in exerciseLogsToDelete {
guard let exerciseLog = exerciseLog as? ExerciseLog else {
return
}
Works great so far.
And to rearrange the NSOrderedSet I ended up doing something like this:
// Swap the order of the orderedSet
if let orderedExerciseLogs: NSOrderedSet = dataSourceWorkoutLog.loggedExercises {
var exerciseLogsAsArray = orderedExerciseLogs.array as! [ExerciseLog]
let temp = exerciseLogsAsArray[indexA]
exerciseLogsAsArray[indexA] = exerciseLogsAsArray[indexB]
exerciseLogsAsArray[indexB] = temp
let exerciseLogsAsOrderedeSet = NSOrderedSet(array: exerciseLogsAsArray)
dataSourceWorkoutLog.loggedExercises = exerciseLogsAsOrderedeSet
}

Storing a simple array in Realm without creating a managed List in Swift

I have an array of data that doesn't need to be a managed List, meaning I don't need Realm to create a new model for the items with links and the ability to query on the items, etc. I just want a simple array, typically of primitives that don't inherit from Object anyway, that will be persisted with my main object.
The only solution I can think of is to use NSData and NSKeyedArchiver/NSKeyedUnarchiver. Is that the best/only way to do this? Should I just use List even if I don't think I'll need it — what's the best practice for this situation?
Realm doesn't support arrays of primitives (although that functionality is coming soon), so the most straightforward solution is to use a List filled with model objects that just wrap your primitives. There's nothing wrong with archiving to and from NSData and storing the data in your Realm model, though, if you feel that better suits your particular use case.
Here's how I decided to deal with this:
var instructions: [String] {
get {
if _instructions == nil {
_instructions = NSKeyedUnarchiver.unarchiveObject(with: instructionsData) as? [String]
}
return _instructions!
}
set {
instructionsData = NSKeyedArchiver.archivedData(withRootObject: newValue)
_instructions = newValue
}
}
fileprivate var _instructions: [String]? = nil
dynamic var instructionsData = Data()
override static func ignoredProperties() -> [String] {
return ["instructions", "_instructions"]
}
That way I can use the array as I normally would and still have it persisted in a simple way (without having to create an actual List and having to manage a bunch of new models/objects).

Accessing a Dictionary using user input returning double value

I'd like the user to input a String to access a key in the dictionary which then returns its coupled value. I'm sure this isn't the only thing wrong with my code but trying to see if I have the right idea and hoping for some additional direction:
Main two issues are writing the correct syntax to connect the user input getInput() (String) inside the function callfunc planetAndTime()The function is passing my dictionary as a parameter.
My other issue is returning my function's double value. ->Double`
func getInput() -> String{
let kb: NSFileHandle = NSFileHandle.fileHandleWithStandardInput()
let inputData: NSData = kb.availableData
let strData = NSString(data: inputData, encoding:NSUTF8StringEncoding) as! String
return strData
}
/////////
let nameOfPlanetsAndTime:[String:Double] = ["Mercury":0.00000816,
"Venus":0.00044, "Mars":0.0000239, "Jupiter":0.00062, "Saturn":0.000204,
"Uranus":0.000289, "Neptune":0.000459, "Pluto":0.000794,
"Center of the Milky Way":25000.000000, "Earth's Cousin":1400.000000]
print("Choose planet")
func planetAndTime(nameOfPlanetsAndTime: [String:Double], userLocation:String) ->Double{
let userLocation = getInput()
if (nameOfPlanetsAndTime[userLocation] < 0){
print("Not a Valid Location, Please Try Again")}
else{
nameOfPlanetsAndTime[userLocation]!
print(nameOfPlanetsAndTime)
}
}
There are a few issues with your code that are due to a misunderstanding of how the Swift language works so I would recommend going through the official Swift documentation for some good examples of the Swift features. To give you a little head start however I will choose a section of your code. For example, instead of writing"
if (nameOfPlanetsAndTime[userLocation] < 0){
print("Not a Valid Location, Please Try Again")}
you can write
guard let planet = nameofPlanetsAndTime[userLocation] {
print("Not a Valid Location, Please Try Again")
return nil
}
return planet
and change the return type of your function to an optional Double. So the method signature would look like
func planetAndTime(nameOfPlanetsAndTime: [String:Double], userLocation:String) ->Double?
Understanding optionals is super important in the Swift "world" and I highly recommend taking a good look at how to use them. I hope this little example is helpful.
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309