.Net加密与解密——对称加密

本文涉及的产品
密钥管理服务KMS,1000个密钥,100个凭据,1个月
简介:    一,思路       对称加密含有一个被称为密钥的东西,在消息发送前使用密钥对消息进行加密,得到密文并发送,接收方收到密文后,使用相同的密钥进行解密,获得原消息。   PS:使用密钥对消息进行加密的过程,由加密算法来完成的,加密算法通常也是公开的。



   一,思路

     

对称加密含有一个被称为密钥的东西,在消息发送前使用密钥对消息进行加密,得到密文并发送,接收方收到密文后,使用相同的密钥进行解密,获得原消息。

 

PS:使用密钥对消息进行加密的过程,由加密算法来完成的,加密算法通常也是公开的。



二,对称加密的流程

           

1,发送方和接收方持有相同的密钥,并严格保密

2,发送方使用密钥对消息进行加密,然后发送消息

3,接收方收到消息后,使用相同的密钥对消息进行解密

PS:在这一过程中,第三方可能截获消息,但得到的知识一堆乱码




三,Demo


     

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography; //注意引入此命名空间
using System.IO;

namespace 对称加密与解密
{
    class Program
    {
        static void Main(string[] args)
        {
            string key = "secret key";  //密钥
            string plainText = "hello,world";  //明文

            string encryptedText = SymmetricCryPtoHelper.Encrypt(plainText, key);  //加密
            Console.WriteLine(encryptedText);

            string clearText = SymmetricCryPtoHelper.Decrypt(encryptedText, key);  //解密
            Console.WriteLine(clearText);

            Console.ReadKey();

        }
    }


    /// <summary>
    /// 对称加密帮助类
    /// </summary>
    /// <remarks>Editor:v-liuhch CreateTime:2015/5/15 22:05:41</remarks>
    public class SymmetricCryPtoHelper
    { 
        //对称加密算法提供器
        private ICryptoTransform encryptor;//加密器对象
        private ICryptoTransform decryptor;//解密器对象
        private const int BufferSize = 1024;



        /// <summary>
        /// Initializes a new instance of the <see cref="SymmetricCryPtoHelper"/> class.
        /// </summary>
        /// <param name="algorithmName">Name of the algorithm.</param>
        /// <param name="key">The key.</param>
        /// <remarks>Editor:v-liuhch</remarks>
        public SymmetricCryPtoHelper(string algorithmName, byte[] key)
        {
            //SymmetricAlgorithm为对称算法基类
            SymmetricAlgorithm provider = SymmetricAlgorithm.Create(algorithmName);
            provider.Key = key;//指定密钥,通常为128位或者196位
            provider.IV = new byte[] { 0x12,0x34,0x56,0x78,0x90,0xAB,0xCD,0xEF};//Initialization vector ,初始化向量,避免了加密之后文字的相关部分也是重复的问题,通常为64位

            encryptor = provider.CreateEncryptor();//创建加密器对象
            decryptor = provider.CreateDecryptor();//创建解密器对象

        }

        public SymmetricCryPtoHelper(byte[] key) : this("TripleDES", key) { }


        //加密算法
        /// <summary>
        /// Encrypts the specified clear text.
        /// </summary>
        /// <param name="clearText">The clear text.</param>
        /// <returns>System.String.</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/5/17 16:56:15</remarks>
        public string Encrypt(string clearText) { 
        
            //创建明文流
            byte[] clearBuffer = Encoding.UTF8.GetBytes(clearText);
            MemoryStream clearStream = new MemoryStream(clearBuffer);

            //创建空的密文流
            MemoryStream encryptedStream = new MemoryStream();


            /* 加密解密涉及到两个流,一个是明文流,一个是密文流
            那么必然有一个中介者,将明文流转换成密文流;或者将密文流转换成明文流;
            * .net中执行这个操作的中介者是一个流类型,叫做CryptoStream;
             * 
             * 加密时构造函数参数:
             *     1,Stream:密文流(此时密文流还没有包含数据,仅仅是一个空流);
             *     2,ICryptoTransform:创建的加密器,负责进行加密计算,
             *     3,枚举:write,将流经CryptoStream的明文流写入到密文流中,最后从密文流中获得加密后的数据
            */
            CryptoStream cryptoStream = new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write);


            //将明文流写入到buffer中
            //将buffer中的数据写入到cryptoStream中
            int bytesRead = 0;
            byte[] buffer = new byte[BufferSize];
            do
            {
                bytesRead = clearStream.Read(buffer, 0, BufferSize);
                cryptoStream.Write(buffer, 0, bytesRead);
                
            } while (bytesRead>0);

            cryptoStream.FlushFinalBlock();//清除缓冲区

            //获取加密后的文本
            buffer = encryptedStream.ToArray();
            string encryptedText = Convert.ToBase64String(buffer);
            return encryptedText;
        
        }
            
        
        /// <summary>
        /// 解密算法
        /// </summary>
        /// <param name="encryptedText">The encrypted text.</param>
        /// <returns>System.String.</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/5/17 16:56:22</remarks>
        public string Decrypt(string encryptedText)
        {
            byte[] encryptedBuffer = Convert.FromBase64String(encryptedText);
            Stream encryptedStream = new MemoryStream(encryptedBuffer);

            MemoryStream clearStream = new MemoryStream();
            /*
             解密时构造函数参数:
             *     1,Stream:密文流(此时密文流包含数据);
             *     2,ICryptoTransform:创建的解密器,负责进行解密计算,
             *     3,枚举:write,将密文流中的数据读出到明文流,进而再转换成明文的,原来的格式
             */
            CryptoStream cryptoStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read);

