C# 加密总结 一些常见的加密方法

一 散列数据 代码如下:

private static string CalculateSHA512Hash(string input)
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            SHA512Managed sha512 = new SHA512Managed();
            byte[] outputBytes = sha512.ComputeHash(inputBytes);
            return Convert.ToBase64String(outputBytes);
        }

原始散列对于彩虹表来说也存在漏洞,在彩虹表中,表内的每一条记录都是一串明文对应一种加密算法生成的一串密文。加盐就是指在密码中加入一个盐,这样可以提高密码散列的安全性。修改后的代码如下:

private static string CalculateSHA512Hash(string input,string salt)
      {
          byte[] saltBytes = Convert.FromBase64String(salt);
          byte[] inputBytes = Encoding.UTF8.GetBytes(input);
          byte[] inputWithSaltBytes = new byte[saltBytes.Length + inputBytes.Length];
          Array.Copy(inputBytes, 0, inputWithSaltBytes, 0, inputBytes.Length);
          Array.Copy(saltBytes, 0, inputWithSaltBytes, inputBytes.Length, saltBytes.Length);
          SHA512Managed sha512 = new SHA512Managed();
          byte[] outputBytes = sha512.ComputeHash(inputWithSaltBytes);
          return Convert.ToBase64String(outputBytes);
      }
      private static string GetSalt(int minSaltSize, int maxSaltSize)
      {
          Random random = new Random();
          int saltSize = random.Next(minSaltSize, maxSaltSize);
          byte[] saltBytes = new byte[saltSize];
          RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
          rng.GetNonZeroBytes(saltBytes);
          return Convert.ToBase64String(saltBytes);
      }

二 对称加密

private static string Encrypt(string input, byte[] key, byte[] iv)
      {
          byte[] inputBytes = Encoding.UTF8.GetBytes(input);
          RijndaelManaged rijndael = new RijndaelManaged();
          ICryptoTransform transform = rijndael.CreateEncryptor(key, iv);
          byte[] encrytData = null;
          using (MemoryStream outputStream = new MemoryStream())
          {
              using (CryptoStream inputStream = new CryptoStream(outputStream, transform, CryptoStreamMode.Write))
              {
                  inputStream.Write(inputBytes, 0, inputBytes.Length);
                  inputStream.FlushFinalBlock();
                  encrytData = outputStream.ToArray();
              }
 
          }
          return Convert.ToBase64String(encrytData);
      }
      private static string Decrypt(string input, byte[] key, byte[] iv)
      {
          byte[] inputBytes=Convert.FromBase64String(input);
          RijndaelManaged rijndael = new RijndaelManaged();
          ICryptoTransform transform = rijndael.CreateDecryptor(key, iv);
          byte[] decryptByte;
          using (MemoryStream outputStream=new MemoryStream())
          {
              using (CryptoStream inputStream=new CryptoStream(outputStream,transform,CryptoStreamMode.Write))
              {
                  inputStream.Write(inputBytes, 0, inputBytes.Length);
                  inputStream.FlushFinalBlock();
                  decryptByte = outputStream.ToArray();
              }
          }
          return Encoding.UTF8.GetString(decryptByte);
      }
      private static void GetKeyAndIVFromPasswordAndSalt(string password, byte[] salt, SymmetricAlgorithm symmetricAlgorithm,
          ref byte[] key, ref byte[] iv)
      {
          Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt);
          key = rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.KeySize / 8);
          iv = rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.BlockSize / 8);
      }
      private static string GetSalt(int minSaltSize, int maxSaltSize)
      {
          Random random = new Random();
          int saltSize = random.Next(minSaltSize, maxSaltSize);
          byte[] saltBytes = new byte[saltSize];
          RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
          rng.GetNonZeroBytes(saltBytes);
          return Convert.ToBase64String(saltBytes);
      }

调用方式:
            byte[] salt = Convert.FromBase64String(GetSalt(9, 18));
            string password = "Password";
            byte[] key=new byte[0];
            byte[] iv = new byte[0];
            GetKeyAndIVFromPasswordAndSalt(password,salt, new RijndaelManaged(), ref key, ref iv);
            string input = "Wrox Press";
            string encrytText = Encrypt(input, key, iv);
            Console.WriteLine(encrytText);
            string decryptText=Decrypt(encrytText,key,iv);
            Console.WriteLine(decryptText);

只是简单的加密和解密数据是不够的,我们还需要确保数据不被改变,我们可以创建一个消息认证代码来生成一个加密的散列。

private static string GenerateMac(string input, byte[] key)
      {
          HMACSHA512 hmac = new HMACSHA512(key);
          byte[] data= hmac.ComputeHash(Convert.FromBase64String(input));
          return Convert.ToBase64String(data);
      }
      static bool IsMacValid(string input, byte[] key, string savedMac)
      {
          string recalculateMac = GenerateMac(input, key);
          return recalculateMac.Equals(savedMac);
      }

例如我们对数据库中LicenseNumber加密,那么我们就必须修改表结构,修改后如图:

非对称加密:

