ColdFusion Zero Byte Padding Java 1.6 vs 1.7

时间:2013-12-06 23:46:49

标签: java encryption coldfusion java-7 java-6

<cfset var strB = createObject("java", "java.lang.StringBuilder")/>

<cfloop from=1 to=32 index="i">
    <cfset zeroPad = zeroPad & URLDecode("%00")/>
</cfloop>

<cfset strB.append(arguments.username)/>
<cfset strB.append(arguments.password)/>
<cfset strB.append(zeroPad)/>

<cfif strB.length() GT 32>
    <cfset key = strB.substring(0,32)/>
<cfelse>
    <cfset key = strB.toString()/>
</cfif>

生成的密钥用于AES加密。这是方法...

<cffunction name="aesEncrypt" returntype="string" output="no">

    <cfargument name="plainText" type="string" />
    <cfargument name="key" type="string" />

    <cfset var cipher = CreateObject("java", "javax.crypto.Cipher")/>
    <cfset var system = CreateObject("java", "java.lang.System")/>
    <cfset var secretkeyspec = CreateObject("java", "javax.crypto.spec.SecretKeySpec")/>
    <cfset var ivparamspec = CreateObject("java", "javax.crypto.spec.IvParameterSpec")/>
    <cfset var b64 = CreateObject("java", "org.apache.commons.codec.binary.Base64")/>

    <cfset var result = ""/>
    <cfset var keyBytes = getByteArray(32)/>
    <cfset var iv = getByteArray(16)/>
    <cfset var b = key.getBytes('UTF-8')/>

    <cfset var cipher = cipher.getInstance("AES/CBC/PKCS5Padding")/>

    <cftry>

    <cfset keyLen = len(b)/>
    <cfif keyLen gt len(keyBytes)>
        <cfset keyLen = len(keyBytes)/>
    </cfif>

    <cfset system.arraycopy(b, 0, keyBytes, 0, keyLen)/>
    <cfset system.arraycopy(b, 0, iv, 0, 16)/>

    <cfset keySpec = secretkeyspec.init(keyBytes, "AES")/>
    <cfset ivSpec = ivparamspec.init(iv)/>

    <cfset cipher.init(cipher.ENCRYPT_MODE, keySpec, ivSpec)/>

    <cfset results = cipher.doFinal(plainText.getBytes())/>

    <cfset result = binaryEncode(results, "Base64")/>

    <cfcatch type="any">
        <cfthrow message="#cfcatch.Message# (plainText:#plainText# key:#key#)"/>
    </cfcatch>

    </cftry>

    <cfreturn result/>

</cffunction>

<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>

在我的本地开发机器(Mac OS X Mavericks,Java 1.6)上,这很好用,我可以使用生成的密钥进行加密。但是,在我的生产环境(Windows Server 2008,Java 1.7)上,我收到错误“密钥大小无效”。两者的密钥大小显示为32,我感到很沮丧。

我目前正在更新我的本地开发机器以匹配服务器上的Java版本,但我仍然无法想到导致这种情况的简单类中的差异。

0 个答案:

没有答案