RSA密钥创建始终为零

时间:2019-01-03 07:52:50

标签: ios swift encryption rsa

所以我有一个要求,我必须使用 RSA 来加密Strings

在剪贴板上查看Example

因此,在进行了一些研究之后,我发现this可能是适合我的情况的正确答案。

在修改代码以在最后阶段形成代码之后。

 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
    }
}
  • 我不知道message字段代表什么,根据我的要求,这是我需要将UUID / Pin和服务器PublicKey放入其中的地方。
  • 函数在始终返回SecKeyCreateWithData的情况下转义了nil处的闭包,我想念的是什么。

0 个答案:

没有答案