ColdFusion hash_hmac256 output format / encoding - coldfusion

I have this script to output an hash_hmac similar function in CFML:
<cfprocessingdirective pageencoding = "iso-8859-1">
<cfset msg = "AgostinoSqueglinPiccolinMonachin">
<cfset jMsg = JavaCast("string",msg).getBytes() />
<cfset jKey = JavaCast("string","cicciolin").getBytes() />
<cfset key = createObject("java","javax.crypto.spec.SecretKeySpec") />
<cfset mac = createObject("java","javax.crypto.Mac") />
<!--- this line had to be changed to the 256 version --->
<cfset key = key.init(jKey,"hmacSHA256") />
<cfset mac = mac.getInstance(key.getAlgorithm()) />
<cfset mac.init(key) />
<cfset mac.update(jMsg) />
<cfset cc = mac.doFinal()>
<cfset strBase64Value = ToString( cc,"Utf-8" ) />
<cfscript>
writeDump(msg);
writeDump(strBase64Value);
</cfscript>
This should output the same result as this php:
<?php
$uu = hash_hmac('sha256', "AgostinoSqueglinPiccolinMonachin", "cicciolin", true);
echo $uu;
?>
But I got this different result, due probably to an format error:
ColdFusion : �GK�襍}Ÿ�}��B�}9w�(���u�m�
PHP: ÐGKÒè¥}Ÿ»}©ì¬B§}9w´(«æüu§mÃ
Seems some characters does not output in the correct way.
How can I solve this?
UPDATE:
The solution works perfectly, but there are other problem if I try to encode new line:
for example
Php:
$sign = "GET\n" . "agostinsqueglin" . "". "piccolin";
$uu = base64_encode(hash_hmac('sha256', $sign, "cicciolin", true));
If I try with:
sign = "GET#chr(13)##chr(10)#" & "agostinsqueglin" & "" & "piccolin";
I got two different results.
This is due to the way coldfusion handling "\n" newline...

The code you've provided is a little more long-winded than it needs to be, and ... well, here's an improved version:
<cfscript>
msg = "AgostinoSqueglinPiccolinMonachin";
key = "cicciolin";
algorithm = "HmacSHA256";
encoding = "iso-8859-1";
secret = createObject('java',"javax.crypto.spec.SecretKeySpec").init( charsetDecode(key,encoding) , algorithm );
mac = createObject('java',"javax.crypto.Mac").getInstance(algorithm);
mac.init(secret);
digest = mac.doFinal( charsetDecode(msg,encoding) );
writeDump( msg );
writeDump( toString(digest,encoding) );
</cfscript>
This is based on the answer and comments here: Calculate HMAC-SHA256 digest in ColdFusion using Java
Obviously for regular use it should be wrapped up in a suitable function.

It looks like you're trying to output a UTF-8 string while your processingdirective is set to iso-8859-1. Try changing it:
<cfprocessingdirective pageencoding = "UTF-8">

Related

cfinvoke with two different methods

I have two cfinvoke, I need to use them in one cfm
<cfinvoke component="cfc/queries" method="getProjects" searchString="#Session.Auth.pref_name#" view="#Session.Auth.view#" returnvariable="Projects">
<cfinvoke component="cfc/queries" method="projectDetails" searchString="#URL.id#" projectsuffix="#URL.suffix#" returnvariable="Details">
to return two queries, but when I coding like this way it's not working.
I'm still new to the ColdFusion and I don't know how to fix that.
Since both functions are in the same CFC, you wouldn't want to use cfinvoke since it recreates the object each time it's called. Instead, use a new or a createObject().
<cfset queries = new location.to.cfc.queriesCFC()>
Then you can just reference the functions.
<cfset Projects =
queries.getProjects(
searchString=session.Auth.pref_name,
view = session.Auth.view
)
>
<cfset Details =
queries.projectDetails(
searchString=url.id,
projectsuffix=url.suffix
)
>
You may want to sanitize url.id and url.suffix before you pass them through. This will help with injection issues.
What does getProjects() do?
We can write like as below,
<!--- Object creation --->
<cfset query = CreateObject("component", "cfc.queries")/>
<!--- Function call --->
<cfset Projects = query.getProjects( searchString = session.Auth.pref_name, view = session.Auth.view )>
<cfset Details = query.projectDetails( searchString = session.Auth.pref_name, view = session.Auth.view )>

Base64 decoding error in coldfusion

I'm trying to decode a base64 string with #ToString( ToBinary( stringToDecode ) )# and coldfusion gives an error saying the parameter must be a base-64 encoded string. The string comes from a third party, and is supposed to be a pdf file. Here is a part of it:
JVBERi0xLjUKJeLjz9MKMSAwIG9iago8PC9UeXBlL1hPYmplY3QvUmVzb3VyY2VzPDw+Pi9TdWJ0 eXBlL0Zvcm0vQkJveFswIDAgMTUuNDQgMTUuNDZdL01hdHJpeCBbMSAwIDAgMSAwIDBdL0xlbmd0 aCAyMi9Gb3JtVHlwZSAxL0ZpbHRlci9GbGF0ZURlY29kZT4+c3RyZWFtCk9lHxbaEDXZpIO1A/Gj mGuxQdW3qkgKZW5kc3RyZWFtCmVuZG9iagoyIDAgb2JqCjw8L1R5cGUvWE9iamVjdC9SZXNvdXJj ZXM8PD4+L1N1YnR5cGUvRm9ybS9CQm94WzAgMCAxNS40NCAxNS4xOV0vTWF0cml4IFsxIDAgMCAx IDAgMF0vTGVuZ3RoIDIyL0Zvcm1UeXBlIDEvRmlsdGVyL0ZsYXRlRGVjb2RlPj5zdHJlYW0KtDN8 NkUKYx04Gj8V9LfOboGvN9VRIgplbmRzdHJlYW0KZW5kb2JqCjMgMCBvYmoKPDwvVHlwZS9YT2Jq ZWN0L1Jlc291cmNlczw8Pj4vU3VidHlwZS9Gb3JtL0JCb3hbMCAwIDE1LjQ0IDE1LjcyXS9NYXRy aXggWzEgMCAwIDEgMCAwXS9MZW5ndGggMjIvRm9ybVR5cGUgMS9GaWx0ZXIvRmxhdGVEZWNvZGU+
What I had thought was the spaces were a problem, but I did a replace to replace all " " with "" and they are still in there. Is there something else I should be doing?
In my testing I can take a local pdf and convert it to a string to mimic the string you are getting from the API. I can then take it and convert it back to a PDF.
When I use the string you put above I cannot get it to work. Not sure if something is list from you pasting it here or not.
Here is my code, maybe you can alter it to use the string right from the api.
<cffile action="readbinary" file="#expandPath('./test.pdf')#" variable="thefile"/>
<cfset the_string = toString(theFile)/>
<cfscript>
patrick_string = ToBase64("JVBERi0xLjUKJeLjz9MKMSAwIG9iago8PC9UeXBlL1hPYmplY3QvUmVzb3VyY2VzPDw+Pi9TdWJ0 eXBlL0Zvcm0vQkJveFswIDAgMTUuNDQgMTUuNDZdL01hdHJpeCBbMSAwIDAgMSAwIDBdL0xlbmd0 aCAyMi9Gb3JtVHlwZSAxL0ZpbHRlci9GbGF0ZURlY29kZT4+c3RyZWFtCk9lHxbaEDXZpIO1A/Gj mGuxQdW3qkgKZW5kc3RyZWFtCmVuZG9iagoyIDAgb2JqCjw8L1R5cGUvWE9iamVjdC9SZXNvdXJj ZXM8PD4+L1N1YnR5cGUvRm9ybS9CQm94WzAgMCAxNS40NCAxNS4xOV0vTWF0cml4IFsxIDAgMCAx IDAgMF0vTGVuZ3RoIDIyL0Zvcm1UeXBlIDEvRmlsdGVyL0ZsYXRlRGVjb2RlPj5zdHJlYW0KtDN8 NkUKYx04Gj8V9LfOboGvN9VRIgplbmRzdHJlYW0KZW5kb2JqCjMgMCBvYmoKPDwvVHlwZS9YT2Jq ZWN0L1Jlc291cmNlczw8Pj4vU3VidHlwZS9Gb3JtL0JCb3hbMCAwIDE1LjQ0IDE1LjcyXS9NYXRy aXggWzEgMCAwIDEgMCAwXS9MZW5ndGggMjIvRm9ybVR5cGUgMS9GaWx0ZXIvRmxhdGVEZWNvZGU+");
string2 = toBinary(ToBase64(the_string));
binencode=BinaryEncode(string2, "Base64");
</cfscript>
<cffile action="write" file="#expandPath('./randy.pdf')#" output="#thefile#" addnewline="No" />
click
Updated Code:
<cffile action="readbinary" file="#expandPath('./test.pdf')#" variable="thefile"/>
<cfset the_string = toBase64(theFile)/>
<cfscript>
string2 = toBinary(the_string);
</cfscript>
<cffile action="write" file="#expandPath('./randy.pdf')#" output="#string2#" addnewline="No" />
click
Here's an updated cfscript way of doing it in case anyone is interested:
<cfscript>
// read the binary file and save it as a variable
myPdf = fileReadBinary( expandPath( "/test.pdf" ) );
// encode as base64
myPdf = toBase64( myPdf );
// output the base64 version to the browser
writedump( myPdf );
// convert back to binary
myPdf = toBinary( myPdf );
// write to a new PDF file
fileWrite( expandPath( "/new.pdf" ), myPdf );
</cfscript>

Some Functions seems to be not exist when creating new bucket or checking if bucket exists using OpenBD

I am using OpenBD and trying to check whether bucket exists or not on my S3 server, if it is not exist then, to create new bucket. Here's my code:
index.cfm
<cfset request.awsaccess = "zzzzawsaccesszzzz">
<cfset request.awskey = "zzzzzzzzawskeyzzzzzzzz">
<cfset request.datasource="tcs">
<cfset request.region="us-west-2">
<cfscript>
AmazonRegisterdatasource(datasource=request.datasource,awsaccess=request.awsaccess,awskey=request.awskey,region=request.region );
result = AmazonS3listbuckets( datasource=request.datasource );
WriteDump(result);
WriteOutput(result.bucket[1]);
</cfscript>
For the above code I am getting this output:
Now I am adding one more function AmazonS3createbucket(),
<cfscript>
result = AmazonS3createbucket( datasource=request.datasource, bucket="anyBucket" );
</cfscript>
For the above script I am getting error: that No such function exists - amazons3createbucket.. Here's the screenshot:
I am referring the OpenBD Manual to filter these function.
Also faced the same problem while using this functions also:
<cfscript>
result = AmazonS3bucketexists( datasource=request.datasource, bucket="anyBucket" );
</cfscript>
Have you tried using an alternate syntax?
<cfscript>
result = AmazonS3bucketexists(ArgumentCollection = {
datasource : request.datasource,
bucket : "anyBucket"
});
</cfscript>

Downloading large file in ColdFusion using CFHTTP

I'm trying to download a large (600MB) binary file to the server using CFHTTP on Coldfusion 8:
<cfhttp
method="get"
url="#fileURL#"
path="#filePath#"
file="#fileName#"
timeout="600"
getasbinary="auto"
>
It's working fine for smaller files (100something MB) but for the large one's I'm getting the Server 500 error: "java.lang.OutOfMemoryError: Java heap space".
The file is being downloaded from a Dropbox folder - so only available option is to use HTTP GET.
Does anyone have idea how to download it, so it wouldn't kill the server or timeout?
You can do this by calling Java from CF code. The buffered input and output stream classees are designed to hold onto chunks of data, rather than the whole thing, avoiding OutOfMemory errors.
getByteArray() is a helper method because there's not way to declare something like byte buf[]=new byte[1024]; in CF directly.
In the example change the source and destination variables.
Example
<cfset source = 'protocol://domain/path/to/file.ext'>
<cfset destination = getDirectoryFromPath(getCurrentTemplatePath()) & listlast(source, "/")>
<cffunction name="getByteArray" access="private" returnType="binary" output="no">
<cfargument name="size" type="numeric" required="true"/>
<cfset var emptyByteArray =
createObject("java", "java.io.ByteArrayOutputStream").init().toByteArray()/>
<cfset var byteClass = emptyByteArray.getClass().getComponentType()/>
<cfset var byteArray =
createObject("java","java.lang.reflect.Array").newInstance(byteClass, arguments.size)/>
<cfreturn byteArray/>
</cffunction>
<cfscript>
uri = createObject("java", "java.net.URL").init(source);
uis = uri.openStream();
bis = createObject("java", "java.io.BufferedInputStream").init(uis);
fos = createObject("java", "java.io.FileOutputStream").init(destination);
bos = createObject("java", "java.io.BufferedOutputStream").init(fos);
buffer = getByteArray(1024);
len = bis.read(buffer);
while(len > 0) {
bos.write(buffer,0,len);
len = bis.read(buffer);
}
bos.close();
bis.close();
fos.close();
uis.close();
</cfscript>
The problem is is that it's too large. ColdFusion reads the entire thing into memory before writing it to disk.
You'll be better off using some other method to get the file. wget can do http requests from a command-line. That with judicious use of CFEXECUTE is probably a good way to go.

How to use custom1,custom2,custom3,custom4 in <cfsearch> w/ Solr?

do custom1, custom2, custom3, custom4 attribute of <cfsearch> work with Solr? The documentation said they're only for Verity MATCHES operator. How to use customX with Solr in <cfsearch>?
Thanks
Yes, they do. Here is an example:
Building the collection
The strings are column names. For example 'keywords' is a valid column in the query "qIndex".
<cfindex collection = "#arguments.collectionName#"
action = "REFRESH"
type = "CUSTOM"
body = "Show_Name, Title"
key = "theKey"
custom1 = "Show_Description"
custom2 = "keywords"
custom3 = "Show_ID"
custom4 = "Asset_ID"
title = "Title"
query = "qIndex"
URLPath = "theURL" />
Searching the Collection
<!--- Populate the remaining attributes of the cfsearch tag --->
<cfif !structKeyExists(arguments, 'searchArgs')>
<cfset arguments.searchArgs = {
collection = arguments.collectionName
,criteria = "#arguments.term#"
,contextPassages = "1"
,contextBytes = "1024"
,suggestions = "always"
,status = "searchStatus" } />
</cfif>
<!--- Force the name of the result as its referenced only internally --->
<cfset arguments.searchArgs.name = 'qSearchResults' />
<!--- Try to search our collection using Solr --->
<cfsearch attributecollection="#arguments.searchArgs#" />