RC2加密算法在C#的应用

2024-02-17 10:58

本文主要是介绍RC2加密算法在C#的应用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 

using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace Curllion
{
 public class Crypt
 {
  /// <summary>
  /// 新建一个大小为10261B的文件,以便将加密数据写入固定大小的文件。
  /// </summary>
  /// <param name="filePath">文件保存的地址,包含文件名</param>
  public static void InitBinFile(string filePath)
  {
   byte[] tmp = new byte[10261];
   try  //创建文件流,将其内容全部写入0
   {
    System.IO.FileStream writeFileStream = new FileStream(filePath,
     System.IO.FileMode.Create,
     System.IO.FileAccess.Write,
     System.IO.FileShare.None,512,false);

    for(int i = 0 ;i< 10261;i++)
     tmp[i] = 0; 
    writeFileStream.Write(tmp,0,10261);
    writeFileStream.Flush();
    writeFileStream.Close();
   }
   catch(System.IO.IOException)
   {
    MessageBox.Show("文件操作错误!","错误!",MessageBoxButtons.OK,MessageBoxIcon.Error);
   }
  }
  /// <summary>
  /// 将文本数据加密后写入一个文件,其中,这个文件是用InitBinFile建立的,这个文件将被分成十块,
  /// 用来分别保存10组不同的数据,第一个byte位保留,第2位到第21位分别用来存放每块数据的长度,但
  /// 一个byte的取值为0-127,所以,用两个byte来存放一个长度。
  /// </summary>
  /// <param name="toEncryptText">要加密的文本</param>
  /// <param name="filePath">要写入的文件</param>
  /// <param name="dataIndex">写入第几块,取值为1--10</param>
  /// <returns>是否操作成功</returns>
  public static bool EncryptToFile(string toEncryptText,string filePath,int dataIndex)
  {
   bool r = false;
   if(dataIndex > 10 && dataIndex < 1)
   {
    MessageBox.Show("数据索引的取值范围在1至10之间!","错误!",
     MessageBoxButtons.OK,MessageBoxIcon.Error);
    return r;
   }
   byte[] encrypted;  
   //初始化向量
   byte[] key = {106,51,25,141,157,142,23,111,234,159,187,154,215,34,37,204};   
   //密匙
   byte[] IV = {135,186,133,136,184,149,153,144};
   //创建UTF-16 编码,用来在byte[]和string之间转换
   System.Text.UnicodeEncoding textConverter = new UnicodeEncoding();
   //创建RC2服务
      RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
   //打开要写入的文件,主要是为了保持原文件的内容不丢失
   System.IO.FileStream tmpFileStream= new FileStream(filePath,
    System.IO.FileMode.Open,
    System.IO.FileAccess.Read,
    System.IO.FileShare.None,1024,true);

   byte[] index = new byte[10261];
   //将读取的内容写到byte数组
   tmpFileStream.Read(index,0,10261);
   tmpFileStream.Close();
   //定义基本的加密转换运算
   System.Security.Cryptography.ICryptoTransform Encryptor = rc2CSP.CreateEncryptor(key,IV);
   System.IO.MemoryStream msEncrypt = new MemoryStream();
   //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。
   System.Security.Cryptography.CryptoStream csEncrypt = new CryptoStream(msEncrypt,
    Encryptor,CryptoStreamMode.Write);
   //将要加密的文本转换成UTF-16 编码,保存在tmp数组。
   byte[] tmp = textConverter.GetBytes(toEncryptText);
   //将tmp输入csEncrypt,将通过Encryptor来加密。
   csEncrypt.Write(tmp,0,tmp.Length);
   //输出到msEnctypt
   csEncrypt.FlushFinalBlock();
   //将流转成byte[]
   encrypted = msEncrypt.ToArray();
   if(encrypted.Length>1024)
   {
    MessageBox.Show("加密后,数据长度大于1KB,无法保存");
    return false;
   }
   //得到加密后数据的大小,将结果存在指定的位置。
   index[dataIndex*2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length/128));
   index[dataIndex*2]     = Convert.ToByte(Convert.ToString(encrypted.Length%128));
   //将加密后的结果写入index(覆盖)
   for(int i=0;i<encrypted.Length;i++)
    index[1024*(dataIndex-1)+21+i]=encrypted[i];
   //建立文件流
   tmpFileStream = new FileStream(filePath,
    System.IO.FileMode.Truncate,
    System.IO.FileAccess.Write,
    System.IO.FileShare.None,1024,true);
   //写文件
   tmpFileStream.Write(index,0,10261);
   tmpFileStream.Flush();
   r = true;
   tmpFileStream.Close();
   return r;
  }
  /// <summary>
  /// 从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的
  /// </summary>
  /// <param name="filePath">要解密的文件</param>
  /// <param name="dataIndex">要从哪一个块中解密</param>
  /// <returns>解密后的文本</returns>
  public static string DecryptFromFile(string filePath,int dataIndex)
  {
   string r = "";
   if(dataIndex > 10 && dataIndex < 1)
   {
    MessageBox.Show("数据索引的取值范围在1至10之间!","错误!",
     MessageBoxButtons.OK,MessageBoxIcon.Error);
    return r;
   }
   byte[] decrypted;
   byte[] key = {106,51,25,141,157,142,23,111,234,159,187,154,215,34,37,204};
   byte[] IV = {135,186,133,136,184,149,153,144};
   System.Text.UnicodeEncoding textConverter = new UnicodeEncoding();
   RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
   System.IO.FileStream tmpFileStream = new FileStream(filePath,
    System.IO.FileMode.Open,
    System.IO.FileAccess.Read,
    System.IO.FileShare.None,1024,true);

   System.Security.Cryptography.ICryptoTransform Decryptor = rc2CSP.CreateDecryptor(key,IV);
   System.IO.MemoryStream msDecrypt = new MemoryStream();
   System.Security.Cryptography.CryptoStream csDecrypt = new CryptoStream(msDecrypt,
    Decryptor,CryptoStreamMode.Write);
   byte[] index = new byte[10261];

   tmpFileStream.Read(index,0,10261);
   int startIndex = 1024*(dataIndex-1)+21;
   int count      = index[dataIndex*2 - 1]*128 + index[dataIndex*2];
   byte[] tmp     = new byte[count];

   Array.Copy(index,1024*(dataIndex-1)+21,tmp,0,count);
   csDecrypt.Write(tmp,0,count);
   csDecrypt.FlushFinalBlock();
   decrypted = msDecrypt.ToArray();
   r = textConverter.GetString(decrypted,0,decrypted.Length);
   tmpFileStream.Close();
   return r;
  }
  /// <summary>
  /// 将一段文本加密后保存到一个文件
  /// </summary>
  /// <param name="toEncryptText">要加密的文本数据</param>
  /// <param name="filePath">要保存的文件</param>
  /// <returns>是否加密成功</returns>
  public static bool EncryptToFile(string toEncryptText,string filePath)
  {
   bool r = false;
   byte[] encrypted;
   byte[] key = {106,51,25,141,157,142,23,111,234,159,187,154,215,34,37,204};
   byte[] IV = {135,186,133,136,184,149,153,144};
   System.Text.UnicodeEncoding textConverter = new UnicodeEncoding();
   RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
   System.IO.FileStream tmpFileStream = new FileStream(filePath,
    System.IO.FileMode.OpenOrCreate,
    System.IO.FileAccess.Write,
    System.IO.FileShare.None,1024,true);

   System.Security.Cryptography.ICryptoTransform Encryptor = rc2CSP.CreateEncryptor(key,IV);
   System.IO.MemoryStream msEncrypt = new MemoryStream();
   System.Security.Cryptography.CryptoStream csEncrypt = new CryptoStream(msEncrypt,
    Encryptor,CryptoStreamMode.Write);

   byte[] tmp = textConverter.GetBytes(toEncryptText);
   csEncrypt.Write(tmp,0,tmp.Length);
   csEncrypt.FlushFinalBlock();   
   encrypted = msEncrypt.ToArray();
   tmpFileStream.Write(encrypted,0,encrypted.Length);
   tmpFileStream.Flush();
   r = true;
   tmpFileStream.Close();
   return r;
  }
  /// <summary>
  /// 将一个被加密的文件解密
  /// </summary>
  /// <param name="filePath">要解密的文件</param>
  /// <returns>解密后的文本</returns>
  public static string DecryptFromFile(string filePath)
  {
   string r = "";
   byte[] decrypted;
   byte[] key = {106,51,25,141,157,142,23,111,234,159,187,154,215,34,37,204};
   byte[] IV = {135,186,133,136,184,149,153,144};
   System.Text.UnicodeEncoding textConverter = new UnicodeEncoding();
   RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
   System.IO.FileStream tmpFileStream = new FileStream(filePath,
    System.IO.FileMode.Open,
    System.IO.FileAccess.Read,
    System.IO.FileShare.None,1024,true);
   System.Security.Cryptography.ICryptoTransform Decryptor = rc2CSP.CreateDecryptor(key,IV);
   System.IO.MemoryStream msDecrypt = new MemoryStream();
   System.Security.Cryptography.CryptoStream csDecrypt = new CryptoStream(msDecrypt,
    Decryptor,CryptoStreamMode.Write);

   byte[] tmp = new byte[tmpFileStream.Length];
   tmpFileStream.Read(tmp,0,tmp.Length);
   csDecrypt.Write(tmp,0,tmp.Length);
   csDecrypt.FlushFinalBlock();
   decrypted = msDecrypt.ToArray();    
   r = textConverter.GetString(decrypted,0,decrypted.Length);
   tmpFileStream.Close();
   return r;
  }
 }
}

