2

我将“CryptoSwift 1.0.0”和带有 Xcode 10.2 的 Swift 5 用于 iOS 应用程序,CryptoSwift 加密工作正常,还有我的 PHP 服务器加密和解密。

但是我收到了这个错误:dataPaddingRequired当这个方法被执行时:

let cipher = try aes.decrypt(Array<UInt8>(cryptedData))

这是我的代码:

加密功能

static func cryptArtisan(strClair: String) -> [String:String] {
    let key = generateStringKey()
    var cryptedMessage = ""
    var cryptedKey = ""
    do {
        let aes = try AES(key: Array<UInt8>(key.utf8), blockMode: ECB(), padding: .pkcs5) // aes128

        let ciphertext = try aes.encrypt(Array(strClair.utf8))
        cryptedMessage = ciphertext.toBase64()!

        let publicKey = try PublicKey(derNamed: "public")
        let clear = try ClearMessage(string: key, using: .utf8)
        let encrypted = try clear.encrypted(with: publicKey, padding: .PKCS1)
        cryptedKey = encrypted.base64String
    } catch { }

    cryptedMessage = cryptedMessage.replacingOccurrences(of: "+", with: "%2B")
    cryptedKey = cryptedKey.replacingOccurrences(of: "+", with: "%2B")

    return ["msg":cryptedMessage, "key":cryptedKey, "clairKey": key]
}

解密功能

static func decryptArtisan(cryptedMessage: String , key:String) -> String? {
    var clairMessage:String? = nil;

    if let cryptedData = Data(base64Encoded: cryptedMessage) {
        do {
            let aes = try AES(key: Array<UInt8>(key.utf8), blockMode: ECB(), padding: .pkcs5) // aes128
            let cipher = try aes.decrypt(Array<UInt8>(cryptedData))
            clairMessage = String(bytes: cipher, encoding: .utf8)
        }catch{
            print(error)
        }
    }

    return clairMessage
}

如何解密服务器发送的加密消息?

更新: 我试图不将错误转换为 NSError,我注意到抛出了 dataPaddingRequired 错误。

4

0 回答 0