将十六进制编码的字符串转换为字符串

将十六进制编码的字符串转换为字符串

本文介绍了将十六进制编码的字符串转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Swift 3中转换以下十六进制编码的String

I want to convert following hex-encoded String in Swift 3:

dcb04a9e103a5cd8b53763051cef09bc66abe029fdebae5e1d417e2ffc2a07a4

与其等价的String:

Ü°J:\ص7cï  ¼f«à)ýë®^A~/ü*¤

以下网站做得很好:

http://codebeautify.org/hex-string-converter

http://string-functions.com/hex-string.aspx

但是我无法在Swift 3中做同样的事情.以下代码也无法完成这项工作:

But I am unable to do the same in Swift 3. Following code doesn't do the job too:

func convertHexStringToNormalString(hexString:String)->String!{
  if let data = hexString.data(using: .utf8){
      return String.init(data:data, encoding: .utf8)
  }else{ return nil}
}

推荐答案

您要使用十六进制编码的数据作为AES密钥,但是数据不是有效的UTF-8序列.您可以解释它以ISO Latin编码形式作为字符串,但AES(key: String, ...)初始化程序将字符串转换回其UTF-8表示形式,也就是说,您将获得与开始时不同的关键数据.

You want to use the hex encoded data as an AES key, but thedata is not a valid UTF-8 sequence. You could interpretit as a string in ISO Latin encoding, but the AES(key: String, ...)initializer converts the string back to its UTF-8 representation,i.e. you'll get different key data from what you started with.

因此,您根本不应该将其转换为字符串.使用

Therefore you should not convert it to a string at all. Use the

extension Data {
    init?(fromHexEncodedString string: String)
}

来自在Swift中进行十六进制/二进制字符串转换的方法将十六进制编码的字符串转换为Data,然后将其传递作为AES(key: Array<UInt8>, ...)初始值设定项的数组:

method from hex/binary string conversion in Swiftto convert the hex encoded string to Data and then pass thatas an array to the AES(key: Array<UInt8>, ...) initializer:

let hexkey = "dcb04a9e103a5cd8b53763051cef09bc66abe029fdebae5e1d417e2ffc2a07a4"
let key = Array(Data(fromHexEncodedString: hexkey)!)

let encrypted = try AES(key: key, ....)

这篇关于将十六进制编码的字符串转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:03