Converting Coldfusion encryption code to C#

前端 未结 1 1596
醉梦人生
醉梦人生 2021-01-19 16:27

I have a Coldfusion page that includes a section of code that encrypts a variable like this:




        
1条回答
  •  醉梦人生
    2021-01-19 16:53

    You might want to try the BouncyCastle C# API. I ran a few tests, for POC, and it seemed to produce the same results as your CF code.

    A few things to keep in mind: If you read Strong Encryption in ColdFusion it explains that ColdFusion uses ECB mode and PKCS5Padding by default. So when specifying the shorthand Blowfish, you are actually saying use Blowfish/ECB/PKCS5Padding. In order to duplicate the encryption in C# (or any language), you must to use those same settings.

    There does not seem to be a lot of documentation for the C# port, but from what I can tell the BlowfishEngine defaults to ECB mode. So if you wrap it in a PaddedBufferedBlockCipher the result should be PKCS5 padded. That should give you the same result as your CF code:

        byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(userIDString);
        byte[] keyBytes = System.Convert.FromBase64String(keyInBase64);
    
        // initialize for ECB mode and PKCS5/PKCS7 padding
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new BlowfishEngine());
        KeyParameter param = new KeyParameter(keyBytes);
        cipher.Init(true, param);
    
        // encrypt and encode as base64
        byte[] encryptedBytes =  cipher.DoFinal(inputBytes);
        string idBase64 = System.Convert.ToBase64String(encryptedBytes);
    

    NB: I am not an expert on encryption, but will say that use of "ECB" mode is discouraged. See wiki for a good illustration of why. So you should seriously consider choosing a different mode.

    0 讨论(0)
提交回复
热议问题