            int bytesRead = 0;
            byte[] buffer = new byte[BufferSize];

            do
            {
                bytesRead = cryptoStream.Read(buffer, 0, BufferSize);
                clearStream.Write(buffer, 0, bytesRead);

            } while (bytesRead>0);

            buffer = clearStream.GetBuffer();
            string clearText = Encoding.UTF8.GetString(buffer, 0, (int)clearStream.Length);

            return clearText;
        
        
        }


        /// <summary>
        /// Encrypts the specified clear text.
        /// </summary>
        /// <param name="clearText">The clear text.</param>
        /// <param name="key">The key.</param>
        /// <returns>System.String.</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/5/17 16:56:40</remarks>
        public static string Encrypt(string clearText, string key) {


            byte[] keyData = new byte[16];
            byte[] sourceData = Encoding.Default.GetBytes(key);
            int copyBytes = 16;
            if (sourceData.Length<16)
            {
                copyBytes = sourceData.Length;
                
            }

            Array.Copy(sourceData, keyData, copyBytes);
            SymmetricCryPtoHelper helper = new SymmetricCryPtoHelper(keyData);
            return helper.Encrypt(clearText);

        }


        /// <summary>
        /// Decrypts the specified encrypted text.
        /// </summary>
        /// <param name="encryptedText">The encrypted text.</param>
        /// <param name="key">The key.</param>
        /// <returns>System.String.</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/5/17 16:56:44</remarks>
        public static string Decrypt(string encryptedText, string key)
        {

            byte[] keyData = new byte[16];
            byte[] sourceData = Encoding.Default.GetBytes(key);
            int copyBytes = 16;
            if (sourceData.Length<16)
            {
                copyBytes = sourceData.Length;
            }

            Array.Copy(sourceData, keyData, copyBytes);

            SymmetricCryPtoHelper helper = new SymmetricCryPtoHelper(keyData);
            return helper.Decrypt(encryptedText);

        }
    
    }
}





   四,隐患问题


1,发送方和接收方都需要持有密钥,并保证密钥不被泄露。

2,如果第三方非法获得了密钥,在对消息进行篡改后,重新加密发给接收方,则接收方无法辨别。既然无法判断消息是否被篡改,也无法确定消息是由谁发送过来的,无法满足完整性和可认证性。











目录
相关文章
|
4月前
|
存储 安全 数据安全/隐私保护
Codota的数据加密技术包括静态数据加密和传输中的数据加密
Codota的数据加密技术包括静态数据加密和传输中的数据加密
84 4
|
4月前
|
安全 数据库 数据安全/隐私保护
对称加密与非对称加密的区别
对称加密与非对称加密的区别
245 64
|
7月前
|
存储 数据安全/隐私保护
.NET Core 究竟隐藏着怎样的神秘力量,能实现强身份验证与数据加密?
【8月更文挑战第28天】在数字化时代,数据安全与身份验证至关重要。.NET Core 提供了强大的工具,如 Identity 框架,帮助我们构建高效且可靠的身份验证系统,并支持高度定制化的用户模型和认证逻辑。此外,通过 `System.Security.Cryptography` 命名空间,.NET Core 还提供了丰富的加密算法和工具,确保数据传输和存储过程中的安全性。以下是一个简单的示例,展示如何使用 .NET Core 的 Identity 框架实现用户注册和登录功能。
58 3
|
3月前
|
Java 数据安全/隐私保护
对称加密、非对称加密、哈希摘要
对称加密使用同一密钥进行加解密,速度快但需保密;非对称加密采用公钥加密、私钥解密,公钥可公开,安全性高但速度较慢,双向通信需双方各持一对密钥;哈希摘要是从数据中提取特征,用于数据完整性校验,不同数据的哈希值几乎不会相同。
57 0
|
5月前
|
安全 网络协议 网络安全
【HTTPS】对称加密和非对称加密
【HTTPS】对称加密和非对称加密
66 0
|
6月前
|
算法 安全 网络安全
概念区分:对称加密、非对称加密、公钥、私钥、签名、证书
概念区分:对称加密、非对称加密、公钥、私钥、签名、证书
351 0
|
7月前
|
存储 算法 安全
|
18天前
|
云安全 安全 数据建模
《数字证书:互联网世界的"身份证"与"防盗门"》 ——揭秘网络安全背后的加密江湖
在2023年某深夜,上海陆家嘴金融公司机房遭遇黑客攻击,神秘青铜大门与九大掌门封印的玉牌突现,阻止了入侵。此门象征数字证书,保障网络安全。数字证书如验钞机识别假币,保护用户数据。它通过SSL/TLS加密、CA认证和非对称加密,构建安全通信。证书分为DV、OV、EV三类,分别适合不同场景。忽视证书安全可能导致巨额损失。阿里云提供一站式证书服务,助力企业部署SSL证书,迎接未来量子计算和物联网挑战。
|
3月前
|
安全 算法 网络协议
【网络原理】——图解HTTPS如何加密(通俗简单易懂)
HTTPS加密过程,明文,密文,密钥,对称加密,非对称加密,公钥和私钥,证书加密
|
3月前
|
存储 SQL 安全
网络安全与信息安全:关于网络安全漏洞、加密技术、安全意识等方面的知识分享
随着互联网的普及,网络安全问题日益突出。本文将介绍网络安全的重要性,分析常见的网络安全漏洞及其危害,探讨加密技术在保障网络安全中的作用,并强调提高安全意识的必要性。通过本文的学习,读者将了解网络安全的基本概念和应对策略,提升个人和组织的网络安全防护能力。

热门文章

最新文章