最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

encryption - Encrypt RSAECBOAEPWithSHA-256AndMGF1Padding Swift Padding error - Stack Overflow

programmeradmin0浏览0评论

Backend gives us publicKey and we need to encrypt with

RSA/ECB/OAEPWithSHA-256AndMGF1Padding

and send it to server.

I am using this functions :

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 : true] 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 bufferData = string.data(using: .utf8)!
            
            var error: Unmanaged<CFError>?
            guard let encryptedData = SecKeyCreateEncryptedData(
                publicKey,
                .rsaEncryptionOAEPSHA256, // Specify OAEP with SHA-256 padding
                bufferData as CFData,
                &error
            ) as Data? else { return nil }
            return encryptedData.base64EncodedString()
        }

But it is not working. The error is Padding error in decryption

发布评论

评论列表(0)

  1. 暂无评论