Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
            }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...