亲宝软件园·资讯

展开

C#使用RSA加密解密文件

人气:0

加密代码:

//加密代码,注意会覆盖原文件,里面有我的公钥,你要用时记得覆盖我的公钥
 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;
}
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论