如何使用C#加密另一个程序?

时间:2011-06-11 03:24:09

标签: c# encryption

所以,在Visual C#.NET中,我希望能够以某种方式获取程序(通过打开的文件对话框),然后以某种方式获取该程序的字节并加密字节,以便稍后执行。 / p>

我该怎么做?我如何使用Visual C#.NET加密,然后解密一个程序?

1 个答案:

答案 0 :(得分:2)

This answer向您展示了如何执行字节数组。一个警告,这可能会导致病毒扫描程序出现问题,因为它在恶意软件中很常见。

如果您不想从内存中执行,我会举例说明如何加密存储然后解密并运行可执行文件。

 public class FileEncryptRunner
 {
    Byte[] key = ASCIIEncoding.ASCII.GetBytes("thisisakeyzzzzzz");
    Byte[] IV = ASCIIEncoding.ASCII.GetBytes("thisisadeltazzzz");

    public void SaveEncryptedFile(string sourceFileName)
    {
       using (FileStream fStream = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read, FileShare.Read),
              outFStream = new FileStream(Environment.SpecialFolder.MyDocuments+"test.crp", FileMode.Create))
       {
          Rijndael RijndaelAlg = Rijndael.Create();
          using (CryptoStream cStream = new CryptoStream(outFStream, RijndaelAlg.CreateEncryptor(key, IV), CryptoStreamMode.Write))
          {
              StreamWriter sWriter = new StreamWriter(cStream);
              fStream.CopyTo(cStream);
          }
       }
    }

    public void ExecuteEncrypted()
    {
       using (FileStream fStream = new FileStream(Environment.SpecialFolder.MyDocuments + "test.crp", FileMode.Open, FileAccess.Read, FileShare.Read),
              outFStream = new FileStream(Environment.SpecialFolder.MyDocuments + "crpTemp.exe", FileMode.Create))
       {
          Rijndael RijndaelAlg = Rijndael.Create();
          using (CryptoStream cStream = new CryptoStream(fStream, RijndaelAlg.CreateDecryptor(key, IV), CryptoStreamMode.Read))
          {   //Here you have a choice. If you want it to only ever exist decrypted in memory then you have to use the method in
              // the linked answer.
              //If you want to run it from a file than it's easy and you save the file and run it, this is simple.                                               
              cStream.CopyTo(outFStream);
          }
       }
       Process.Start(Environment.SpecialFolder.MyDocuments + "crpTemp.exe");
    }
 }