Sysmetric encryption and decryption via AES

using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Xml.Linq;
using static System.Convert;

namespace CryptographyLib
{
    public static class Protector
    {
        //salt size must be at least 8 bytes,we will use 16 bytes.
        private static readonly byte[] salt=Encoding.Unicode.GetBytes("7BANANAS");

        private static readonly int iterations=2000;

        public static string Encrypt(string plainText,string pwd)
        {
            byte[] encryptedBytes;
            byte[] plainBytes=Encoding.Unicode.GetBytes(plainText);
            var aes=Aes.Create();
            var pbkdf2=new Rfc2898DeriveBytes(pwd,salt,iterations);
            aes.Key=pbkdf2.GetBytes(32);
            aes.IV=pbkdf2.GetBytes(16);

            using(var ms=new MemoryStream())
            {
                using(var cs=new CryptoStream(ms,aes.CreateEncryptor(),CryptoStreamMode.Write))
                {
                    cs.Write(plainBytes,0,plainBytes.Length);
                }
                encryptedBytes=ms.ToArray();
            }
            return Convert.ToBase64String(encryptedBytes);
        }

        public static string Decrypt(string cryptoText,string pwd)
        {
            byte[] plainBytes;
            byte[] cryptoBytes=Convert.FromBase64String(cryptoText);
            var aes=Aes.Create();

            var pbkdf2=new Rfc2898DeriveBytes(pwd,salt,iterations);
            aes.Key=pbkdf2.GetBytes(32);
            aes.IV=pbkdf2.GetBytes(16);

            using(var ms=new MemoryStream())
            {
                using(var cs=new CryptoStream(ms,aes.CreateDecryptor(),CryptoStreamMode.Write))
                {
                    cs.Write(cryptoBytes,0,cryptoBytes.Length);
                }
                plainBytes=ms.ToArray();
            }
            return Encoding.Unicode.GetString(plainBytes);
        }
    }
}

 

原文链接: https://www.cnblogs.com/Fred1987/p/14387899.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    Sysmetric encryption and decryption via AES

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/401878

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月19日 上午9:28
下一篇 2023年4月19日 上午9:28

相关推荐