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

时间:2017-08-23 10:25:32

标签: ios swift encryption rsa

我希望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。现在我想用这个密钥来加密我的另一个func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else { return .zero } let cellCount = CGFloat(collectionView.numberOfItems(inSection: section)) if cellCount > 0 { let cellWidth = flowLayout.itemSize.width + flowLayout.minimumInteritemSpacing let totalCellWidth = cellWidth * cellCount let contentWidth = collectionView.frame.size.width - collectionView.contentInset.left - collectionView.contentInset.right - flowLayout.headerReferenceSize.width - flowLayout.footerReferenceSize.width if (totalCellWidth < contentWidth) { let padding = (contentWidth - totalCellWidth + flowLayout.minimumInteritemSpacing) / 2.0 return UIEdgeInsetsMake(0, padding, 0, 0) } } return .zero } 。我怎么能这样做。

2 个答案:

答案 0 :(得分:7)

希望这会对你有所帮助:

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
            }

答案 1 :(得分:0)

import Foundation
import Security


struct RSA {

static func encrypt(string: String, publicKey: String?) -> String? {
    guard let publicKey = publicKey else { return nil }

    let keyString = publicKey.replacingOccurrences(of: "-----BEGIN RSA PUBLIC KEY-----\n", with: "").replacingOccurrences(of: "\n-----END RSA PUBLIC KEY-----", with: "")
    guard let data = Data(base64Encoded: keyString) else { return nil }

    var attributes: CFDictionary {
        return [kSecAttrKeyType         : kSecAttrKeyTypeRSA,
                kSecAttrKeyClass        : kSecAttrKeyClassPublic,
                kSecAttrKeySizeInBits   : 2048,
                kSecReturnPersistentRef : kCFBooleanTrue] as CFDictionary
    }

    var error: Unmanaged<CFError>? = nil
    guard let secKey = SecKeyCreateWithData(data as CFData, attributes, &error) else {
        print(error.debugDescription)
        return nil
    }
    return encrypt(string: string, publicKey: secKey)
}

static func encrypt(string: String, publicKey: SecKey) -> String? {
    let buffer = [UInt8](string.utf8)

    var keySize   = SecKeyGetBlockSize(publicKey)
    var keyBuffer = [UInt8](repeating: 0, count: keySize)

    // Encrypto  should less than key length
    guard SecKeyEncrypt(publicKey, SecPadding.PKCS1, buffer, buffer.count, &keyBuffer, &keySize) == errSecSuccess else { return nil }
    return Data(bytes: keyBuffer, count: keySize).base64EncodedString()
   }
}

像这样使用

var pemString = "-----BEGIN RSA PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl/zjMK4w1XZAnpIqLeTAMW7cEUNIifP3HjmUavvc2+oPG1QjNCfxQM6LulZSl6qRim2JGxbc3yvnbMRJqch6IhJ/ysbTekVSqOjskIRGxq0pg0J8PqF3ZZQK6D7BYHi6iaJUMVV0ISB5LogJouyOWqsZyiEjgPz3jj0HIrh14Q6wPZVMpVbIwQR9nZp5gU5minseCyZfQs3PArgXgnzRPdw7Hb0/NY5OVE2Rz1SFTnda6w12SEu1IsVhVhJz1QteNrwNwJAT6WgZd+xnOZhU3Ei+EQK2SijfEGqmWNt1utJygK/0APy8w7VTol7ygbqfuHevGcg90QEXjxZKCjkXkQIDAQAB\n-----END RSA PUBLIC KEY-----"


let password = "abcdefg"
let encryptedPassword = RSA.encrypt(string: password, publicKey: pemString)
print(encryptedPassword)