So I have a requirement where i have to encrypt Strings
using RSA.
So after doing some researching i have found this could be the right answer for my case.
After modifying the code to form this at the last stage.
private func encrypt(with key: String) {
let serverPublicKey = key.data(using: .utf8)?.base64EncodedData()
guard let serverPublicKey2 = serverPublicKey else { return }
let data2 = Data(base64Encoded: serverPublicKey2)
guard let data = data2 else { return }
let keyDict:[NSObject:NSObject] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPublic,
kSecAttrKeySizeInBits: NSNumber(value: 2048),
kSecReturnPersistentRef: true as NSObject
]
let publickeysi = SecKeyCreateWithData(data as CFData, keyDict as CFDictionary, nil)
guard let publicKeySi = publickeysi else { return }
//Encrypt a string with the public key
let message = "This is my message." // this field in bullet point one
let blockSize = SecKeyGetBlockSize(publicKeySi)
var messageEncrypted = [UInt8](repeating: 0, count: blockSize)
var messageEncryptedSize = blockSize
var status: OSStatus!
status = SecKeyEncrypt(publickeysi!, SecPadding.PKCS1, message, message.count, &messageEncrypted, &messageEncryptedSize)
if status != noErr {
print("Encryption Error!")
return
}
}
- I Don't know what is
message
field stands for, and based on my requirement is this where i need to put myUUID
/Pin
& serverPublicKey
. - function escapes the closure at
SecKeyCreateWithData
as it's always returningnil
, What am i missing.