小编典典

如何使用ios中的RSA公钥加密和解密字符串(纯文本)

swift

我想Encrypt用我的RSA公钥输入一个字符串(纯文本)。我有一个public key,作为从服务器发送来的,String并创建了一个RSA公共密钥。现在我想使用该键Encrypt填充文本PKACS12。我怎样才能做到这一点。我经历了很多堆栈溢出问题,但没有获得任何成功。

我这是怎么创建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)

这将创建一个RSA public key成功。现在我想用这个密钥来加密另一个Plain Text。我怎样才能做到这一点。


阅读 669

收藏
2020-07-07

共1个答案

小编典典

希望这个能对您有所帮助:

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
            }
2020-07-07