【问题标题】:Chilkat iOS10+ RSA compatibility issueChilkat iOS10+ RSA 兼容性问题
【发布时间】:2018-10-24 18:47:49
【问题描述】:

我在一个 iOS 应用程序中使用本机 RSA,在另一个应用程序中使用 Chilkat RSA 库。在原生 iOS 端,我使用以下函数加密 (OAEP SHA256) 数据:

    static func encryptWithKey(_ data: Data, rsaKey: SecKey) -> Data? {
        let algorithm = SecKeyAlgorithm.rsaEncryptionOAEPSHA256

        guard SecKeyIsAlgorithmSupported(rsaKey, .encrypt, algorithm) else { return nil }

        var error: Unmanaged<CFError>?
        let encryptedData = SecKeyCreateEncryptedData(rsaKey, algorithm, data as CFData, &error)

        if let encryptionError = error {
            print(encryptionError.takeRetainedValue())
        }

        return encryptedData as Data?
    }

然后在另一个应用程序中,我使用 Chilkat 库解密这些数据:

static func decrypt(base64 encryptedText: String, with xmlKey: String) -> Data? {
    let privateKey = CkoPrivateKey()

    guard let success = privateKey?.loadXml(xmlKey), success else { return nil }
    guard let rsa = CkoRsa() else { return nil }

    rsa.unlockComponent(Chilkat.key)

    rsa.oaepPadding  = true
    rsa.littleEndian = false
    rsa.oaepHash     = "sha256"
    rsa.encodingMode = "base64"

    rsa.importPrivateKeyObj(privateKey)

    if let decryptedData = rsa.decryptBytesENC(encryptedText, bUsePrivateKey: true) {
        return decryptedData
    } else {
        print(rsa.lastErrorText)
    }

    return nil
}

即使我使用了一对私钥/公钥,我也会收到错误消息(来自 rsa.lastErrorText):

"ChilkatLog:
DecryptBytesENC(7ms):
    DllDate: Feb  1 2018
    ChilkatVersion: 9.5.0.72
    UnlockPrefix: XXXXXXXXXXXX
    Architecture: Little Endian; 64-bit
    Language: IOS C/C++/Swift/Objective-C
    VerboseLogging: 1
    usePrivateKey: 1
    Component successfully unlocked using purchased unlock code.
    rsaDecryptBytes(7ms):
    rsa_decrypt(7ms):
    KeyType: Private
    InputSize: 256
    Padding: OAEP
    OaepHashAlg: SHA-256
    MgfHashAlg: SHA-1
    ParamLen: 0
    ModulusBitLen: 2048
    inlen: 256
    modulus_bytelen: 256
    modulus_bitlen: 2048
    bigEndian: 0
    Byte swapping from big-endian to little-endian
    padding: OAEP
    No leading zero byte for OAEP decoding.
    OAEP decoding failed.
    --rsa_decrypt
    --rsaDecryptBytes
    Failed.
    --DecryptBytesENC
    --ChilkatLog"

有什么想法吗?

【问题讨论】:

    标签: ios swift encryption rsa chilkat


    【解决方案1】:

    我添加了一些额外的日志记录,因此我们可以在 RSA 解密之后但在 OAEP 取消填充之前查看字节(十六进制)。在 RSA 解密之后(但在 OAEP 取消填充之前),我们应该看到这种格式的字节:

    0x00  || maskedseed || maskedDB
    

    换句话说,结果的第一个字节应该是 0 字节。如果用于解密的 RSA 私钥与用于加密的公钥不对应,那么我们将看到随机字节。 (即第一个字节不会是 0)。 maskedseed 和 maskedDB 仍将显示为随机字节。

    【讨论】:

      【解决方案2】:

      问题出在 OAEP Mgf 哈希函数中。如果您设置 oaepMgfHash = "sha256" 它将与本机 iOS RSA 实现兼容。此外,Chilkat 库提供了对正确 oaepMgfHash 函数的自动回退,以防您错误地指定它。谢谢,马特!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-28
        • 2014-02-12
        • 2011-10-04
        • 2013-03-28
        • 2019-10-03
        • 2018-06-02
        • 2012-03-28
        相关资源
        最近更新 更多