这篇关于RC2加密算法在C#的应用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/717561

相关文章

C#文件复制异常:"未能找到文件"的解决方案与预防措施

《C#文件复制异常:未能找到文件的解决方案与预防措施》在C#开发中,文件操作是基础中的基础,但有时最基础的File.Copy()方法也会抛出令人困惑的异常,当targetFilePath设置为D:2... 目录一个看似简单的文件操作问题问题重现与错误分析错误代码示例错误信息根本原因分析全面解决方案1. 确保

基于C#实现PDF转图片的详细教程

《基于C#实现PDF转图片的详细教程》在数字化办公场景中,PDF文件的可视化处理需求日益增长,本文将围绕Spire.PDFfor.NET这一工具,详解如何通过C#将PDF转换为JPG、PNG等主流图片... 目录引言一、组件部署二、快速入门:PDF 转图片的核心 C# 代码三、分辨率设置 - 清晰度的决定因

C# LiteDB处理时间序列数据的高性能解决方案

《C#LiteDB处理时间序列数据的高性能解决方案》LiteDB作为.NET生态下的轻量级嵌入式NoSQL数据库,一直是时间序列处理的优选方案,本文将为大家大家简单介绍一下LiteDB处理时间序列数... 目录为什么选择LiteDB处理时间序列数据第一章:LiteDB时间序列数据模型设计1.1 核心设计原则