private static string Encrypt(string input, string publickey)
       {
           RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
           rsa.FromXmlString(publickey);
           byte[] encryptData = rsa.Encrypt(Encoding.UTF8.GetBytes(input), true);
           return Convert.ToBase64String(encryptData);
       }
       private static string Decrypt(string input, string privatekey)
       {
           RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
           rsa.FromXmlString(privatekey);
           byte[] dencryptData = rsa.Decrypt(Convert.FromBase64String(input), true);
           return Encoding.UTF8.GetString(dencryptData);
       }
       private static void GetkeyXml(out string publicKey, out string privateKey)
       {
           RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
           publicKey = rsa.ToXmlString(false);
           privateKey = rsa.ToXmlString(true);
       }

证书加密:

static byte[] SignData(byte[] clearText, X509Certificate2 signingCertificate)
      {
          ContentInfo contentInfo = new ContentInfo(clearText);
          CmsSigner signer = new CmsSigner(signingCertificate);
          SignedCms signedCms = new SignedCms(contentInfo);
          signedCms.ComputeSignature(signer);
          return signedCms.Encode();
      }
      static byte[] ValidateSignatureAndExtractContent(byte[] signedCmsAsBytes, ICollection<string> signingSubjects)
      {
          SignedCms signedCms = new SignedCms();
          signedCms.Decode(signedCmsAsBytes);
          signedCms.CheckSignature(true);
          foreach (SignerInfo signerInfo in signedCms.SignerInfos)
          {
              X509Certificate2 signingCertificate = signerInfo.Certificate;
              signingSubjects.Add(signingCertificate.Subject);
          }
          return signedCms.ContentInfo.Content;
      }
      static byte[] EncryptWithCertificate(byte[] clearText, X509Certificate2 certificate)
      {
          ContentInfo contentInfo = new ContentInfo(clearText);
          EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo);
          CmsRecipient recipient = new CmsRecipient(certificate);
          envelopedCms.Encrypt(recipient);
          return envelopedCms.Encode();
      }
      static byte[] DecryptWithCertificate(byte[] cipherText)
      {
          EnvelopedCms envelopedCms = new EnvelopedCms();
          envelopedCms.Decode(cipherText);
          envelopedCms.Decrypt();
          return envelopedCms.ContentInfo.Content;
      }
      static X509Certificate2 LoadCertificateFromFile(string filename)
      {
          X509Certificate2 certificate = new X509Certificate2();
          certificate.Import(ReadBinaryFile(filename));
          return certificate;
      }
      static byte[] ReadBinaryFile(string filename)
      {
          FileStream f = new FileStream(filename, FileMode.Open, FileAccess.Read);
          int size = (int)f.Length;
          byte[] data = new byte[size];
          size = f.Read(data, 0, size);
          f.Close();
          return data;
      }
      private static X509Certificate2 GetCertificateBySubjectName(string subjectName)
      {
 
          X509Store myStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
              myStore.Open(OpenFlags.ReadOnly);
              X509Certificate2Collection certificateCollection = myStore.Certificates.Find(X509FindType.FindBySubjectName, subjectName, true);
              X509Certificate2 myCertificate = certificateCollection[0];
              if (myStore != null)
                  myStore.Close();
              return myCertificate;
      }

调用方式:

string input = "Wrox Press";
            byte[] clearTextAsBytes = Encoding.UTF8.GetBytes(input);
            X509Certificate2 serverPublicKeyCertificate = LoadCertificateFromFile("IISExpress.cer");
            X509Certificate2 signingCertificate = GetCertificateBySubjectName("test");
            byte[] signedClearText = SignData(clearTextAsBytes, signingCertificate);
            byte[] encryptedAndSignedData = EncryptWithCertificate(signedClearText, serverPublicKeyCertificate);

byte[] encodedUnencryptedCms = DecryptWithCertificate(encryptedAndSignedData);
            List<string> signingSubjects = new List<string>();
            byte[] receivedClearText = ValidateSignatureAndExtractContent(encodedUnencryptedCms, signingSubjects);
            string unecnryptedString = Encoding.UTF8.GetString(receivedClearText);
            Console.ReadLine();

