跨语言HMAC / SHA256 / Base64的问题

时间:2015-05-13 23:21:59

标签: javascript node.js swift base64 hmac

我使用node.js脚本为azure documentDB创建签名 - 简化版本是(结果在底部): -

var crypto = require("crypto");

var masterKey = "ABCDE"
var key = new Buffer(masterKey, "base64");
var signature = crypto.createHmac("sha256", key).update("FGHIJ").digest("base64");

console.log("\n\n"+signature)

// RNkID54/1h1H9p3NWPeRA0mOW2L0c0HUJGTTY2GPbDo=

这是有效的,并且我需要它。我试图在Swift中用CommonCrypto做同样的事情

let keyString = "ABCDE"
let body = "FGHIJ"

let utf8data = keyString.dataUsingEncoding(NSUTF8StringEncoding)
let key = utf8data!.base64EncodedDataWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

let str = body.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = body.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)

CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), key.bytes, key.length, str!, strLen, result);

var hmacData = NSData(bytes: result, length: digestLen)
var hmacBase64 = hmacData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

result.dealloc(digestLen)

let signature = String(hmacBase64)

let test = "RNkID54/1h1H9p3NWPeRA0mOW2L0c0HUJGTTY2GPbDo="
XCTAssert(test == signature, "Pass")

但它会返回完全不同的结果。如果我将masterKey直接传递给javascript hmac,并将其作为字符串传递给Swift中的CCHmac方法,那么一切正常;所以它似乎与找到相当于此的东西有关: -

var key = new Buffer(masterKey, "base64");

思想?

更多信息 - 这: -

let keyString = "ABCDE"
let body = "FGHIJ"

let keyData = keyString.dataUsingEncoding(NSUTF8StringEncoding)! // .base64EncodedDataWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let bodyData = body.dataUsingEncoding(NSUTF8StringEncoding)!

let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)

CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), keyData.bytes, keyData.length, bodyData.bytes, bodyData.length, result);

var hmacData = NSData(bytes: result, length: digestLen)
var hmacBase64 = hmacData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

result.dealloc(digestLen)

let signature = String(hmacBase64)

let test = "FA372zbobgpTLI5cQWh5YFiFwkNhMI8womX4Cvw68YE=" // "RNkID54/1h1H9p3NWPeRA0mOW2L0c0HUJGTTY2GPbDo="
XCTAssert(test == signature, "Pass")

产生与此相同的结果: -

var crypto = require("crypto");

var masterKey = "ABCDE"
var signature = crypto.createHmac("sha256", masterKey).update("FGHIJ").digest("base64");

console.log("\n\n"+signature)

// FA372zbobgpTLI5cQWh5YFiFwkNhMI8womX4Cvw68YE=

0 个答案:

没有答案