Encrypting in Coldfusion and then decrypting in PHP

后端 未结 2 716
不知归路
不知归路 2021-01-18 05:43

I have a problem reproducing the same result generated in PHP vs Coldfusion.

In PHP encrypting this way:



        
2条回答
  •  醉话见心
    2021-01-18 06:07

    (Too long for comments)

    Artjom B. already provided the answer above. Artjom B. wrote

    The problem is the padding. The mcrypt extension of PHP only uses ZeroPadding [...] you either need to pad the plaintext in php [...] or use a different cipher in ColdFusion such as "DES/ECB/NoPadding". I recommend the former, because if you use NoPadding, the plaintext must already be a multiple of the block size.

    Unfortunately, it is difficult to produce a null character in CF. AFAIK, the only technique that works is to use URLDecode("%00"). If you cannot modify the PHP code as @Artjom B. suggested, you could try using the function below to pad the text in CF. Disclaimer: It is only lightly tested (CF10), but seemed to produce the same result as above.

    Update: Since the CF encrypt() function always interprets the plain text input as a UTF-8 string, you can also use charsetEncode(bytes, "utf-8") to create a null character from a single element byte array, ie charsetEncode( javacast("byte[]", [0] ), "utf-8")


    Example:

    Valor = nullPad("TESTE", 8);
    Key = "$224455@";
    result = Encrypt(Valor, ToBase64(Key), "DES/ECB/NoPadding", "BASE64");
    // Result: TzwRx5Bxoa0=
    WriteDump( "Encrypted Text = "& Result ); 
    

    Function:

    /*
       Pads a string, with null bytes, to a multiple of the given block size
    
       @param plainText - string to pad
       @param blockSize - pad string so it is a multiple of this size
       @param encoding - charset encoding of text
    */
    string function nullPad( string plainText, numeric blockSize, string encoding="UTF-8")
    {
        local.newText = arguments.plainText;
        local.bytes = charsetDecode(arguments.plainText, arguments.encoding);
        local.remain = arrayLen( local.bytes ) % arguments.blockSize;
    
        if (local.remain neq 0) 
        {
            local.padSize = arguments.blockSize - local.remain;
            local.newText &= repeatString( urlDecode("%00"), local.padSize );
        }
    
        return local.newText;
    }
    

提交回复
热议问题