19

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.

Bista
  • 7,869
  • 3
  • 27
  • 55
fja
  • 1,823
  • 1
  • 15
  • 28
  • Related: [hex/binary string conversion in Swift](http://stackoverflow.com/questions/40276322/hex-binary-string-conversion-in-swift). – Martin R Apr 12 '17 at 06:55
  • Does this answer your question? [Converting Hex String to NSData in Swift](https://stackoverflow.com/questions/26501276/converting-hex-string-to-nsdata-in-swift) – Cy-4AH Dec 15 '22 at 09:13

3 Answers3

40

You can convert your hexa String back to array of [UInt8] iterating every two hexa characters and initialize an UInt8 using its string radix initializer. The following implementation assumes the hexa string is well formed:


Edit/update: Xcode 11 • Swift 5.1

extension StringProtocol {
    var hexaData: Data { .init(hexa) }
    var hexaBytes: [UInt8] { .init(hexa) }
    private var hexa: UnfoldSequence<UInt8, Index> {
        sequence(state: startIndex) { startIndex in
            guard startIndex < self.endIndex else { return nil }
            let endIndex = self.index(startIndex, offsetBy: 2, limitedBy: self.endIndex) ?? self.endIndex
            defer { startIndex = endIndex }
            return UInt8(self[startIndex..<endIndex], radix: 16)
        }
    }
}

let string = "e0696349774606f1b5602ffa6c2d953f"
let data = string.hexaData    // 16 bytes
let bytes = string.hexaBytes  // [224, 105, 99, 73, 119, 70, 6, 241, 181, 96, 47, 250, 108, 45, 149, 63]

If you would like to handle malformed hexa strings as well you can make it a throwing method:

extension String {
    enum DecodingError: Error {
        case invalidHexaCharacter(Character), oddNumberOfCharacters
    }
}

extension Collection {
    func unfoldSubSequences(limitedTo maxLength: Int) -> UnfoldSequence<SubSequence,Index> {
        sequence(state: startIndex) { lowerBound in
            guard lowerBound < endIndex else { return nil }
            let upperBound = index(lowerBound,
                offsetBy: maxLength,
                limitedBy: endIndex
            ) ?? endIndex
            defer { lowerBound = upperBound }
            return self[lowerBound..<upperBound]
        }
    }
}

extension StringProtocol {
    func hexa<D>() throws -> D where D: DataProtocol & RangeReplaceableCollection {
        try .init(self)
    }
}

extension DataProtocol where Self: RangeReplaceableCollection {
    init<S: StringProtocol>(_ hexa: S) throws {
        guard hexa.count.isMultiple(of: 2) else {
            throw String.DecodingError.oddNumberOfCharacters
        }
        self = .init()
        reserveCapacity(hexa.utf8.count/2)
        for pair in hexa.unfoldSubSequences(limitedTo: 2) {
            guard let byte = UInt8(pair, radix: 16) else {
                for character in pair where !character.isHexDigit {
                    throw String.DecodingError.invalidHexaCharacter(character)
                }
                continue
            }
            append(byte)
        }
    }
}

Usage:

let hexaString = "e0696349774606f1b5602ffa6c2d953f"
do {
    let bytes: [UInt8] = try hexaString.hexa()
    print(bytes)
    let data: Data = try hexaString.hexa()
    print(data)
} catch {
    print(error)
}

This will print

[224, 105, 99, 73, 119, 70, 6, 241, 181, 96, 47, 250, 108, 45, 149, 63]
16 bytes

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 1
    Is it possible to explain this portion of the code: `.flatMap { UInt8(String(hexa[$0..<$0.advanced(by: 2)]), radix: 16) }` in your answer? – fja Apr 12 '17 at 05:53
  • 1
    hexa is an array of characters that I am iterating every two of them using stride. $0 means the subrange startIndex and $0..advanced(by: 2) is the subrange endIndex. Uint8 radix 16 converts the string to a number from 0 to 255 – Leo Dabus Apr 12 '17 at 05:56
  • 1
    One last question. Why are we striding through the characters by 2 and not some other number? – fja Apr 12 '17 at 06:07
  • 1
    you need to convert two hexa into 1 byte (0-9 a...f = 0...15) 16 * 16 = 256 – Leo Dabus Apr 12 '17 at 06:10
  • Just mentioning that this might silently accept invalid input. As an example, both "0102xx" and "+1+2" return `[1, 2]`. – Martin R Apr 10 '22 at 17:50
  • @MartinR updated the [post](https://stackoverflow.com/a/43360864/2303865) to handle malformed hexa strings as well – Leo Dabus Apr 10 '22 at 22:02
  • 1
    Great! It is probably a matter of taste if this should be a throwing or a failable initializer. Since other initializers like `Data(base64Encoded:)` are failable, I chose that as well: https://stackoverflow.com/a/40278391/1187415. – Martin R Apr 11 '22 at 00:29
7

Swift 5

import CryptoSwift

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]
swearwolf
  • 327
  • 3
  • 10
3

Based on answer from Leo Dabus

Details

  • Swift 5.1, Xcode 11.2.1

Solution

enum HexConvertError: Error {
    case wrongInputStringLength
    case wrongInputStringCharacters
}

extension StringProtocol {
    func asHexArrayFromNonValidatedSource() -> [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)
        }
    }

    func asHexArray() throws -> [UInt8] {
        if count % 2 != 0 { throw HexConvertError.wrongInputStringLength }
        let characterSet = "0123456789ABCDEFabcdef"
        let wrongCharacter = first { return !characterSet.contains($0) }
        if wrongCharacter != nil { throw HexConvertError.wrongInputStringCharacters }
        return asHexArrayFromNonValidatedSource()
    }
}

Usage

// Way 1
do {
     print("with validation: \(try input.asHexArray() )")
} catch (let error) {
     print("with validation: \(error)")
}

// Way 2
"12g". asHexArrayFromNonValidatedSource()

Full sample

Do not forget to paste here the solution code

func test(input: String) {
    print("input: \(input)")
    do {
        print("with validation: \(try input.asHexArray() )")
    } catch (let error) {
        print("with validation: \(error)")
    }
    print("without validation \(input.asHexArrayFromNonValidatedSource())\n")
}

test(input: "12wr22")
test(input: "124")
test(input: "12AF")

Console output

input: 12wr22
with validation: wrongInputStringCharacters
without validation [18, 34]

input: 124
with validation: wrongInputStringLength
without validation [18, 4]

input: 1240
with validation: [18, 64]
without validation [18, 64]

input: 12AF
with validation: [18, 175]
without validation [18, 175]
Vasily Bodnarchuk
  • 24,482
  • 9
  • 132
  • 127