C#使用RSA加密解密文件
本文实例为大家分享了C#使用RSA加密解密文件的具体代码,供大家参考,具体内容如下
加密代码:
//加密代码,注意会覆盖原文件,里面有我的公钥,你要用时记得覆盖我的公钥 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>"); //导入密钥 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); } //加密 f.Seek(0, SeekOrigin.Begin); foreach(byte[] d in con) { f.Write(d, 0, d.Length); } f.Close(); return true; }
解密代码:
//解密代码,覆盖原文件,返回值表示是否解密成功 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); } //解密 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; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)