Next Page

1

Previous Page

Thread: Base64

Created on: 09/04/08 12:03 PM

Replies: 1

jbliss


New Member


Joined: 09/04/08

Posts: 2

Base64
09/04/08 12:03 PM

So, Ray helped me solve this via email and I thought I'd post the solution here for the good of the order:

The point of this exercise is that I have a table with a primary key that's a standard Microsoft GUID (36 hex characters long). This is fine but there's one remote "place" I need to store references to this primary key (via webservice) that'll only accept a max of 25 characters. So by base64'ing the GUID, I'll be able to use Microsoft's GUID and not break the webservice.

Problem is: CF's ToBase64 chokes on the decimal representation of a GUID (it's too big). So, luckily, I found this http://www.fusebox.org/forums/messageview.cfm?catid=21&threadid=5075 and used it to create this:

<cffunction access="public" name="HexToBase64" output="yes" returntype="string">
	<cfargument name="Hex" type="string" required="yes">
	<cfset outStream = CreateObject("java", "java.io.ByteArrayOutputStream").init()>
    <cfset inputLength = Len(Hex)>
    <cfset outputString = "">
    <cfset i = 0>
    <cfset ch = "">
    <cfif inputLength mod 2 neq 0>
        <cfset Hex = "0" & Hex>
    </cfif>
    <cfloop from="1" to="#inputLength#" index="i" step="2">
        <cfset ch = Mid(Hex, i, 2)>
        <cfset outStream.write(javacast("int", InputBaseN(ch, 16)))>
    </cfloop>
    <cfset outStream.flush()>
    <cfset outStream.close()>
    <cfreturn ToBase64(outStream.toByteArray())>
</cffunction>

Sweet. Then Ray helped me noodle the return voyage. (Unfortunately, CF does not have "FromBase64" or equivalent.)

<cffunction access="public" name="Base64ToHex" output="yes" returntype="string">
	<cfargument name="Base64" type="string" required="yes">
	<cfset aBinary = ToBinary(Base64)>
    <cfset Hex = "">
    <cfloop index="i" from="1" to="#ArrayLen(aBinary)#">
        <cfset Hex = Hex & FormatBaseN(BitAnd(aBinary[i], 255), 16)>
    </cfloop>
    <cfreturn Hex>
</cffunction>

Hope this saves someone some time someday.

Link | Top | Bottom

jbliss


New Member


Joined: 09/04/08

Posts: 2

RE: Base64
09/04/08 12:19 PM

Addendum: Microsoft GUID likes this format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx so, near the top of HexToBase64, I added:

<cfset Hex = Replace(Hex, "-", "", "ALL")>

...and near the bottom of Base64ToHex, I added:

<cfset Hex = Insert("-", Hex, 21)>
<cfset Hex = Insert("-", Hex, 17)>
<cfset Hex = Insert("-", Hex, 13)>
<cfset Hex = Insert("-", Hex, 9)>

Link | Top | Bottom

Next Page

1

Previous Page

New Post

Please login to post a response.