Flutter / Dart equivalent for "ChaChaPoly.SealedBox" in Swift - ios

I am developing a flutter application and need a equivalent to the "ChaChaPoly.SealedBox" in Swift (Cryptokit). Its important to initialize the box with a combination of nonce and cipher text. We do not have the nonce as separated bytes.
In Swift it looks like:
let encryptedBytes : Data = Data(base64Encoded: serverResponse)
let sealedBox = try! ChaChaPoly.SealedBox(combined: encryptedBytes)
let symmKey : SymmetricKey = SymmetricKey(data: keyData)
let decodedData : Data = try! ChaChaPoly.open(sealedBox, using: symmKey)
How could this be solved using flutter?
Thanks for your help!

Related

I received a response from the sever I wanted to decode it before I use it further

I have a string received from the server and I was trying to decode the string with padding but it is throwing nil as result. I tried codes that are available in stack overflow but of no use. Help will be highly appreciated.
I tried with base64 encoded with ignore unknown characters option and padding, still it throws nil.
let pem = "MIICyjCCAjOgAwIBAgIDBJPhMA0GCSqGSIb3DQEBBQUAMHsxEjAQBgNVBAMTCVJvb3RjZXJ0MTESMBAGA1UECRMJYmVsbGFuZHVyMQswCQYDVQQIEwJrYTEPMA0GA1UEERMGODg4ODg4MQwwCgYDVQQLEwNlc3MxGDAWBgNVBAoTD2VtdWRocmEgbGltaXRlZDELMAkGA1UEBhMCaW4wHhcNMTkwNzExMTAzNzM4WhcNMjgxMjI2MTAzNzM4WjB0MREwDwYDVQQDEwhBdmFkaGVzaDEMMAoGA1UECRMDYnRtMQswCQYDVQQIEwJrYTEPMA0GA1UEERMGODc4Nzg3MQwwCgYDVQQLEwNlc3MxGDAWBgNVBAoTD2VtdWRocmEgbGltaXRlZDELMAkGA1UEBhMCaW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMDAm7W3nc3hyyAhG8RBCSmlSDzcU/C39dPEFPq3N0JpSghMojnZg0jnfwXCvWqtPhlTYEdVLSXRehmQpS2v/FN8wkqZoVaKHNQE1UJnzPbyjfTlQA20nlCNVTNBQ70rWYzfuuFhliUBycGbYaIE/VGk354AEdXipLklCPf7PsgZAgMBAAGjYzBhMBIGA1UdEwEB/wQIMAYBAf8CAQAwHwYDVR0jBBgwFoAUkdq9ZIGVtD0x6k6hO7PdFMidh/QwHQYDVR0OBBYEFDwUkx0+5e1xTcavaVBpvREel/hZMAsGA1UdDwQEAwIBzjANBgkqhkiG9w0BAQUFAAOBgQBIDy2MjWWsZC9G1k3DFYyP2/jsj/xzKyQh2e5YrnxIGtK5jBRKZe3JOuq1wxMzRfzd22lnSyKzf4dKMp2ADXJnNQrB/aafGs9nf+FXuIomquZHoNGrThfSyB/tre8T3dMWRiUdYy74XL2wvQb6tVHPQ/UEPSYOyf3XDSnzpgtjmw=="
let decodedData = NSData(base64Encoded: dataStr, options: .ignoreUnknownCharacters)
let length = dataStr.count
dataStr = dataStr.padding(toLength: length + (4 - length % 4) % 4, withPad: "=", startingAt: 0)`
It has to give some decoded data with which I can create a certificate because the response is in the format of .cert.
A certificate is not a string. You cannot create a string from the raw Data.
You can decode the base64 encoded string simply with
let decodedData = Data(base64Encoded: dataStr)
Notes:
Don't use NSData in Swift.
The ignoreUnknownCharacters is not needed.
The padding is wrong. It's only required when encoding the data and the base64 related API of String and Data adds the = characters automatically.
May be It will Help
For Image I am doing like this
I am converting UIImage To data and Converting That data to base64EncodedString
let imageData = UIimage.pngData()
//encode string
let imgBase64Str = imageData?.base64EncodedString(options: .lineLength64Characters) ?? ""
//decoding string to data
let decodedData = Data(base64Encoded: imgBase64Str, options: .ignoreUnknownCharacters)

Is it possible to use CKRecord.encodeSystemFields with JSONEncoder

I see in "How (and when) do I use iCloud's encodeSystemFields method on CKRecord?" how to use NSKeyedArchiver to cache the salient fields of CKRecord. Is there a way to use JSONEncoder with encodeSystemFields? My other cache data is saved as JSON so I'd like encodeSystemFields to fit with that.
Unfortunately Data is not allowed in valid JSON despite being Codable, and fails the test JSONSerialization.isValidJSONObject, so I can't just jam the output of NSKeyedArchiver into my JSON serialization.
let d = Data()
d is Codable // true
// ...encodeSystemFields...
JSONSerialization.isValidJSONObject([d]) // false
let listofd = [d]
JSONSerialization.isValidJSONObject(listofd) // false
let dictofd = ["test":d]
JSONSerialization.isValidJSONObject(dictofd) // false
It doesn't matter if d is Data or NSMutableData. I get the same results.
The solution I found was to first serialize using NSKeyedArchiver to NSMutableData, cast it to Data, and use JSONEncoder to encode it again to JSON. It creates less than 2000 bytes of JSON. which overwhelmed my tiny record but that's life.
Here is a working playground for that:
import Foundation
import CloudKit
let zoneID1 = CKRecordZoneID(zoneName: "Test.1",
ownerName: CKCurrentUserDefaultName)
let recID1 = CKRecordID(recordName: "Test1",
zoneID: zoneID1)
let rec1 = CKRecord(recordType: "Test",
recordID: recID1)
let cacheNSData = NSMutableData()
let kArchiver = NSKeyedArchiver(forWritingWith: cacheNSData)
rec1.encodeSystemFields(with: kArchiver)
kArchiver.finishEncoding()
cacheNSData.length
let cacheData = cacheNSData as Data
let jEncoder = JSONEncoder()
struct Cache: Codable {
var title: String
var blob: Data
}
let cacheItem = Cache(title: "abc", blob: cacheData)
let jData = try jEncoder.encode(cacheItem)
jData.count
String(data: jData, encoding: .utf8)

What is the equivalence in swift 3

In java I am using the following code
string value = "b:0001"
byte[] bytes = value.getBytes("US-ASCII");
Does anyone know the equivalent in Swift 3 but instead of passing to bytes [] pass to Data?
This gives you Data back:
let str = "b:0001"
let bytes = str.data(using: .ascii)!

Value of type 'Data?' has no member 'base64EncodedStringWithOptions'

Here I am encoding my string but it gives an error stated above. What I had done is:
let plainData = (password)?.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
let base64String = plainData.base64EncodedStringWithOptions(NSData.Base64EncodingOptions.init(rawValue: 0))
It gives me an error on the second line of code.
If anyone can help!
You need to use base64EncodedString() function of NSData.
let base64String = plainData?.base64EncodedString()
This works with Swift 3.0
Actually with update of swift version it gives an error. We can do something like:
let plainData = (password)?.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
let base64String = plainData?.base64EncodedData(options: NSData.Base64EncodingOptions.init(rawValue: 0))
It solved my problem.

How to convert Base64 string to NSData?

I have an iOS application (written in Swift) that retrieves data from a wcf service in JSON format. One of the data is an image stored as a base64string. However, I was not able to convert the base64string to NSData.
My main purpose is to convert base64string all the way to blob so that I could save that in the database. On the other hand, if you know at least part of it such as from base64string to NSData would be helpful.
Following code would give you the idea of my table
let ItemsDB = Table("Items")
let idDB = Expression<String>("ID")
let nameDB = Expression<String>("Name")
let catDB = Expression<String>("Category")
let uomDB = Expression<String>("UOM")
let priceDB = Expression<Double>("Price")
let imageDB = Expression<Blob>("Image")
let actDB = Expression<Bool>("Active")
To convert from Base64 string to NSData
let nsd: NSData = NSData(base64EncodedString: Image, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!
To Convert to Blob
nsd.datatypeValue
This works:
Swift 3, 4 & 5:
var data = Data(base64Encoded: recording_base64, options: .ignoreUnknownCharacters)
Swift 2:
var data = NSData(base64EncodedString: recording_base64, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
There are lot of example you can find online but most of them are in Objective-c. For example, Converting between NSData and base64 strings
It is pretty straight forward for you to use
NSData(base64EncodedString: String, options: NSDataBase64DecodingOptions)

Resources