如何在Swift中将十六进制字符串转换为UInt8字节数组?

fja*_*fja 11 encryption aes ios swift

我有以下代码:

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
Run Code Online (Sandbox Code Playgroud)

我怎样才能转换hexString回相同的UInt8字节数组?

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

Leo*_*bus 23

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

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要么

let hexaString = "e0696349774606f1b5602ffa6c2d953f"

let bytes = hexaString.hexa   // [224, 105, 99, 73, 119, 70, 6, 241, 181, 96, 47, 250, 108, 45, 149, 63]
Run Code Online (Sandbox Code Playgroud)

操场:

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


swe*_*olf 7

斯威夫特 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]
Run Code Online (Sandbox Code Playgroud)