ColdFusion 散列

ColdFusion Hash

我正在尝试使用此公式创建密码摘要以获取以下变量,但我的代码不匹配。不确定我做错了什么,但我会在需要帮助时承认。希望有人能提供帮助。

ColdFusion 代码:

<cfSet PW = "AMADEUS">
<cfSet TS = "2015-09-30T14:12:15Z">
<cfSet NONCE = "secretnonce10111"> 
<cfDump var="#ToBase64(Hash(NONCE & TS & Hash(PW,'SHA-1'),'SHA-1'))#">

我的代码输出:

Njk0MEY3MDc0NUYyOEE1MDMwRURGRkNGNTVGOTcyMUI4OUMxM0U0Qg==

我显然做错了什么,但对于我的生活无法弄清楚是什么。任何人?布勒?

散列的有趣之处在于,即使您从正确的字符串开始,如果这些字符串 combined/encoded/decoded 不正确,结果仍然可能是完全错误的。

最大的问题是这些函数中的大多数实际上都使用输入字符串的 二进制 表示形式。所以这些字符串的解码方式有很大的不同。请注意,同一个字符串在解码为 UTF-8 与十六进制时会产生完全不同的二进制文件?这意味着 Hash、ToBase64 等的结果也将完全不同。

// Result: UTF-8: 65-65-68-69
writeOutput("<br>UTF-8: "& arrayToList(charsetDecode("AADE", "UTF-8"), "-"));

// Result:  HEX: -86--34
writeOutput("<br>HEX: "& arrayToList(binaryDecode("AADE", "HEX"), "-"));

可能的解决方案:

当前代码的问题是 ToBase64 assumes the input string is encoded as UTF-8. Whereas Hash() actually returns a hexadecimal string. So ToBase64() decodes it incorrectly. Instead, use binaryDecode and binaryEncode 将哈希值从十六进制转换为 base64:

resultAsHex = Hash( NONCE & TS & Hash(PW,"SHA-1"), "SHA-1");
resultAsBase64 = binaryEncode(binaryDecode(resultAsHex, "HEX"), "base64");
writeDump(resultAsBase64);

更可靠的解决方案:

话虽如此,但在字符串连接和哈希处理时要非常小心。如it does not always yield the expected results. Without knowing more about this specific API, I cannot be completely certain what it expects. However, it is usually safer to only work with the binary values. Unfortunately, CF's ArrayAppend() function lacks support for binary arrays, but you can easily use Apache's ArrayUtilsclass,这是与CF捆绑在一起的。

ArrayUtils = createObject("java", "org.apache.commons.lang.ArrayUtils");

// Combine binary of NONCE + TS
nonceBytes = charsetDecode(NONCE, "UTF-8");
timeBytes = charsetDecode(TS, "UTF-8");
combinedBytes = ArrayUtils.addAll(nonceBytes, timeBytes);

// Combine with binary of SECRET 
secretBytes = binaryDecode( Hash(PW,"SHA-1"), "HEX");
combinedBytes = ArrayUtils.addAll(combinedBytes, secretBytes);

// Finally, HASH the binary and convert to base64
resultAsHex = hash(combinedBytes, "SHA-1");
resultAsBase64 = binaryEncode(binaryDecode(resultAsHex, "hex"), "base64");

writeDump(resultAsBase64);