美文网首页
Swift5.0 DES加密算法

Swift5.0 DES加密算法

作者: Yo_Moon | 来源:发表于2020-08-11 14:40 被阅读0次

    不喜欢废话,纯干货

    
    
    import CommonCrypto
    
    extension String {
        
        func crypt(operation:CCOperation, key: String) -> String? {
            
            if let keyData = key.data(using: .utf8) {
                
                var cryptData: Data?
                
                if operation == kCCEncrypt {
                    cryptData = self.data(using: .utf8)
                } else {
                    cryptData = Data(base64Encoded: self, options: .ignoreUnknownCharacters)
                }
                
                if cryptData == nil {
                    return nil
                }
                
                let algoritm: CCAlgorithm = CCAlgorithm(kCCAlgorithmDES)
                let option: CCOptions = CCOptions(kCCOptionPKCS7Padding)
                
                let keyBytes = [UInt8](keyData)
                let keyLength = kCCKeySizeDES
                
                let dataIn = [UInt8](cryptData!)
                let dataInlength = cryptData!.count
                
                let dataOutAvailable = Int(dataInlength + kCCBlockSizeDES)
                let dataOut = UnsafeMutablePointer<UInt8>.allocate(capacity: dataOutAvailable)
                let dataOutMoved = UnsafeMutablePointer<Int>.allocate(capacity: 1)
                
                dataOutMoved.initialize(to: 0)
                
                let cryptStatus = CCCrypt(operation, algoritm, option, keyBytes, keyLength, keyBytes, dataIn, dataInlength, dataOut, dataOutAvailable, dataOutMoved)
                
                var data: Data?
                
                if CCStatus(cryptStatus) == CCStatus(kCCSuccess) {
                    data = Data(bytesNoCopy: dataOut, count: dataOutMoved.pointee, deallocator: .none)
                }
                
                dataOutMoved.deallocate()
                dataOut.deallocate()
                
                if data == nil {
                    return nil
                }
                
                if operation == kCCEncrypt {
                    data = data!.base64EncodedData(options: .lineLength64Characters)
                }
                
                return String(data: data!, encoding: .utf8)
            }
            
            return nil
    
        }
        
    }
    
    
    WX20200811-143245@2x.png

    相关文章

      网友评论

          本文标题:Swift5.0 DES加密算法

          本文链接:https://www.haomeiwen.com/subject/pwxydktx.html