Swift中实现AES 128字符串加密并输出二进制数据的问题
Got it, let's fix this for you! The issue with your current code is that you're converting the raw encrypted bytes to a hex string—what you actually want is to keep those bytes as binary data, which in Swift is represented using the Data type.
CryptoSwift's encrypt() method returns a [UInt8] array, which is just the raw binary bytes of your encrypted data. Instead of calling toHexString() on it, you can wrap that array directly into a Data instance, which is Swift's native way to handle binary data (perfect for things like file storage, network transmission, etc.).
Here's the revised code with proper error handling and binary output:
func encrypt(data: String) -> Data? { // Validate AES128 key and IV lengths (must be 16 bytes each) guard let keyBytes = "0101010101010101".data(using: .utf8)?.bytes, keyBytes.count == 16 else { print("Error: AES128 requires a 16-byte key") return nil } guard let ivBytes = "0000000000000000".data(using: .utf8)?.bytes, ivBytes.count == 16 else { print("Error: AES128 requires a 16-byte IV") return nil } do { let aes = try AES(key: keyBytes, iv: ivBytes) // Encrypt the input string's UTF-8 bytes into raw binary let encryptedBytes = try aes.encrypt(Array(data.utf8)) // Convert the byte array to Data (Swift's binary data type) return Data(encryptedBytes) } catch { print("Encryption failed: \(error.localizedDescription)") return nil } }
Key Notes:
- Binary Representation: The returned
Dataobject is pure binary data—you can write it directly to a file, send it over a network, or store it as-is without any string conversion. - Validation: I added checks to ensure your key and IV are exactly 16 bytes long (required for AES128). Your current key/IV strings work because their UTF-8 encoding is 16 bytes, but this catch prevents silent failures if you ever change them.
- Error Handling: Switched from
try?to ado-catchblock so you can see exactly what went wrong if encryption fails (way easier to debug!).
If you need to use this binary data later (like decrypting it), you can convert the Data back to a [UInt8] array using encryptedData.bytes (CryptoSwift adds this convenience extension to Data).
内容的提问来源于stack exchange,提问作者Muhammad Jamaal

