用C ++加密并用C#解密

时间:2014-04-09 05:45:36

标签: c# c++ encryption

我必须加密C ++应用程序中的字段并在C#中将其解密。 对于加密,我使用的是openssl库。代码如下 -

  AES_KEY AESkey;
  string plainText = "kumar atul" ;
  unsigned char CBlock[1024]={0};
  unsigned char Key[16];

  char *MBlock = new char(plainText.size() ) ;
  int pLen = plainText.size();

  int plainTextLen=strlen((const char*) MBlock);
  strcpy((char *) MBlock, plainText.c_str() );
  for (int i=strlen((const char*) MBlock); i<16; i++)
  {
    MBlock[i] = 0;
  }
  unsigned char ckey[] =  { 200, 5, 78, 232, 9, 6, 0, 4, 200, 5, 78, 232, 9, 6, 0, 4 };
  AES_set_encrypt_key((const unsigned char *) ckey, 128, &AESkey);
  unsigned char ivec[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5 };
  int num = 0 ;
  AES_cfb128_encrypt( (const unsigned char *) MBlock, CBlock, 16, &AESkey, ivec, &num, AES_ENCRYPT) ;
  std::string str(( char *) CBlock);

我在C#中编写了一些程序来将相同的字符串加密到相同的加密值,但它们没有用。

请帮忙。 提前谢谢。

编辑1:

我无法在c ++中找到用base64编码加密的方法。 另外,

要加密的C#代码:

        private byte[] DESKey = { 200, 5, 78, 232, 9, 6, 0, 4, 200, 5, 78, 232, 9, 6, 0, 4 };
        private byte[] DESInitializationVector = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5 };


        public  string Encrypt(string value)
        {            
            using (var cryptoProvider = new AesManaged())
            using (var memoryStream = new MemoryStream())
            using (var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(DESKey, DESInitializationVector), CryptoStreamMode.Write))
            using (var writer = new StreamWriter(cryptoStream))
            {
                writer.Write(value);
                writer.Flush();
                cryptoStream.FlushFinalBlock();
                writer.Flush();
                return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
            }
        }

0 个答案:

没有答案