C# Encrypts and decrypts files using RSA

Time:2019-10-5

In this paper, we share the specific code of C# using RSA to encrypt and decrypt files for your reference. The details are as follows.

Encryption code:

// Encryption code, note that it will overwrite the original file, which contains my public key, you need to remember to overwrite my public key when you use it.
 private bool  encryptFile(string filename)
    {
      FileStream f;
      try
      {
        f = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
      }
      catch
      {
        return false;
      }
      Random r = new Random();
      Thread.Sleep(10*r.Next(3,8));
      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
      rsa.FromXmlString("<RSAKeyValue><Modulus>w7nNT8U7kwTw8UqLk0lROxmfTRZnQrMH1QrNyUGtoeAJ3w+iH08j+h83cPWxwPoxpXm1cgCLFWtCFWY1rkQDCCLxJhUIwYTbGKTg9h0uUVfNxGiNji7dcHShd01UYpZjHCwOar1wjJD4vJqVJCk++59UUMhE9IUATuSUVpRy1bE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>");
      // Import key
      byte[] data = new byte[16];
      ArrayList con = new ArrayList();
      while(f.Read(data, 0, 16)!=0)
      {

        byte[] result = rsa.Encrypt(data,false);
        //Thread.Sleep(10 * r.Next(2, 7));
        con.Add(result);
      }
      // encryption
      f.Seek(0, SeekOrigin.Begin);
      foreach(byte[] d in con)
      {
        f.Write(d, 0, d.Length);
      }

      f.Close();
      return true;
}

Decrypt code:

// Decrypt code, overwrite original file, return value indicates whether decryption is successful
 private bool decryptFile(string filename,string key)
    {
      FileStream f;
      try
      {
        f = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
      }
      catch
      {
        return false;
      }
      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
      try
      {
        rsa.FromXmlString(key);
      }
      catch
      {
        return false;
      }

      byte[] data = new byte[128];
      ArrayList con = new ArrayList();
      while (f.Read(data, 0, 128) != 0)
      {
        byte[] result;
        try
        {
          result = rsa.Decrypt(data, false);
        }
        catch
        {
          return false;
        }
        con.Add(result);
      }
      // decryption
      f.SetLength(con.Count * 16);
      f.Seek(0, SeekOrigin.Begin);
      foreach (byte[] d in con)
      {
        f.Write(d, 0, d.Length);
      }
      f.Close();
      return true;
}

The above is the whole content of this article. I hope it will be helpful to everyone’s study, and I hope you will support developpaer more.