TripleDES in CFB mode, C# and Crypto++ differs

旧时模样 提交于 2019-12-01 21:46:32

The FeedBackSize you have changed, relates to the CFB mode of operation (msdn documentation). Therefore you should also check that Feedback size in C++ and C# are the same.

I believe that your bug could be maligned BlockSizes between the C++ code and the C# code. Have you tried setting BlockSize = 8 in the C# implementation?

These are not correct:

CFB_FIPS_Mode<DES_EDE3>::Encryption enc;
enc.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv));

sizeof(key) and sizeof(iv) returns the size of the pointers, not the size of the security parameters. You should use this instead:

enc.SetKeyWithIV(key, DES_EDE3::DEFAULT_KEYLENGTH, iv, DES_EDE3::BLOCKSIZE);

If it works for .Net, then you should prefer to increase the feedback size for libraries like Mcrypt and .Net; and not reduce the feedback size in Crypto++. That's because some modes lose security when the feedback size is not the full block size.

I don't know if this will work with .Net, but its something you should consider or try:

public FibxCrypt()
{
    _cryptoAlgo = new TripleDESCryptoServiceProvider();
    _cryptoAlgo.Key = _key;
    _cryptoAlgo.IV = _iv;
    _cryptoAlgo.Mode = CipherMode.CFB;
    _cryptoAlgo.Padding = PaddingMode.Zeros;

    // Add this:
   _cryptoAlgo.FeedbackSize = _cryptoAlgo.BlockSize;
}

If you can't adjust the feedback size in .Net, then here's how to change feedback size in Crypto++. You setup a AlgorithmParameters to hold the feedback size parameter, and then you call SetKey with the additional parameters:

void *CryptData(BYTE *bDataIn, LONG lIn, LONG *lOut, byte* key, byte* iv)
{
    AlgorithmParameters params = MakeParameters(Name::FeedbackSize(), 1 /*8-bits*/)
                                               (Name::IV(), ConstByteArrayParameter(iv, DES_EDE3::BLOCKSIZE));
    CFB_FIPS_Mode<DES_EDE3>::Encryption enc;
    enc.SetKey(key, 24, DES_EDE3::DEFAULT_KEYLENGTH);

    ...
}

Its not clear to me if CFB mode operating in FIPS mode allows such a small feedback size. If it throws an exception, then you will need to use just CFB_Mode.

AlgorithmParameters may look a little odd because of the operator() overload. You can read about it at NameValuePairs on the Crypto++ wiki. Other wiki pages of interest are TripleDES and CFB Mode.

----

Another thing to watch out for is text encoding. It usually causes interoperability issues in .Net and Java due to UTF-16. UTF-8 and ASCII cause the least amount of problems. You should be OK since you encoding = new UTF8Encoding().

But if things still don't work for you, then you a byte message that is not encoded or interpreted. For example, use this in both .Net and Crypto++:

byte msg[4] = { 0x01, 0x02, 0x03, 0x04 };

The four bytes are not interpreted, so it side steps encoding issues.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!