Swift4中使用CryptoSwift报错:表达式类型缺乏上下文导致歧义
Fixing "Type of expression is ambiguous without more context" in CryptoSwift AES Encryption (Swift 4)
The error you're hitting stems from a few mismatches between your code and how CryptoSwift expects AES parameters to be structured in Swift 4. Let's break down the issues and fix them step by step:
Key Issues in Your Code
- String vs. Byte Array Mismatch: CryptoSwift's AES initializer requires
keyandIVas[UInt8](byte arrays), not rawStringvalues. - Incorrect Block Mode Syntax: The
ivisn't a separate parameter for AES initialization—it's an associated value of theCBCblock mode enum. - Unsafe Force Unwraps: Using
!ondataandtry!can cause crashes if operations fail. Since your function is markedthrows, we should properly propagate errors instead. - Redundant Optional Unwrap: The
encrypt()method returns a non-optional[UInt8]on success, soenc!is unnecessary.
Corrected Code
Here's the revised function that resolves all these problems:
func aesEncrypt(_ key: String, iv: String) throws -> String { guard let data = self.data(using: .utf8) else { throw NSError(domain: "EncryptionError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to convert string to UTF-8 data"]) } let keyBytes = Array(key.utf8) let ivBytes = Array(iv.utf8) // Initialize AES with correct block mode syntax (IV is part of CBC) let aes = AES(key: keyBytes, blockMode: CBC(iv: ivBytes), padding: .pkcs7) let encryptedBytes = try aes.encrypt(Array(data)) let encData = Data(encryptedBytes) return encData.base64EncodedString() }
Important Additional Notes
- Key/IV Length Requirements: Make sure your key is 16, 24, or 32 bytes long (for AES-128, AES-192, AES-256 respectively) and your IV is exactly 16 bytes. If your input strings don't match these lengths, you may need to pad or hash them first (e.g., using SHA-256 to derive a 32-byte key from a shorter string).
- Error Handling: The guard statement now throws a meaningful error if string-to-data conversion fails, and we use
tryinstead oftry!to let encryption errors propagate to the caller for proper handling. - Version Compatibility: This code works with CryptoSwift versions compatible with Swift 4 (typically 0.8.x or 0.9.x). If you're using a newer version, syntax might shift slightly, but the core logic remains consistent.
内容的提问来源于stack exchange,提问作者Hitesh Mor
相关产品推荐
相关产品推荐

