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
猜你喜欢
- paras.xml文件<?xml version="1.0" encoding="UTF-8"
- 顺序结构按照代码书写的顺序一行一行执行分支结构if 语句基本语法形式:if(布尔表达式){ //条件满足时执行代码
- 声明一个客户端对象:protected RedisClient Redis = new RedisClient("127.0.0
- 前言看标题好像很简单的样子,但是针对使用jar包发布SpringBoot项目就不一样了。当你使用tomcat发布项目的时候,上传文件存放会变
- 众所周知,PDF文档除了具有较强稳定性和兼容性外, 还具有较强的安全性,在工作中可以有效避免别人无意中对文档内容进行修改。但与此同
- javaWeb 四大域对象1)和属性相关的方法Object getAttribute(String name) 获取指定的属性En
- 前言网上SSO的框架很多,此篇文章使用的是自写的SSO来实现简单的登录授权功能,目的在于扩展性,权限这方面,自写扩展性会好点。提示:以下是本
- storm操作zookeeper的主要函数都定义在命名空间backtype.storm.cluster中(即cluster.clj文件中)。
- Java8实现菜单树形数据当我们打开京东商城时,左侧的菜单依次分为 * 展示,这是如何实现的呢?本篇暂不讲述前端,只讲述如何使用java8 的
- 导出Excel的框架有很多种,POI相对来说比较老了,很多Excel框架底层都是POI、有EasyPoi、EasyExcel、包括Hutoo
- 一、Has方法与With方法如:A类必须包含B类一个不为null的实例,而B类可选择时候包含A类一个实例。A.HasRequired(a =
- 一、案例场景遇到过这样的场景,在定义一个static修饰的Map时,使用了大量的put()方法赋值,就类似这样——public static
- Gradle和Maven都是当前热门的自动化构建工具。使用Gradle去构建项目,由于没有办法像Maven一样配置Setting文件来修改本
- Spring Batch job任务只跑一次在一次实际使用spring batch的过程中,在定时任务中,第一次执行Job没有出现问题,然后
- @ModelAttribute与@RequestBody的区别最近在写代码的过程中,发现之前项目都是使用的@ModelAttribute注解
- 这篇文章主要介绍了Spring Boot项目维护全局json数据代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考
- 这些天忙着刷题,又怕遗忘了spring boot, 所以抽出一点时间折腾折腾,加深点印象。 spring boot 的文件上传与 sprin
- 1、什么是 生命周期?Maven 强大的原因是有一个十分完善的生命周期,生命周期可以理解为项目构建步骤的集合,它定义了各个构建环节的执行顺序
- final,static,this,super 关键字总结正文开始@Assassin1. final 关键字:final 关键字,意思是最终
- 1.前提:已安装JDK14,可以到jdk官网下载,或加QQ群835259695,快速免费下载2.不说没用的直接上jdk14环境下的jpack