how to encrypt and decrypt a String(Plain Text) wi

2019-01-18 08:09发布

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条回答
太酷不给撩
2楼-- · 2019-01-18 08:42

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
            }
查看更多
登录 后发表回答