how to encrypt and decrypt a String(Plain Text) with RSA public key in ios, swift

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

I want to Encrypt a string(Plain Text) with my RSA public key. I have a public key, which sent from the server as a String and with that I created a RSA public key. now I want to use that key to Encrypt my text with padding PKACS12. how can I do that. I went through lots of stack overflow questions and I didn't get any success.

this is how I create the RSA public key,

let serverPublicKey = "Some text with key"  let data2 = Data.init(base64Encoded: serverPublicKey)  let keyDict:[NSObject:NSObject] = [   kSecAttrKeyType: kSecAttrKeyTypeRSA,   kSecAttrKeyClass: kSecAttrKeyClassPublic,   kSecAttrKeySizeInBits: NSNumber(value: 2048),   kSecReturnPersistentRef: true as NSObject  ]  let publickeysi = SecKeyCreateWithData(data2! as CFData, keyDict as CFDictionary, nil)

this creates a RSA public key successfully. now I want to use this key to encrypt my another Plain Text. how can I do that.

回答1:

Hope this will help you:

let serverPublicKey = "Some text with key"      let data2 = Data.init(base64Encoded: serverPublicKey)      let keyDict:[NSObject:NSObject] = [       kSecAttrKeyType: kSecAttrKeyTypeRSA,       kSecAttrKeyClass: kSecAttrKeyClassPublic,       kSecAttrKeySizeInBits: NSNumber(value: 2048),       kSecReturnPersistentRef: true as NSObject      ]      let publickeysi = SecKeyCreateWithData(data2! as CFData, keyDict as CFDictionary, nil)      //Encrypt a string with the public key             let message = "This is my message."             let blockSize = SecKeyGetBlockSize(publickeysi!)             var messageEncrypted = [UInt8](repeating: 0, count: blockSize)             var messageEncryptedSize = blockSize              var status: OSStatus!              status = SecKeyEncrypt(publickeysi!, SecPadding.PKCS1, message, message.characters.count, &messageEncrypted, &messageEncryptedSize)              if status != noErr {                 print("Encryption Error!")                 return             }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!