我的计算机是win8,这里并没有用什么企业级证书,作为测试,我是用win8中IIS来创建自签名证书,然后用mmc来管理证书(http://softbbs.zol.com.cn/1/20_1370.html),所以以上的GetCertificateBySubjectName方法需要修改如下:

private static X509Certificate2 GetCertificateBySubjectName(string subjectName)
        {
            X509Store myStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            myStore.Open(OpenFlags.ReadOnly);

X509Certificate2Collection certificateCollection = myStore.Certificates.Find(X509FindType.FindBySubjectName, subjectName, true);
            X509Certificate2 myCertificate;
            if (certificateCollection.Count > 0)
            {
                myCertificate = certificateCollection[0];
            }
            else
            {
                X509Certificate2[] array = new X509Certificate2[myStore.Certificates.Count];
                myStore.Certificates.CopyTo(array, 0);
                myCertificate = array.FirstOrDefault(x => x.FriendlyName.Equals(subjectName));
            }
            if (myStore != null)
                myStore.Close();
            return myCertificate;
        }

 
 
 
标签: C#

C# 加密总结 一些常见的加密方法的更多相关文章

  1. IOS常见的加密方法,常用的MD5和Base64

    iOS代码加密常用加密方式 iOS代码加密常用加密方式,常见的iOS代码加密常用加密方式算法包括MD5加密.AES加密.BASE64加密,三大算法iOS代码加密是如何进行加密的,且看下文 MD5 iO ...

  2. 常见的加密和解密算法—DES

    一.DES加密概述 DES全称为Data Encryption Standard,即数据加密标准,是一种使用密钥加密的块算法,1977年被美国联邦政府的国家标准局确定为联邦资料处理标准(FIPS),并 ...

  3. 常见的加密和解密算法—MD5

    一.MD5加密概述 Message Digest Algorithm MD5(中文名为消息摘要算法第五版)为计算机安全领域广泛使用的一种散列函数,用以提供消息的完整性保护.该算法的文件号为RFC 13 ...

  4. python常见的加密方式

    1.前言 我们所说的加密方式都是对二进制编码的格式进行加密,对应到python中,则是我妈们的bytes. 所以当我们在Python中进行加密操作的时候,要确保我们的操作是bytes,否则就会报错. ...

  5. python爬虫之常见的加密方式

    前言 数据加密与解密通常是为了保证数据在传输过程中的安全性,自古以来就一直存在,古代主要应用在战争领域,战争中会有很多情报信息要传递,这些重要的信息都会经过加密,在发送到对应的人手上. 现代 ,在网络 ...

  6. android 对称加密,非对称加密 android 常见的加密

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha android 常见的加密 ======== 不可逆加密:md5,sha1 可逆的加密中 ...

  7. 常见的加密和解密算法—AES

    一.AES加密概述 高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准.这个标准用 ...

  8. 常见的加密和解密算法—BASE64

    一.BASE64加密和解密概述 Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,Base64编码可用于在HTTP环境下传递较长的标识信息.例如,在Java Persistence系 ...

  9. php使用N层加密eval gzinflate str_rot13 base64 破解方法汇总

    php使用N层加密eval gzinflate str_rot13 base64 破解方法汇总 来源:本站转载 作者:佚名 时间:2011-02-14 TAG: 我要投稿 PHP使用eval(gzin ...

随机推荐

  1. POJ 3311 Hie with the Pie floyd+状压DP

    链接:http://poj.org/problem?id=3311 题意:有N个地点和一个出发点(N<=10),给出全部地点两两之间的距离,问从出发点出发,走遍全部地点再回到出发点的最短距离是多 ...

  2. C语言中关键字auto、static、register、const、volatile、extern的作用

    原文:C语言中关键字auto.static.register.const.volatile.extern的作用 关键字auto.static.register.const.volatile.exter ...

  3. 我的MYSQL学习心得(十三)

    原文:我的MYSQL学习心得(十三) 我的MYSQL学习心得(十三) 我的MYSQL学习心得(一) 我的MYSQL学习心得(二) 我的MYSQL学习心得(三) 我的MYSQL学习心得(四) 我的MYS ...

  4. C#映射网络驱动器

    using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public class NetResource ...

  5. 谈谈那些年PHP中屌屌的验证码

    验证码已经是现在网站中非常基础的知识点了,验证码的存在可以防止恶意破解密码.刷票.灌水,可以有效的防止暴力破解特定用户. 现在就来了解了解那些年PHP中屌屌的验证码吧. 首先,以四位验证码为例(多位验 ...

  6. 一个可以直接使用的MsgBox基于form居中API

    可直接复制DialogBox项目(文件夹)到需要的项目中然后直接引用和using CodeProject.Dialog 已修正原作者代码错误的地方,可直接使用,VS2010测试成功 具体可以参考案例T ...

  7. C#编程实践–产假方案优化版

    前言 既然作为一个踏踏实实学习技术的人,就要有一颗谦卑.虚心和追求卓越的心,我不能一次就写出很完美的代码,但我相信,踏踏实实一步一步的优化,代码就可以变得趋近完美,至少在某一个特定场景下相对完美,这和 ...

  8. 【转】在PC上测试移动端网站和模拟手机浏览器的5大方法

    查了很多资料,尝试了大部分方法,下面将这一天的努力总结下分享给大家,也让大家免去看那么多文章,以下介绍的方法,都是本人亲自测试成功的方法,测试环境winxp. 一.Chrome*浏览器 chrome模 ...

  9. 解决ZF2_PATH environment

    本方法基于:ZendFramework 2.1.4版本在WIN7下构建,其他版本的安装方式相差不大. 操作之前您需要搭建好PHP运行环境,保证PHP版本不低于PHP 5.3.3,并且去http://f ...

  10. Linux系统编程:dup2()重定向

    对于Dup2 的理解: 源代码: #include <unistd.h> #include <stdio.h> #include <stdlib.h> #inclu ...