机密+强制施法违规:应避免强制施法。(force_cast)

Aru*_*thi 2 security swift

请不要标记重复的问题。

大家好,

我正在执行NSURLAuthenticationMethodClientCertificate,在其中使用以下代码。如果我不使用swiftlint,在哪种代码中可以使用。但是,当我使用swiftlint时,出现此错误,无法解决。尝试了很多,请帮助我。在下面发布代码。

    var items: CFArray?
    //let PKCS12Data = DataSourceManager.sharedInstance.serverPolicyManager?.PKCS12Data
    securityError = SecPKCS12Import(certData, options, &items)

    if securityError == errSecSuccess {
        let certItems: CFArray = items as CFArray!
        let certItemsArray: Array = certItems as Array
        let dict: AnyObject? = certItemsArray.first
        if let certEntry: Dictionary = dict as? Dictionary<String, AnyObject> {

            // grab the identity
            let identityPointer = certEntry["identity"]
            let secIdentityRef = identityPointer as!  SecIdentity
            print("\(String(describing: identityPointer))  :::: \(secIdentityRef)")
            // grab the trust
            let trustPointer: AnyObject? = certEntry["trust"]
            let trustRef: SecTrust? = trustPointer as! SecTrust
            print("\(String(describing: trustPointer))  :::: \(trustRef)")
            // grab the cert
            let chainPointer: AnyObject? = certEntry["chain"]
            identityAndTrust = IdentityAndTrust(identityRef: secIdentityRef, trust: trustRef!, certArray:  chainPointer!)

        }

    }
Run Code Online (Sandbox Code Playgroud)

我在以下几行中发现强制转换违反。

let secIdentityRef = identityPointer as! SecIdentity

let trustRef: SecTrust? = trustPointer as! SecTrust

swa*_*sta 5

基本上,您正在做的是强制向下转换,这意味着您保证自己identityPointer和和trustPointer分别是SecIdentity和SecTrust类的对象。但是如果不是的话该怎么办?您将它们从移出字典AnyObject,因此通常它们可能不会转换为目标类。斯威夫林特告诉您,强制施法是一种不良做法,希望您避免。

但是,对于CoreFoundation类型,您似乎不能使用条件转换as?,因此强制转换是唯一的选择。对于这种特殊情况,可以在代码中添加特殊注释来禁用Swiftlint规则。

let secIdentityRef = identityPointer as! SecIdentity // swiftlint:disable:this force_cast
Run Code Online (Sandbox Code Playgroud)

为了安全起见,您还可以通过检查Core Foundation的“类型ID”来检查对象的身份:

guard let identityPointer = certEntry["identity"],
    CFGetTypeID(identityPointer) == SecIdentityGetTypeID() else {
    // here you know that the cast will fail
}
let secIdentityRef = identityPointer as! SecIdentity // swiftlint:disable:this force_cast
Run Code Online (Sandbox Code Playgroud)