我有哈希二进制数据的问题。我需要做一个位于服务器上的PDF文件的SHA-256哈希。我是这样做的:
<cfset t01= getTickCount()>
<cfhttp
name="inv1"
method="get"
getAsBinary="yes"
url="http://url.to.pdf.com/INVOICEXY.pdf"
result="inv"
/>
<cfset t02= getTickCount()>
<cfoutput>
<cfdump var="#inv.Filecontent#" />
CFHTTP: #t02 - t01# ms
</cfoutput>
<cfscript>
imageBinary = inv.Filecontent;
function hashBytes( bytes ){
// Get our instance of the digest algorithm that we'll use
// to hash the byte array.
var messageDigest = createObject( "java", "java.security.MessageDigest" ).getInstance("SHA-256");
// Get the digest for the given byte array. This returns the
// digest in byte-array format.
var digest = messageDigest.digest( bytes );
// Now that we have our digested byte array (as another byte
// array), we have to convert that into a HEX string. For
// this, we'll need a HEX buffer.
writeDump(digest);
var hexBuffer = [];
// Each integer in the byte digest needs to be converted into
// a HEX character (with possible leading zero).
for (i = 1 ; i <= arrayLen( bytes ) ; i++){
// Get only the last 8-bits of the integer.
var tail = bitAnd( 255, bytes[i] );
// Get the hex-encoding of the byte.
var hex = ucase( formatBaseN( tail, 16 ) );
// In order to make sure that all of the HEX characters
// are two-digits, we have to prepend a zero for any
// value that was originall LTE to 16 - the largest value
// that won't result in two HEX characters.
arrayAppend(
hexBuffer,
(tail <= 16 ? ("0" & hex) : hex)
);
}
// Return the flattened character buffer.
return( arrayToList( hexBuffer, "" ) );
}
imageHash = hashBytes( imageBinary );
// Create an instance of our DigestUtils class - this class
// simplifies some of the operations we just saw in the
// MessageDigest class above, turning them into simple,
// one-line calls.
writeOutput( "Fingerprint:SHA " & imageHash );
函数hashBytes
来自Ben Nadel。我从这个函数得到的输出是一个由53760个字符组成的巨大混乱。我不知道自己做错了什么。
我也试过这个:
<cfscript>
imageBinary = inv.Filecontent;
digestUtils = createObject(
"java",
"org.apache.commons.codec.digest.DigestUtils"
);
// Get the hash of the byte array using our hashBytes() function
// which dips down into the Java layer directly.
imageHash = ucase( digestUtils.sha256Hex( imageBinary ) );
// Output the image "fingerprint".
writeOutput( "Fingerprint: " & imageHash );
</cfscript>
我收到错误
未找到sha256Hex方法
虽然我在commons-codec-1.8.jar
文件夹中有wwwroot\WEB-INF\lib
,但该文件夹应包含DigestUtils的版本,包括sha256Hex()
非常感谢!
修改
我解决了chars长期回归的问题。这是一个可怕的错误。在Ben Nadel的原始代码中,这行代码for (var byte in digest){...
在Coldfusion 9中不起作用。所以我将其更改为:for (i = 1 ; i <= arrayLen( bytes ) ; i++){...
而不是:for (i = 1 ; i <= arrayLen( digest ) ; i++){...
和{{1转到var tail = bitAnd( 255, bytes[i] );