【问题标题】:How to convert hexadecimal string to an array of UInt8 bytes in Swift?如何在 Swift 中将十六进制字符串转换为 UInt8 字节数组?
【发布时间】:2017-09-07 17:10:18
【问题描述】:

我有以下代码:

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

如何将hexString 转换回相同的UInt8 字节数组?

我问的原因是因为我想通过加密的十六进制字符串与服务器通信,我需要将其转换回 UInt8 字节数组以将字符串解码为其原始形式。

【问题讨论】:

标签: ios swift encryption aes


【解决方案1】:

您可以将您的十六进制字符串转换回 UInt8 数组,每两个六进制字符迭代一次,并使用 UInt8 radix 16 初始化程序从中初始化一个 UInt8:


编辑/更新:Xcode 14 • 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]

游乐场:

let hexaString = "e0696349774606f1b5602ffa6c2d953f"

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

【讨论】:

  • 能否在你的回答中解释这部分代码:.flatMap { UInt8(String(hexa[$0..&lt;$0.advanced(by: 2)]), radix: 16) }?
  • hexa 是一个字符数组,我使用 stride 每两个字符进行迭代。 $0 表示子范围 startIndex,$0..advanced(by: 2) 是子范围 endIndex。 uint8 radix 16 将字符串转换为0到255之间的数字
  • 最后一个问题。为什么我们在字符中跨过 2 而不是其他数字?
  • 你需要将两个hexa转换成1个字节(0-9 a...f = 0...15)16 * 16 = 256
【解决方案2】:

斯威夫特 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]

【讨论】:

  • 我尝试这个时遇到分段错误
【解决方案3】:

基于Leo Dabus的回答

详情

  • Swift 5.1,Xcode 11.2.1

解决方案

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()
    }
}

用法

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

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

完整样本

不要忘记在此处粘贴解决方案代码

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")

控制台输出

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 2017-08-23
    • 2015-09-21
    • 1970-01-01
    相关资源
    最近更新 更多