如何在设备上加密,在C#中解密(使用3DES)

问题描述:

大家好,
我正在用C/C ++对设备(MPOS)进行编程,我需要通过TCP/IP将加密的数据发送到用C#编写的套接字服务器.

问题:
加密数据(HelloWorld)并将其传输到服务器后,我总是收到消息"Bad Data"的异常.

直接在设备上加密:

Hi all,
I''m programming a device (MPOS) in C/C++ and I need to send encrypted data via TCP/IP to a socket server written in C#.

Problem:
After encrypting the data (HelloWorld) and transmitting it to the server, I always get an exception with the message "Bad Data".

Encrypting on the device is straight forward:

DoEncryption((char*)secBuffer,length,_3DES_ENCRYPTION,key);



从C#方面,我正在使用通用对称算法助手.
(通用SymmetricAlgorithm帮助器 [



From the C# side, I''m using the Generic Symmetric Algorithm Helper.
(Generic SymmetricAlgorithm Helper[^]).

var keyString = "012345678901234567891234";
var key = Encoding.UTF8.GetBytes(keyString);
var sec = new Utilities.Crypto.SymmetricCryptography<TripleDESCryptoServiceProvider>(key, null);
//read encrypted data. i've saved it to a file.
var d1 = File.ReadAllBytes(@"c:\raw.txt");
var dec2 = sec.Decrypt(enc2); //always gives me "Bad Data"



一方面,以上C加密中未指定IV.我修改了SymmetricCryptography的构造函数以自动生成IV.



For one thing, no IV is specified in the C encryption above. I modified the SymmetricCryptography''s constructor a bit to auto generate the IV.

public SymmetricCryptography(byte[] key, byte[] iv)
{
    _key = key;
    if (iv == null)
    {
         _provider.Key = key;
         _provider.GenerateIV();
         iv = _provider.IV;
    }
    _iv = iv;
}



我该如何运作?

问候,
Richard



How do I get this to work?

Regards,
Richard

来自设备的加密数据似乎无效.
也许尝试在C#和设备上加密一个小的测试字符串,并检查结果是否相同.
It looks as though the encrypted data from the device is invalid.
Perhaps try encrypting a small test string in C# and on the device and check that the results are the same.