C#执行数据加密的DES.Create 方法

目录

一、重载

二、Create()

1.定义

2.实例1,加密和解密文件中的数据

3.实例2,加密和解密内存中的数据

三、Create(String)

四、关于DES加密


命名空间:

System.Security.Cryptography

数据集:

System.Security.Cryptography.dll

创建加密对象的实例以执行数据加密标准 (DES) 算法。

一、重载

|----------------|-----------------------------------|
| Create() | 创建加密对象的实例以执行数据加密标准 (DES) 算法。 |
| Create(String) | 创建加密对象的实例以执行数据加密标准 (DES) 算法的指定实现。 |

二、Create()

创建加密对象的实例以执行数据加密标准 (DES) 算法。

1.定义

cs 复制代码
public static System.Security.Cryptography.DES Create ();

返回
DES
一个加密对象。

2.实例1,加密和解密文件中的数据

cpp 复制代码
// DES.Create()
// 创建和使用 DES 对象来加密和解密文件中的数据。
using System.Security.Cryptography;
using System.Text;

namespace ConsoleApp8
{
    class DESSample
    {
        static void Main()
        {
            try
            {
                byte[] key;
                byte[] iv;
                using (DES des = DES.Create())        // 以随机秘钥创建加密流对象,初始化IV                                          
                {
                    key = des.Key;
                    iv = des.IV;
                }
                string original = "大海航行靠舵手";    //要加密的原始字符串                                     
                string filename = "CText.enc";        //加密后要文件名和路径默认当前工作目录                                             
                EncryptTextToFile(original, filename, key, iv);//把字符串加密成文件
                string decrypted = DecryptTextFromFile(filename, key, iv);//从文件中解密出字符串
                Console.WriteLine(decrypted);         //输出解密后的字符串                                           
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        /// <summary>
        /// 自定义加密方法:
        /// 创建并打开文件流;
        /// 创建DES对象;
        /// 以随机秘钥创建DES加密器;
        /// 创建加密流;
        /// </summary>
        /// <param name="text">
        /// 把输入参数转成字节数组;
        /// 遍历字节数组并写入加密流</param>
        /// <param name="path">
        /// 文件路径,默认当前工作路径</param>
        /// <param name="key">
        /// 随机秘钥</param>
        /// <param name="iv">
        /// 随机矢量</param>
        public static void EncryptTextToFile(string text, string path, byte[] key, byte[] iv)
        {
            try
            {
                using FileStream fStream = File.Open(path, FileMode.Create);
                using DES des = DES.Create();
                using ICryptoTransform encryptor = des.CreateEncryptor(key, iv);
                using var cStream = new CryptoStream(fStream, encryptor, CryptoStreamMode.Write);
                byte[] toEncrypt = Encoding.UTF8.GetBytes(text);
                cStream.Write(toEncrypt, 0, toEncrypt.Length);
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                throw;
            }
        }
        /// <summary>
        /// 自定义的解密方法:
        /// 创建文件流对象并打开加密后的文件;
        /// 创建DES解密器;
        /// 创建加密流。
        /// 创建文件流阅读器对象,并把加密流转UTF8文本:
        /// 从 StreamReader 读回所有文本;
        /// StreamReader 从 CryptoStream 接收解密的字节;
        /// CryptoStream 从 FileStream 接收加密的字节。
        /// </summary>
        /// <param name="path">
        /// 文件路径,默认当前工作路径</param>
        /// <param name="key">
        /// 随机秘钥</param>
        /// <param name="iv">
        /// 矢量</param>
        /// <returns></returns>
        public static string DecryptTextFromFile(string path, byte[] key, byte[] iv)
        {
            try
            {
                using FileStream fStream = File.OpenRead(path);
                using DES des = DES.Create();
                using ICryptoTransform decryptor = des.CreateDecryptor(key, iv);
                using var cStream = new CryptoStream(fStream, decryptor, CryptoStreamMode.Read);
                using StreamReader reader = new(cStream, Encoding.UTF8);
                return reader.ReadToEnd();
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                throw;
            }
        }
    }
}
//运行结果:
/*
大海航行靠舵手

 */

3.实例2,加密和解密内存中的数据

cs 复制代码
// DES.Create()
// 创建和使用 DES 对象来加密和解密内存中的数据。
using System.Security.Cryptography;
using System.Text;

namespace ConsoleApp9
{
    class DESSample2
    {
        static void Main()
        {
            try
            {
                byte[] key;
                byte[] iv;
                using (DES des = DES.Create())
                {
                    key = des.Key;
                    iv = des.IV;
                }
                string original = "海燕在大海上飞翔";
                byte[] encrypted = EncryptToMemory(original, key, iv);      // 加密字符串到缓存
                string decrypted = DecryptFromMemory(encrypted, key, iv);   //自缓存解密到字符串
                Console.WriteLine(decrypted);                               //输出解密的字符串                                               
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        /// <summary>
        /// 自定义的加密方法:
        /// 从内存流中获取字节数组;
        /// 加密流读取内容并完成加密。
        /// </summary>
        public static byte[] EncryptToMemory(string text, byte[] key, byte[] iv)
        {
            try
            {
                using MemoryStream mStream = new();             //创建内存流
                using DES des = DES.Create();                   //创建DES对象
                using ICryptoTransform encryptor = des.CreateEncryptor(key, iv);//创建加密器
                using var cStream = new CryptoStream(mStream, encryptor,
                    CryptoStreamMode.Write);                    //创建加密流
                byte[] toEncrypt = Encoding.UTF8.GetBytes(text);//把输入字符串转字节数组
                cStream.Write(toEncrypt, 0, toEncrypt.Length);  //将字节数组写入加密流并刷新
                byte[] ret = mStream.ToArray();
                return ret;                                     //返回加密的内存数据
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                throw;
            }
        }
        /// <summary>
        /// 自缓存中解密:
        /// 创建缓存用于装载解密的数据,
        /// 注意:DES 加密的数据总是比解密的数据稍大;
        /// 用刚创建的缓存创建内存流;
        /// 不断地从 CryptoStream 中读取数据,直到完成(返回 0)。
        /// </summary>
        public static string DecryptFromMemory(byte[] encrypted, byte[] key, byte[] iv)
        {
            try
            {
                byte[] decrypted = new byte[encrypted.Length];
                int offset = 0;
                using DES des = DES.Create();                              //创建DES对象                                              
                using MemoryStream mStream = new(decrypted);               //创建内存流
                using var cStream = new CryptoStream(mStream, des.
                    CreateDecryptor(key, iv), CryptoStreamMode.Read);      //创建解密流对象

                int read = 1;
                while (read > 0)
                 {
                     read = cStream.Read(decrypted, offset, decrypted.Length - offset);
                     offset += read;
                 }
                return Encoding.UTF8.GetString(decrypted, 0, offset);      // 把解密的转文本并返回
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                throw;
            }
        }
    }
}

三、Create(String)

创建加密对象的实例以执行数据加密标准 (DES) 算法的指定实现。

cs 复制代码
public static DES Create (string algName);

参数
algName String
要使用的 DES 的特定实现的名称。

返回
DES
一个加密对象。

四、关于DES加密

DES,全称Data Encryption Standard,是一种对称加密算法。DES加密算法是以8字节为一个块进行加密,一个数据块一个数据块的加密,一个8字节的明文加密后的密文也是8字节。如果明文长度不为8字节的整数倍,添加值为0的字节凑满8字节整数倍。所以加密后的密文长度一定为8字节的整数倍。

DES使用的密钥key为8字节,初始向量IV也是8字节。

相关推荐
通信仿真实验室15 分钟前
(10)MATLAB莱斯(Rician)衰落信道仿真1
开发语言·matlab
勿语&18 分钟前
Element-UI Plus 暗黑主题切换及自定义主题色
开发语言·javascript·ui
吾爱星辰4 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
ChinaDragonDreamer4 小时前
Kotlin:2.0.20 的新特性
android·开发语言·kotlin
IT良4 小时前
c#增删改查 (数据操作的基础)
开发语言·c#
yufei-coder4 小时前
掌握 C# 中的 LINQ(语言集成查询)
windows·vscode·c#·visual studio
Kalika0-05 小时前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
_.Switch5 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
代码雕刻家5 小时前
课设实验-数据结构-单链表-文教文化用品品牌
c语言·开发语言·数据结构
一个闪现必杀技5 小时前
Python入门--函数
开发语言·python·青少年编程·pycharm