How to convert hex string to UInt8 byte array in Swift?

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 to convert hexString back to the same array from UInt8 bytes?

The reason I am asking is because I want to communicate with the server through an encrypted hexadecimal string, and I need to convert it back to an array of UInt8 bytes in order to decode the string into its original form.

+10
source share
2 answers

You can convert your hex string back to a UInt8 array by repeating every two hexadecimal characters and initialize UInt8 from it using the UInt8 radix 16 initializer:

 extension StringProtocol { var hexa: [UInt8] { var startIndex = self.startIndex return stride(from: 0, to: count, by: 2).compactMap { _ in let endIndex = index(startIndex, offsetBy: 2, limitedBy: self.endIndex) ?? self.endIndex defer { startIndex = endIndex } return UInt8(self[startIndex..<endIndex], radix: 16) } } } 

Playground:

 let hexaString = "e0696349774606f1b5602ffa6c2d953f" let bytes = hexaString.hexa // [224, 105, 99, 73, 119, 70, 6, 241, 181, 96, 47, 250, 108, 45, 149, 63] 
+22
source

Swift 5

 let hexString = "e0696349774606f1b5602ffa6c2d953f" let hexArray = Array<UInt8>.init(hex: hexString) // [224, 105, 99, 73, 119, 70, 6, 241, 181, 96, 47, 250, 108, 45, 149, 63] 
+1
source

Source: https://habr.com/ru/post/1266622/


All Articles