I have the following code:
var encryptedByteArray: Array<UInt8>?
do {
let aes = try AES(key: "passwordpassword", iv: "drowssapdrowssap")
encryptedByteArray = try aes.encrypt(Array("ThisIsAnExample".utf8))
} catch {
fatalError("Failed to initiate aes!")
}
print(encryptedByteArray!) // Prints [224, 105, 99, 73, 119, 70, 6, 241, 181, 96, 47, 250, 108, 45, 149, 63]
let hexString = encryptedByteArray?.toHexString()
print(hexString!) // Prints e0696349774606f1b5602ffa6c2d953f
How can I convert hexString
back to the same array of UInt8
bytes?
The reason why I am asking is because I want to communicate with a server through an encrypted hexadecimal string and I need to convert it back to an array of UInt8
bytes to decode the string to its original form.
Swift 5
You can convert your hexa string back to array of UInt8 iterating every two hexa characters and initialize an UInt8 from it using UInt8 radix 16 initializer:
Playground:
Details
Solution
Usage
Full sample
Console output