PostgreSQL简介及实战应用

《PostgreSQL简介及实战应用》PostgreSQL是一种功能强大的开源关系型数据库管理系统,以其稳定性、高性能、扩展性和复杂查询能力在众多项目中得到广泛应用,本文将从基础概念讲起,逐步深入到高... 目录前言1. PostgreSQL基础1.1 PostgreSQL简介1.2 基础语法1.3 数据库

C#高效实现Word文档内容查找与替换的6种方法

《C#高效实现Word文档内容查找与替换的6种方法》在日常文档处理工作中,尤其是面对大型Word文档时,手动查找、替换文本往往既耗时又容易出错,本文整理了C#查找与替换Word内容的6种方法,大家可以... 目录环境准备方法一:查找文本并替换为新文本方法二:使用正则表达式查找并替换文本方法三:将文本替换为图

Python中的filter() 函数的工作原理及应用技巧

《Python中的filter()函数的工作原理及应用技巧》Python的filter()函数用于筛选序列元素,返回迭代器,适合函数式编程,相比列表推导式,内存更优,尤其适用于大数据集,结合lamb... 目录前言一、基本概念基本语法二、使用方式1. 使用 lambda 函数2. 使用普通函数3. 使用 N

Python中yield的用法和实际应用示例

《Python中yield的用法和实际应用示例》在Python中,yield关键字主要用于生成器函数(generatorfunctions)中,其目的是使函数能够像迭代器一样工作,即可以被遍历,但不会... 目录python中yield的用法详解一、引言二、yield的基本用法1、yield与生成器2、yi

Python多线程应用中的卡死问题优化方案指南

《Python多线程应用中的卡死问题优化方案指南》在利用Python语言开发某查询软件时,遇到了点击搜索按钮后软件卡死的问题,本文将简单分析一下出现的原因以及对应的优化方案,希望对大家有所帮助... 目录问题描述优化方案1. 网络请求优化2. 多线程架构优化3. 全局异常处理4. 配置管理优化优化效果1.

C#使用Spire.XLS快速生成多表格Excel文件

《C#使用Spire.XLS快速生成多表格Excel文件》在日常开发中,我们经常需要将业务数据导出为结构清晰的Excel文件,本文将手把手教你使用Spire.XLS这个强大的.NET组件,只需几行C#... 目录一、Spire.XLS核心优势清单1.1 性能碾压:从3秒到0.5秒的质变1.2 批量操作的优雅

C#和Unity中的中介者模式使用方式

《C#和Unity中的中介者模式使用方式》中介者模式通过中介者封装对象交互,降低耦合度,集中控制逻辑,适用于复杂系统组件交互场景,C#中可用事件、委托或MediatR实现,提升可维护性与灵活性... 目录C#中的中介者模式详解一、中介者模式的基本概念1. 定义2. 组成要素3. 模式结构二、中介者模式的特点