在Swift中加密和解密超过132个字符

时间:2018-05-21 05:44:43

标签: swift encryption rsa

我有这个Rsa swift代码并且它工作正常并加密或破坏数据但是当string.count超过132 char错误破坏并加密数据时,我怎样才能破坏和加密数据超过132个char 我的Rsa课程是,我不想要单独的数据

class RSAWrapper {
    private var publicKey : SecKey?
    private var privateKey : SecKey?

    func generateKeyPair(keySize: UInt, privateTag: String, publicTag: String) -> Bool {

        self.publicKey = nil
        self.privateKey = nil

        if (keySize != 512 && keySize != 1024 && keySize != 2048) {
            // Failed
            print("kelid kharab ast")
            return false
        }

        let publicKeyParameters: [NSString: AnyObject] = [
            kSecAttrIsPermanent: true as AnyObject,
            kSecAttrApplicationTag: publicTag as AnyObject
        ]
        let privateKeyParameters: [NSString: AnyObject] = [
            kSecAttrIsPermanent: true as AnyObject,
            kSecAttrApplicationTag: publicTag as AnyObject
        ]
        let parameters: [String: AnyObject] = [
            kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
            kSecAttrKeySizeInBits as String: keySize as AnyObject,
            kSecPrivateKeyAttrs as String: privateKeyParameters as AnyObject,
            kSecPublicKeyAttrs as String: publicKeyParameters as AnyObject
        ];

        let status : OSStatus = SecKeyGeneratePair(parameters as CFDictionary, &(self.publicKey), &(self.privateKey))

        return (status == errSecSuccess && self.publicKey != nil && self.privateKey != nil)
    }

    func encrypt(text: String) -> [UInt8] {
        let plainBuffer = [UInt8](text.utf8)
        var cipherBufferSize : Int = Int(SecKeyGetBlockSize((self.publicKey)!))
        var cipherBuffer = [UInt8](repeating:0, count:Int(cipherBufferSize))

        // Encrypto  should less than key length
        let status = SecKeyEncrypt((self.publicKey)!, SecPadding.PKCS1, plainBuffer, plainBuffer.count, &cipherBuffer, &cipherBufferSize)
        if (status != errSecSuccess) {
            print("Failed Encryption")
        }
        return cipherBuffer
    }

    func decprypt(encrpted: [UInt8]) -> String? {
        var plaintextBufferSize = Int(SecKeyGetBlockSize((self.privateKey)!))
        var plaintextBuffer = [UInt8](repeating:0, count:Int(plaintextBufferSize))

        let status = SecKeyDecrypt((self.privateKey)!, SecPadding.PKCS1, encrpted, plaintextBufferSize, &plaintextBuffer, &plaintextBufferSize)

        if (status != errSecSuccess) {
            print("Failed Decrypt")
            return nil
        }
        return NSString(bytes: &plaintextBuffer, length: plaintextBufferSize, encoding: String.Encoding.utf8.rawValue)! as String
    }


    func encryptBase64(text: String) -> String {
        let plainBuffer = [UInt8](text.utf8)
        var cipherBufferSize : Int = Int(SecKeyGetBlockSize((self.publicKey)!))
        var cipherBuffer = [UInt8](repeating:0, count:Int(cipherBufferSize))

        // Encrypto  should less than key length
        let status = SecKeyEncrypt((self.publicKey)!, SecPadding.PKCS1, plainBuffer, plainBuffer.count, &cipherBuffer, &cipherBufferSize)
        if (status != errSecSuccess) {
            print("Failed Encryption")
        }

        let mudata = NSData(bytes: &cipherBuffer, length: cipherBufferSize)
        return mudata.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength64Characters)
    }

    func decpryptBase64(encrpted: String) -> String? {

        let data : NSData = NSData(base64Encoded: encrpted, options: .ignoreUnknownCharacters)!
        let count = data.length / MemoryLayout<UInt8>.size
        var array = [UInt8](repeating: 0, count: count)
        data.getBytes(&array, length:count * MemoryLayout<UInt8>.size)

        var plaintextBufferSize = Int(SecKeyGetBlockSize((self.privateKey)!))
        var plaintextBuffer = [UInt8](repeating:0, count:Int(plaintextBufferSize))

        let status = SecKeyDecrypt((self.privateKey)!, SecPadding.PKCS1, array, plaintextBufferSize, &plaintextBuffer, &plaintextBufferSize)

        if (status != errSecSuccess) {
            print("Failed Decrypt")
            return nil
        }
        return NSString(bytes: &plaintextBuffer, length: plaintextBufferSize, encoding: String.Encoding.utf8.rawValue)! as String
    }


    func getPublicKey() -> SecKey? {
        return self.publicKey
    }

    func getPrivateKey() -> SecKey? {
        return self.privateKey
    }

我尝试更改UInt8但是当我做错误时,我必须做什么?

2 个答案:

答案 0 :(得分:2)

对于加密数据,使用AES等对称加密,速度快,没​​有大小限制。

如果您确实需要使用RSA(非对称)密钥对,请使用混合加密,其中数据使用对称加密进行加密,对称使用非对称加密进行加密,这称为混合加密。

但是,正如Luke所说,只需使用HTTPS加密传输中的数据。

答案 1 :(得分:-1)

唯一方法是拆分字符串 这个类用于拆分。

extension String {
    func splitByLength(_ length: Int) -> [String] {
        var result = [String]()
        var collectedCharacters = [Character]()
        collectedCharacters.reserveCapacity(length)
        var count = 0

        for character in self.characters {
            collectedCharacters.append(character)
            count += 1
            if (count == length) {
                // Reached the desired length
                count = 0
                result.append(String(collectedCharacters))
                collectedCharacters.removeAll(keepingCapacity: true)
            }
        }

        // Append the remainder
        if !collectedCharacters.isEmpty {
            result.append(String(collectedCharacters))
        }

        return result
    }
}

然后

 let rsa : RSAWrapper? = RSAWrapper()
        let success : Bool = (rsa?.generateKeyPair(keySize: 2048, privateTag: "com.atarmkplant", publicTag: "com.atarmkplant"))!
        if (!success) {
            print("Failed")
            return
        }



        let test : String = "string more than 132 char "

        let test2=test.splitByLength(132)
        let tedadarrray = test2.count


        var i = 0
        var encryptionstring = ""
        repeat {
            let test3 = test2[i]
            let encryption = rsa?.encryptBase64(text: test3)
            encryptionstring =  encryptionstring + encryption!
            i = i + 1
        } while i < tedadarrray




       let decripArray = encryptionstring.splitByLength(349)
        let tedadarrray2 = decripArray.count








        var i2 = 0
        var decripttionstring = ""
        repeat {
            print(i2 as Any)
            let test3 : String = decripArray[i2]
            let  decription = rsa?.decpryptBase64(encrpted: test3)
            decripttionstring =  decripttionstring + decription!
            i2 = i2 + 1
        } while i2 < tedadarrray2