zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    }
  • 相关阅读:
    Qt 学习之路 2(51):布尔表达式树模型
    Qt 学习之路 2(50):自定义可编辑模型
    Qt 学习之路 2(49):自定义只读模型
    Qt 学习之路 2(48):QSortFilterProxyModel
    spring boot 定时任务
    mybatis 操作总结
    MySQL 中常用的函数
    Maven dependencies 与 dependencyManagement 区别
    springboot 校验机制 @Validated @Valid
    Fork JOIN 分而治之
  • 原文地址:https://www.cnblogs.com/Fred1987/p/14387899.html
Copyright © 2011-2022 走看看