C#实现常见加密算法的示例代码
作者:最菜程序员Sxx 发布时间:2023-05-08 12:44:43
前言
最近项目中需要用到字符串加解密,遂研究了一波,发现密码学真的是博大精深,好多算法的设计都相当巧妙,学到了不少东西,在这里做个小小的总结,方便后续查阅。
文中关键词:
明文(P,Plaintext)
密文(C,Ciphertext)
密钥(K,Key)
加密算法(E,Encypted Algorithm)
解密算法(D,Decrypted Algorithm)
公钥(Public Key)
私钥(Private Key)
常见加密算法如下,本文主要介绍红框里边的5种算法以及C#代码实现
1. Base64编码
1.1 原理介绍
(1)Base64是一种基于64个可打印字符来表示二进制数据的表示方法。其索引表如下:
共包含64个可打印字符为:A-Z、a-z、0-9、+、/,另外还会有“=”或者“==”作为填充字符出现在编码中。
(2)编码规则
将待编码字符串每三个字节分为一组,每组24bit
将上边的24bit分为4组,每组6bit
在每组前添加两个0,每组由6bit变为8bit,总共32bit,即4byte
根据Base64编码对照表获取对应的编码值
上述图例中:“Man”经过Base64编码之后变为“TWFu”。
(3)字节数不足3个时
两个字节:2byte共16bit,按照编码规则,每6bit分为一组,则第三组缺少2bit,用0补齐,得到3个Based64编码,第四组完全没有数据则用“=”补上。因此上图“BC”经过Base64编码之后变为“QkM=”;
一个字节:1byte共8bit,按照编码规则,每6bit分为一组,则第二组缺少4bit,用0补齐,得到2个Based64编码,后两组完全没有数据都用“=”补上。因此上图“A”经过Base64编码之后变为“QQ==”。
1.2 C#代码
// Base64编码
public sealed class Base64
{
// Base64加密
public static string Base64Encrypt(string plaintext)
{
string ciphertext = "";
byte[] buffer = Encoding.ASCII.GetBytes(plaintext);
ciphertext = Convert.ToBase64String(buffer);
return ciphertext;
}
// Base64解密
public static string Base64Decrypt(string ciphertext)
{
string plaintext = "";
byte[] buffer = Convert.FromBase64String(ciphertext);
plaintext = Encoding.ASCII.GetString(buffer);
return plaintext;
}
}
2. 凯撒密码
2.1 原理介绍
凯撒密码是一种很古老的加密体制,主要是通过代换来达到加密的目的。其基本思想是:通过把字母移动一定的位数来实现加密和解密。移动位数就是加密和解密的密钥。
举例说明,假设明文为“ABCD”,密钥设置为7,那么对应的密文就是“HIJK”。具体流程如下表所示:
2.2 C#代码
// Caesar Cipher(凯撒密码)
public sealed class Caesar
{
// 加密
public static string CaesarEncrypt(string plaintext, int key)
{
// 字符串转换为字节数组
byte[] origin = Encoding.ASCII.GetBytes(plaintext);
string rst = null;
for (int i = 0; i < origin.Length; i++)
{
// 获取字符ASCII码
int asciiCode = (int)origin[i];
// 偏移
asciiCode += key;
byte[] byteArray = new byte[] { (byte)asciiCode };
// 将偏移后的数据转为字符
ASCIIEncoding asciiEncoding = new ASCIIEncoding();
string strCharacter = asciiEncoding.GetString(byteArray);
// 拼接数据
rst += strCharacter;
}
return rst;
}
// 解密
public static string CaesarDecrypt(string ciphertext, int key)
{
// 字符串转换为字节数组
byte[] origin = Encoding.ASCII.GetBytes(ciphertext);
string rst = null;
for (int i = 0; i < origin.Length; i++)
{
// 获取字符ASCII码
int asciiCode = (int)origin[i];
// 偏移
asciiCode -= key;
byte[] byteArray = new byte[] { (byte)asciiCode };
// 将偏移后的数据转为字符
ASCIIEncoding asciiEncoding = new ASCIIEncoding();
string strCharacter = asciiEncoding.GetString(byteArray);
// 拼接数据
rst += strCharacter;
}
return rst;
}
}
3. Vigenere密码
3.1 原理介绍
在凯撒密码中,每一个字母通过一定的偏移量(即密钥K)变成另外一个字母,而维吉尼亚密码就是由多个偏移量不同的凯撒密码组成,属于多表密码的一种。在一段时间里它曾被称为“不可破译的密码”。
维吉尼亚密码在加密和解密时,需要一个表格进行对照。表格一般为26*26的矩阵,行和列都是由26个英文字母组成。加密时,明文字母作为列,密钥字母作为行,所对应坐标上的字母即为对应的密文字母。
可以用上述表格直接查找对应的密文,也可通过取模计算的方式。用0-25代替字母A-Z,C表示密文,P表示明文,K表示密钥,维吉尼亚加密算法可表示为:
密文可表示为:
举例说明,假设明文为“I AM A CHINESE”,密钥为“CHINA”,那么密文就是“L HU N CJPVRSG”。具体过程如下表:
3.2 C#代码
// Vigenere Cipher(维吉尼亚密码)
public sealed class Vigenere
{
// 加密
public static string VigenereEncrypt(string plaintext, string key)
{
string ciphertext = "";
byte[] origin = Encoding.ASCII.GetBytes(plaintext.ToUpper());
byte[] keys = Encoding.ASCII.GetBytes(key.ToUpper());
int length = origin.Length;
int d = keys.Length;
for (int i = 0; i < length; i++)
{
int asciiCode = (int)origin[i];
// 加密(移位)
asciiCode = asciiCode + (int)keys[i % d] - (int)'A';
if (asciiCode > (int)'Z')
{
asciiCode -= 26;
}
byte[] byteArray = new byte[] { (byte)asciiCode };
// 将偏移后的数据转为字符
ASCIIEncoding asciiEncoding = new ASCIIEncoding();
string strCharacter = asciiEncoding.GetString(byteArray);
ciphertext += strCharacter;
}
return ciphertext;
}
// 解密
public static string VigenereDecrypt(string ciphertext, string key)
{
string plaintext = "";
byte[] origin = Encoding.ASCII.GetBytes(ciphertext.ToUpper());
byte[] keys = Encoding.ASCII.GetBytes(key.ToUpper());
int length = origin.Length;
int d = keys.Length;
for (int i = 0; i < length; i++)
{
int asciiCode = (int)origin[i];
// 解密(移位)
asciiCode = asciiCode - (int)keys[i % d] + (int)'A';
if (asciiCode < (int)'A')
{
asciiCode += 26;
}
byte[] byteArray = new byte[] { (byte)asciiCode };
// 将偏移后的数据转为字符
ASCIIEncoding asciiEncoding = new ASCIIEncoding();
string strCharacter = asciiEncoding.GetString(byteArray);
plaintext += strCharacter;
}
return plaintext;
}
}
4. DES
4.1 原理介绍
DES(数据加密标准,Data Encryption Standard),出自IBM的研究,后被美国政府正式采用,密钥长度56位,以现代的计算能力可在24h以内被暴力破解。算法设计原理参考这篇博客。
顺便说一下3DES(Triple DES),它是DES向AES过渡的加密算法,使用3条56位的密钥对数据进行三次加密。是DES的一个更安全的变形。它以DES为基本模块,通过组合分组方法设计出分组加密算法。比起最初的DES,3DES更为安全。
4.2 C#代码
C#中提供封装好的DES加解密方法,直接调用即可。
// DES(数据加密标准,Data Encryption Standard)
public sealed class DES
{
/* DES相关
ecb、ctr模式不需要初始化向量
cbc、ofc、cfb需要初始化向量
初始化向量的长度:DES/3DES为8byte;AES为16byte。加解密使用的IV相同。
*/
/// <summary>
/// DES加密
/// </summary>
/// <param name="plaintext">明文</param>
/// <param name="key">密钥,长度8byte</param>
/// <param name="iv">初始化向量,长度8byte</param>
/// <returns>返回密文</returns>
public static string DESEncrypt(string plaintext, string key, string iv)
{
try
{
byte[] btKey = Encoding.UTF8.GetBytes(key);
byte[] btIV = Encoding.UTF8.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (MemoryStream ms = new MemoryStream())
{
byte[] inData = Encoding.UTF8.GetBytes(plaintext);
try
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
{
cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();
}
return Convert.ToBase64String(ms.ToArray());
}
catch
{
return plaintext;
}
}
}
catch { }
return "DES加密出错";
}
/// <summary>
/// DES解密
/// </summary>
/// <param name="ciphertext">密文</param>
/// <param name="key">密钥,长度8byte</param>
/// <param name="iv">初始化向量,长度8byte</param>
/// <returns>返回明文</returns>
public static string DESDecrypt(string ciphertext, string key, string iv)
{
if (ciphertext == "") return "";
try
{
byte[] btKey = Encoding.UTF8.GetBytes(key);
byte[] btIV = Encoding.UTF8.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (MemoryStream ms = new MemoryStream())
{
byte[] inData = Convert.FromBase64String(ciphertext);
try
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
{
cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
catch
{
return ciphertext;
}
}
}
catch { }
return "DES解密出错";
}
}
5. AES
5.1 原理简述
AES(高级加密算法,Advanced Encryption Standard),美国政府提出,该加密算法采用对称分组密码体制,提供128位、192位和256位三种密钥长度,算法应易于各种硬件和软件实现。这种加密算法是美国联邦政府采用的区块加密标准。AES本身就是为了取代DES的,AES具有更好的安全性、效率和灵活性。
5.2 C#代码
// AES(高级加密算法,Advanced Encryption Standard),美政府提出
public sealed class AES
{
/// <summary>
/// AES加密
/// </summary>
/// <param name="plaintext">明文</param>
/// <param name="key">密钥,长度16byte</param>
/// <param name="IV">初始化向量,长度16byte</param>
/// <returns>返回密文</returns>
public static string AESEncrypt(string plaintext, string key, string iv)
{
if (plaintext == "") return "";
try
{
byte[] btKey = Encoding.UTF8.GetBytes(key);
byte[] btIV = Encoding.UTF8.GetBytes(iv);
byte[] inputByteArray = Encoding.UTF8.GetBytes(plaintext);
using (AesCryptoServiceProvider provider = new AesCryptoServiceProvider())
{
using (MemoryStream mStream = new MemoryStream())
{
CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
cStream.Close();
return Convert.ToBase64String(mStream.ToArray());
}
}
}
catch { }
return "AES加密出错";
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="ciphertext">密文</param>
/// <param name="key">密钥,长度16byte</param>
/// <param name="iv">初始化向量,长度16byte</param>
/// <returns>返回明文</returns>
public static string AESDecrypt(string ciphertext, string key, string iv)
{
if (ciphertext == "") return "";
try
{
byte[] btKey = Encoding.UTF8.GetBytes(key);
byte[] btIV = Encoding.UTF8.GetBytes(iv);
byte[] inputByteArray = Convert.FromBase64String(ciphertext);
using (AesCryptoServiceProvider provider = new AesCryptoServiceProvider())
{
using (MemoryStream mStream = new MemoryStream())
{
CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
cStream.Close();
return Encoding.UTF8.GetString(mStream.ToArray());
}
}
}
catch { }
return "AES解密出错";
}
}
来源:https://www.cnblogs.com/shaoxx333/p/16435336.html


猜你喜欢
- 使用Android Studio 创建Android项目,分享给大家(1) 说明:还有一部分人在坚持使用 Eclipse ,建议抓紧换掉。使
- 偶然机会看到一种对象初始的方式:// 新建一个列表,并赋值 "Harry","Tony","
- 一、系统介绍本系统实现扑克的分发,抢地主,电脑自动出牌等功能。二、系统展示1.扑克分发2.抢地主3.出牌4.游戏胜利三、系统实现Card.j
- 一、setting.xml文件的位置今天我们来谈谈Maven setting文件配置的禅定之道。不知道大家有没有听说过禅宗?嗯,没错,就是那
- Spring MVC 请求处理流程用户发起请求,到 DispatcherServlet;然后到 HandlerMapping 返回处理器链(
- 0.解释器(Interpreter)模式定义 :给定一门语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中句子。
- 为了追求更好的用户体验,有时候我们需要一个类似心跳一样跳动着的控件来吸引用户的注意力,这是一个小小的优化需求,但是在 Flutter 里动画
- 在上一篇笔记 《SpringMVC实现图片上传》记录了将图片上传到本地的实现,在很多项目中都会有一台专门的文件服务器来保存文件的,这边记录下
- 本文实例讲述了C#获取USB事件API。分享给大家供大家参考。具体如下:const int WM_DEVICECHANGE = 0x2190
- springboot整合redis主从sentinel一主二从三sentinel配置1、master:127.0.0.1:63792、sla
- Android-webview和js互相调用Android 和 H5 都是移动开发应用的非常广泛。市面上很多App都是使用Android开发
- ${project.basedir}的使用<project> 是 pom.xml 的根节点,project.basedir 就是
- 本文实例讲述了Java文件操作工具类fileUtil。分享给大家供大家参考,具体如下:package com.gcloud.common;i
- Java代码 InputMethodManager imm = (InputMethodManager)getSystemService(S
- 先来说一说我们为什么要用这个东西啊!比如,我们现在有这样了个问题要解决:这样,我们就要用到中间消息间了然后我们就说一下什么是中间消息间吧。采
- 本文实例讲述了C#中数组段用法。分享给大家供大家参考。具体分析如下:1.数组段说明① 结构ArraySegment<T>表示数组
- FTPS:一种多传输协议,相当于加密版的FTP。当你在FTP服务器上收发文件的时候,你面临两个风险。第一个风险是在上载文件的时候为文件加密。
- spring Boot 使用事务非常简单,首先使用注解 @EnableTransactionManagement 开启事务支持后,然后在访问
- 前情提要本文中提供了九种方式获取resources目录下文件的方式。其中打印文件的方法如下: /**
- 实例如下:static void testLock1(){final AtomicInteger waitCount = new Atomi