Swift RSASignature (RSA签名认证采坑记!)

  • 非常非常重要
    encryptedStringurlEncodeStringsha256Data 签名和验证签名的数据务必要一致
    SecKeyAlgorithm 签名和验证使用的算法务必要一致
    publicKeyprivateKey 公钥私钥必须得是一对儿,私钥用于签名,公钥用于验证
        let publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQg49cH7GmFgwYZvF7tT65CsE0nYHAaoSAPshbojdP28mkZy2IWlm50nqFlZxIPhTltJHNddX3l1StvrE83F9QYPsAfPcPTIfftOhEXKqCKErDISDNT3QDE4YkHV925LEPDK+rShZoPfE2l3qB2gpQMZ1fLoDRkHw9HQRTWRulRwIDAQAB"
        let privateKey = "MIICXgIBAAKBgQDQg49cH7GmFgwYZvF7tT65CsE0nYHAaoSAPshbojdP28mkZy2IWlm50nqFlZxIPhTltJHNddX3l1StvrE83F9QYPsAfPcPTIfftOhEXKqCKErDISDNT3QDE4YkHV925LEPDK+rShZoPfE2l3qB2gpQMZ1fLoDRkHw9HQRTWRulRwIDAQABAoGBAK1PLDEeBsJNQPBnX/+6vc9/qObao6YS4t7VUCMZyW+O9yK2v5m9vyY8U6oEmElTkHr8gtOLRbTtC2z+OsKjSHQ9WJtrAZB0gxugdObk8BzszVmj5huiWTnyVd38RcRtk5owmShFzc1/Iol7ir/cGAddrcdqxcT1bRsL5oMHzuIBAkEA+lg+9nBr35IFjYHhJkI1H37DTpfMV1MOkZ6AcAYj/m4mr3CR6tJuh8JPEC/zkP5iypK5yOBiPHHWwu+xlA1SpwJBANU5Z50F9tNSMMLmXy5UI9eb4dBbD+SrB6CyqcuifCDDOnT+A5uxhLknO03l2rBAbzybj0mEY3hZk9cCU7nEjGECQQDFiNwlmI+F2bKH9fOyPIuuTlfNq/mQ7fiQ7oBp5G6CVGgyBqEcqO6OMMQyAaQuxIsvTJdL6cGZ8DmFl5yHNfwBAkBy0oL1kCynB++yRRSkgjL6/LrR1PfuEBv/cbb2Lf3iNr/YGKIgyavLeVD6Vfk6SLieTrcOw/g86yAt/NbRhwKBAkEAwG2AH/5jCLneXCS01+6SzKRJEqwdiTb1VtV1YFdcJLQMWyDjSJYeQfWBu6e0EhOE35igfZ6QkmZaMVKcLmJabw=="

        func sha256(data : Data) -> Data {
            var hash = [UInt8](repeating: 0,  count: Int(CC_SHA256_DIGEST_LENGTH))
            data.withUnsafeBytes {
                _ = CC_SHA256($0.baseAddress, UInt32(data.count), &hash)
            }
            var sha256String = ""
            for byte in hash {
                sha256String += String(format:"%02x", UInt8(byte))
            }
            
            print("sha256 hash: \(sha256String)")
            return Data(hash)
        }

        func getPrivateSecKey() -> SecKey? {
            
            let keyBase64 = Data(base64Encoded: privateKey, options: .ignoreUnknownCharacters)! as CFData
            
            let sec = SecKeyCreateWithData(keyBase64, [kSecAttrType: kSecAttrKeyTypeRSA, kSecAttrKeyClass: kSecAttrKeyClassPrivate] as NSDictionary, nil)
            
            return sec
        }
        
        func getPublicSecKey() -> SecKey? {
            let keyBase64 = Data(base64Encoded: publicKey, options: .ignoreUnknownCharacters)! as CFData
            
            let sec = SecKeyCreateWithData(keyBase64, [kSecAttrType: kSecAttrKeyTypeRSA, kSecAttrKeyClass: kSecAttrKeyClassPublic] as NSDictionary, nil)
            
            return sec
        }

        let encryptedString = "Content-Md5=E8DFA53F95CD10AFE9F8B0CB1E0BD3B8&Nonce=ios&Timestamp=1583223289"
        let urlEncodeString = encryptedString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        let sha256Data = sha256(data: urlEncodeString!.data(using: .utf8)!)
        
        var error: Unmanaged<CFError>?
        let secKey = getPrivateSecKey()
        let encryptedData = SecKeyCreateSignature(secKey!, .rsaSignatureDigestPKCS1v15SHA256, sha256Data as CFData, &error)
        
        let res = encryptedData! as Data
        print("sign:  ", res.base64EncodedString())
        
        let pubSecKey = getPublicSecKey()
        let bool = SecKeyVerifySignature(pubSecKey!, .rsaSignatureDigestPKCS1v15SHA256, sha256Data as CFData, encryptedData!, nil)
        print("verifyResult:  ", bool)

推荐阅读更多精彩内容