1

So I have a requirement where i have to encrypt Strings using RSA.

Have a look on this clipboardExample

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 my UUID / Pin & server PublicKey.
  • function escapes the closure at SecKeyCreateWithData as it's always returning nil, What am i missing.
Mohmmad S
  • 5,001
  • 4
  • 18
  • 50

0 Answers0