将C#转换为ColdFusion

将C#转换为ColdFusion,coldfusion,coldfusion-9,sha1,hmac,coldfusion-11,Coldfusion,Coldfusion 9,Sha1,Hmac,Coldfusion 11,我没有使用C#的经验,我想知道是否有人可以帮助将这个C#代码片段转换为ColdFusion string inputString = "abccde"; string securityKey = "abcdefghijk..."; // Convert security key into ASCII bytes using utf8 encoding byte[] securityKeyBytes = UTF8Encoding.ASCII.GetBytes(securityKey); //

我没有使用C#的经验,我想知道是否有人可以帮助将这个C#代码片段转换为ColdFusion

string inputString = "abccde";
string securityKey = "abcdefghijk...";

// Convert security key into ASCII bytes using utf8 encoding
byte[] securityKeyBytes = UTF8Encoding.ASCII.GetBytes(securityKey);

// Create an HMACSHA1 hashing object that has been seeded with the security key bytes
HMACSHA1 hasher = new HMACSHA1(securityKeyBytes);

// Convert input string into ASCII bytes using utf8 encoding
byte[] inputBytes = UTF8Encoding.ASCII.GetBytes(inputString.ToCharArray());

// Compute the has value
byte[] hash = hasher.ComputeHash(inputBytes);

// Convert back to a base 64 string
string securityToken = Convert.ToBase64String(hash);

return securityToken;
我在stackOverFlow上找到了,这里是我到目前为止所拥有的。我走对方向了吗?任何见解都将不胜感激

<cffunction name="CFHMAC" output="false" returntype="string">
  <cfargument name="signMsg" type="string" required="true" />
  <cfargument name="signKey" type="string" required="true" />
  <cfset var key = createObject("java", "javax.crypto.spec.SecretKeySpec").init(signKey.getBytes(), "HmacSHA1") />
  <cfset var mac = createObject("java", "javax.crypto.Mac").getInstance("HmacSHA1") />
  <cfset mac.init(key) />
  <cfreturn toBase64(mac.doFinal(signMsg.getBytes())) />
</cffunction>

<cfset signMsg= "abccde">
<cfset signatureString = "abcdefghijk...">
<cfset result = CFHMAC(signMsg=signMsg, signKey=signatureString) />
<cfdump var="#result#" />

(从注释中展开)

CF11已经内置了一个UDF,因此您可能不需要该UDF。我建议试一试。请注意,C代码使用:

ASCII字符限制为最低128个Unicode字符, 从U+0000到U+007F

请注意,ASCII编码有一个第8位的歧义,可以允许 恶意使用,但UTF-8编码消除了关于第8个字符的歧义 一点它使用替换回退来替换它使用的每个字符串 无法编码,并且每个无法解码的字节都带有问号 (“?”)字符

假设您需要保持与其他应用程序的兼容性,并且必须保持相同的编码,UTF8Encoding.ASCII应该与CF/Java中的“US-ASCII”编码相对应,但要进行一些测试以验证对无效字符的处理。如果您可以灵活地更改编码,我建议您改用UTF-8。请记住,CF函数始终返回十六进制。如果需要base64字符串,则必须使用

示例:

<!--- Only required when hard coding UTF8 characters into a script --->
<cfprocessingdirective pageEncoding="utf-8">
<cfset message = "Pi π and Sigma Σ.">
<cfset key = "abcdefghijk">
<cfset hexHash = hmac(message, key, "HMACSHA1", "US-ASCII")>
<cfset base64Hash = binaryEncode(binaryDecode(hexHash, "hex"), "base64")>
<cfdump var="#base64Hash#">
HMACSHA1 = J2AZf+zhrebIA/tK3i5PYb4b/Fo= 

关于:在提取字符串的字节时,要非常小心编码。正如我在评论中指出的,最好避免使用
getBytes()
,因为它采用默认编码,不管是什么。这意味着它可能并不总是返回所需的结果,并且在不同的jvm之间可能会有所不同。相反,最好总是显式地提供一个字符集,即
getBytes(“UTF-8”)
getBytes(“US-ASCII”)
,等等。

感谢您的回复,Leigh,我回家后会尝试您的建议。因为不是每个人都阅读注释,所以我决定只修复该UDF以避免将来的编码问题;-)嗨,Leigh,我真的很感谢您的详细解释和示例!这给了我一个很好的起点。