如何将Python的HMAC请求翻译成Swift



我已经用了大约10个小时了,不管我在swift中使用什么HMAC组合,我都不能让它匹配python生成的密钥。

Python代码:

signature = hmac.new(secret.decode('hex'), msg=datastring, digestmod=hashlib.sha256).hexdigest()

迅速代码:

let key = SymmetricKey(data: self.secret.data(using: .utf8)!)
let hexData = HMAC<SHA256>.authenticationCode(for: datastring.data(using: .utf8)!, using: key)
let signature = Data(hexData).map { String(format: "%02hhx", $0) }.joined()

任何帮助我在Swift中做错了(或遗漏了),我将非常感激。

基于self.secret是包含密钥十六进制表示的String的假设,两者之间的区别归结为您使用:

self.secret.data(using: .utf8)!

将直接执行到底层字节的转换,而不是将每个字符对转换为相应的字节,如:

secret.decode('hex')

在Python 2中做

据我所知,在Swift标准库中没有一个函数来做这个转换,但是你可以这样做:

func bytes(fromHex input: String) -> Data {
var result = Data()
var byte: UInt8 = 0 
for (index, character) in input.enumerated() {
let codeUnit = character.utf8[character.utf8.startIndex]
var nibble: UInt8 = 0 
switch codeUnit {
case 0x30..<0x3a:
nibble = codeUnit - 0x30 
case 0x61..<0x67:
nibble = codeUnit - 0x57
default:
break
}   
if index % 2 == 0 { 
byte |= (nibble << 4)
} else {
byte |= nibble
result.append(contentsOf: [byte])
byte = 0 
}   
}
return result
}

,然后你的代码会变成:

let key = SymmetricKey(data: bytes(fromHex: self.secret))
let hexData = HMAC<SHA256>.authenticationCode(for: datastring.data(using: .utf8)!, using: key)
let signature = Data(hexData).map { String(format: "%02hhx", $0) }.joined()

最新更新