i want to encrypt the Data I upload to Firebase with curve25519.
Atm i convert my custom model to [String: Any] and upload this to firebase firestore.
Now I want to encrypt the Data. I thought that I understand how the public/privat key stuff works, but when I search for guides, they always (if I understand it right) use the privat key to encrypt (signature) the Data and the public key to decrypt (isValidSignature) the data.
I don't understand this. I thought that u need the public key to encrypt the data, so the receiver have to use the privat key to decrypt the data and read it.
The Code that others used to encrypt my Dic I found so far looks like this:
let jsonData = try? JSONSerialization.data(withJSONObject: Dic)
let digest512 = SHA512.hash(data: jsonData!)
let signatureForDigest = try! PrivateKey.signature(for: Data(digest512))
But I don't understand where the public key comes into the code. How I use the public key so the receiver can decrypt it with his privat key?
Hope someone can help me. Im really stuck and cant find anything that helps me. I only get more confused.
Greets
Related
We are exploring the use of Realm DB in Flutter.
We tried to initialize an existing encrypted realm file via the configuration details provided at https://pub.dev/packages/realm
var config = Configuration.local([Car.schema], disableFormatUpgrade: true,
path: 'assets/myfile.realm');
return Realm(config);
However, we could not find an option to specify the encryption key while opening the file.
Can anyone please help?
Thank you.
At this time, there is limited support for Realm in Flutter - although the beta package exists, it's a work in progress. You can still call native Realm functions from Flutter and get back access codes. See Flutter: Write platform specific code
Generally speaking, to encrypt a Realm, generate a random encryption key and pass it to the Realm configuration object. Keeping in mind that to unencrypt it, you need to use the same key so it will need to be stored.
Here's a quick Swift example how how to generate a key but the technique applies across the board to all platforms
var key = Data(count: 64)
_ = key.withUnsafeMutableBytes { (pointer: UnsafeMutableRawBufferPointer) in
SecRandomCopyBytes(kSecRandomDefault, 64, pointer.baseAddress!) }
Then to initially create that encrypted Realm, pass the key in the encryptionKey parameter in the Configuration object:
var config = Realm.Configuration(encryptionKey: key)
let realm = try Realm(configuration: config)
//write some data to Realm etc
Then later, get the key from wherever it was stored, typically in a keychain on macOS/iOS - or whatever secure way you choose to store it:
var key = //get the key
var config = Realm.Configuration(encryptionKey: key)
let realm = try Realm(configuration: config)
//read, write data from the encrypted Realm
First time I am building iOS application, I got stuck in saving data securely. How to save sensitive data like username and password in keychain
in app I am using UserDefaults to store and retrieve like below
UserDefaults.standard.set([unameTextfield.text], forKey: "userName")
UserDefaults.standard.set([passwordTextfield.text], forKey: "userPassword")
for retrieving:
let uName = UserDefaults.standard.string(forKey: "userName")
let uPassword = UserDefaults.standard.string(forKey: "userPassword")
but I want to save data securely in Keychain, how to do that?
You are correct, UserDefault is not a good solution when it comes to store sensitive information. Keychain is what you need; however, the problem is that keychain native API is not as easy/straighforward as Userdefault Api.
So, I think a great solution is to use KeychainWrapper.
First, install it. Make your cocaopod file look like this
use_frameworks!
platform :ios, '8.0'
target 'target_name' do
pod 'SwiftKeychainWrapper'
end
Then, install it from the terminal with pod install and import it. (This is from the docs)
import SwiftKeychainWrapper
//Set value
let saveSuccessful: Bool = KeychainWrapper.standard.set("Some String", forKey: "myKey")
//get value
let retrievedString: String? = KeychainWrapper.standard.string(forKey: "myKey")
I’m struggling on how to retrieve an attachment from a CouchDB in Server-Swift.
I understand that CouchDB has a kind of ‘flag’ (called stub) to indicate that there is an attachment.
In the JSON structure I get back from CouchDB I can spot under the key “_attachments” metadata (Content-Type, length etc)
I know how to retrieve that attachment from the CLI (curl -X GET ip:port{id}/{attachment_file}) but I’m drawing a blind how to do it from Swift.
The code to go through the results of a database.retrieveAll() call:
if let docs = docs {
for document in docs["rows"].arrayValue {
var plaatje = [String: Any]()
plaatje["ordernum"] = document["doc"]["orderNumber"].stringValue
plaatje["img"] = // what to put here?????
plaatjes.append(plaatje)
}
}
Is there a method of the database instance or any other way to get the binary of the attachment from Swift?
Currently i am generating an Elliptic Curve KeyPair in my iOS App successfully:
let privateKeyParams: [String: Any] = [
kSecAttrIsPermanent as String: true,
kSecAttrApplicationTag as String: privateTag
]
let publicKeyParams: [String: Any] = [
kSecAttrIsPermanent as String: true,
kSecAttrApplicationTag as String: publicTag,
kSecAttrAccessible as String: kSecAttrAccessibleAlways
]
let query: [String: Any] = [
kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
kSecPrivateKeyAttrs as String: privateKeyParams,
kSecPublicKeyAttrs as String: publicKeyParams,
kSecAttrKeySizeInBits as String: 256 as AnyObject,
]
let status = SecKeyGeneratePair(query as CFDictionary, &self.publicKey, &self.privateKey)
guard status == errSecSuccess else {
print("Could not generate keypair")
return
}
guard let pubKey = self.publicKey, let privKey = self.privateKey else {
print("Keypair null")
return
}
This one works because when i check if my keys exist they do and i can also encrypt/decrypt and sign/verify.
Soo.. in the next step i need to generate a SecCertificate which will basically hold my public key... this is simply a requirement.
But there is literally no API/Documentation on how to do this..the only api i saw is on how to generate SecCertificate from existing der file etc..
So my question is:
How do i generate an SecCertificate object from my existing Elliptic Curve KeyPair (SecKey)?
Thanks and Greetings!
Certificates and cryptographic functions in general are very bad documented and barely supported in Swift / iOS.
But the first question here is: Why do you need a certificate and what do you want to do? The main problem is that you just cannot create a valid certificate out of thin air. A certificate has to be signed by a a certificate authority (CA) so that anyone with the CA certificate can verify that the certificate is valid.
(Of course you can create a self signed certificate but this would be useless in most cases. Additionally, I do not know how to do this easily. All API calls in Swift / iOS assume that you already have a valid certificate. It seems that it is not intended to create certificates inside your app.)
So first, you need a certificate authority, which can sign your certificate. Then, you need to create a certificate signing request from your key pair and send it to your CA. You then will obtain a signed certificate, which you can use in your app. The steps in correct order are:
Create / find a certificate authority (CA)
Create your keypair
Create a certificate signing request (CSR). I currently use CertificateSigningRequestSwift because Apple simply does not provide any functionality to do this.
Send your CSR to the CA and receive the certificate (CRT).
Save the CRT together with the private key in a P12 trust store. I use OpenSSL-for-iPhone to do this.
Get the SecIdentity or the SecCertificate from the P12 trust store
This is a lot of work but after a long time of researching this is the only way I got certificates working in Swift / iOS. Especially the handling with OpenSSL is very tricky (have a look at this post of me to get an idea of the complexity). So, again, the question is what you want to do. If you want to create a SSL client, you need to go the full way, but if you just want to encrypt some stuff, the solution may be a lot easier.
I am learning some tricky development in iPhone and during my experiments I found out that usually we used localized web-service in which all parameter are fixed(Keyword). If my web service will change some fields in the response than how can we handle in iPhone. Please help me. If Anybody have any good idea.
For Example,
Webservice Response1:
[ {
"Number":"A12 hrb",
"List":[
{
"Type":"Works",
"Display":{
"dop":45,
"dopper":56
},
"OAST":"10-01-2012",
"OAET":"07-04-2012",
"Cause":"define",
"Impact":"Queue",
"Description":"Take a Break.",
"LName":"Lunetten To Lunetten",
"Number":"A12 hrb",
}
] }, ]
Webservice Response2:
[ {
"Number":"A12 hrb",
"Number2":"A13 brs",
"List":[
{
"Type":"Works",
"Display":{
"dop":45,
"dopper":56
"picker":90
},
"OAST":"10-01-2012",
"MAET":"07-04-2012",
"OAET":"07-04-2012",
"Cause":"define",
"Impact":"Queue",
"Description":"Take a Break.",
"LName":"Lunetten To Lunetten",
"Number":"A12 hrb",
}
] }, ]
You can do this
Parse the response.If response is JSON then definitely you will get a dictionary just keep a reference of it.
you can get all the keys in dictionary by calling following method
(NSArray *)allKeys
now enumerate above array and access the values respective to each key and do whatever you want
But you should know the meaning/purpose of dynamic keys. If you don't no meaning/purpose of keys these steps may not help you... best of luck.
For this type of case you can get the dictionary and in dictionary you
can get the value of which tag you want means you just need root node
and store root node all the data in dictionary and handle that
dictionary for the further use..
I don't think it will be possible to parse it completely. Atleast you should know which keys are going to be there. e.g. response has Number, Number2 & List as keys. It's ok if some responses do not contain one/some of the keys.
On the other hand, if knowing all the keys in advance is at all not possible, then webservice should have mechanism to convey the keys used in response.
e.g. [ {
"dynamic_keys": "Number2",
"Number":"A12 hrb",
"Number2":"A13 brs",
"List":[
{
"Type":"Works",
"Display":{
"dop":45,
"dopper":56
"picker":90
},
"OAST":"10-01-2012",
"MAET":"07-04-2012",
"OAET":"07-04-2012",
"Cause":"define",
"Impact":"Queue",
"Description":"Take a Break.",
"LName":"Lunetten To Lunetten",
"Number":"A12 hrb",
}
] }, ]
You can read the value of "dynamic_keys" and then using that value you can read value of actual dynamic key.
edit: as mentioned by ssteinberg you can use some framework like JSONKit to parse actual JSON.
See this as well: How to parse JSON having dynamic key node