如何在ios,swift中使用RSA公钥加密和解密字符串(纯文本) [英] how to encrypt and decrypt a String(Plain Text) with RSA public key in ios, swift

查看:2212
本文介绍了如何在ios,swift中使用RSA公钥加密和解密字符串(纯文本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这就是我创建 RSA公钥的方式

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公钥。现在我想用这个密钥来加密另一个纯文本。我怎么能这样做。

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.

推荐答案

希望这会对你有所帮助:

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
            }

这篇关于如何在ios,swift中使用RSA公钥加密和解密字符串(纯文本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