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);
            }
        }
    }
  • 相关阅读:
    Tomcat配置JMX远程监控(Windown7 Linxu)
    Maven Tomcat:run 使用tomcat7
    关于C3P0容错和自动重连特性的研究
    密码算法记录
    Linxu 安装Nignx
    Linxu Yum方式安装Mysql
    Linxu
    tomcat结合nginx使用小结
    Tomcat性能优化(三) Executor配置
    深入学习C#匿名函数、委托、Lambda表达式、表达式树类型——Expression tree types
  • 原文地址:https://www.cnblogs.com/Fred1987/p/14387899.html
Copyright © 2011-2022 走看看