• net中System.Security.Cryptography 命名空间 下的加密算法


    .net中System.Security.Cryptography命名空间

    在.NETFramework出现之前,如果我们需要进行加密的话,我们只有各种较底层的技术可以选择,如 Microsoft Crypto API、Crypto++、Openssl等等,其用法相当复杂。而在 .NET Framework中,这些复杂内容已经被封装在各个 .NET 框架类中,并且由一个System.Security.Cryptography 命名空间包含这些与加密、签名相关的类。利用这些类,我们就可以很方便地使用各种广泛使用的算法,包括RSA, DSA, Rijndael, SHA和其他Hash算法等等。

    首先,我们了解一下加密中的一些基本术语:

     

    对称加密算法

    加密算法的一般类型有对称和非对称两种。对称算法使用相同的密钥来加密和解密数据。对称密钥密码算法所用的加密密钥和解密密钥通常是相同的,即使不同也可以很容易地由其中的任意一个推导出另一个。在此算法中,加、解密双方所用的密钥都要保守秘密。由于计算速度快,对称加密算法被广泛应用于大量数据,如文件的加密过程中。

    使用分组密码算法数字签名常用的加密标准有:DES,Tripl-DES,RC2,RC4,CAST等。

    .NET Framework提供了以下类来实现对称加密算法:

    DESCryptoServiceProvider

    RC2CryptoServiceProvider

    RijndaelManaged

    TripleDESCryptoServiceProvider

    下面是一个DESCryptoServiceProvider类的应用实例:

    下面的示例使用 DESCryptoServiceProvider 类将一些数据加密到内存,然后解密数据。

    //This sample demonstrates using a key based on the cryptographic serviceprovider (CSP) version
    // of the Data Encryption Standard (DES)algorithm toencrypt a string to a byte array, and then
    // to decrypt the byte array back to a string.

    using System;
    using System.IO;
    using System.Text;
    using System.Security.Cryptography;

    class CryptoMemoryStream
    {
    // Main method.
    public static void Main()
    {
    // Create a new DES key.
    DESCryptoServiceProvider key = newDESCryptoServiceProvider();

    // Encrypt a string to a byte array.
    byte[] buffer = Encrypt("This is some plaintext!", key);

    // Decrypt the byte array back to a string.
    string plaintext = Decrypt(buffer, key);

    // Display the plaintext value to the console.
    Console.WriteLine(plaintext);
    }

    // Encrypt the string.
    public static byte[] Encrypt(stringPlainText, SymmetricAlgorithm key)
    {
    // Create a memory stream.
    MemoryStream ms = new MemoryStream();

    // Create a CryptoStream using the memory stream andthe
    // CSP DES key.
    CryptoStream encStream = new CryptoStream(ms,key.CreateEncryptor(), CryptoStreamMode.Write);

    // Create a StreamWriter to write a string
    // to the stream.
    StreamWriter sw = new StreamWriter(encStream);

    // Write the plaintext to the stream.
    sw.WriteLine(PlainText);

    // Close the StreamWriter and CryptoStream.
    sw.Close();
    encStream.Close();

    // Get an array of bytes that represents
    // the memory stream.
    byte[] buffer = ms.ToArray();

    // Close the memory stream.
    ms.Close();

    // Return the encrypted byte array.
    return buffer;
    }

    // Decrypt the byte array.
    public static string Decrypt(byte[]CypherText, SymmetricAlgorithm key)
    {
    // Create a memory stream to the passed buffer.
    MemoryStream ms = new MemoryStream(CypherText);

    // Create a CryptoStream using the memory stream andthe
    // CSP DES key.
    CryptoStream encStream = new CryptoStream(ms,key.CreateDecryptor(), CryptoStreamMode.Read);

    // Create a StreamReader for reading the stream.
    StreamReader sr = new StreamReader(encStream);

    // Read the stream as a string.
    string val = sr.ReadLine();

    // Close the streams.
    sr.Close();
    encStream.Close();
    ms.Close();

    return val;
    }
    }

    公共钥匙加密算法 (非对称密钥密码算法)

    公共钥匙加密算法又称为非对称密钥密码算法。它使用到两个密钥:公开密钥和私有密钥,分别用于对数据的加密和解密,即如果用公开密钥对数据进行加密,只有用对应的私有密钥才能进行解密;如果用私有密钥对数据进行加密,则只有用对应的公开密钥才能解密。

    使用公钥密码算法进行数字签名通用的加密标准有: RSA,DSA等。

    .NET Framework提供了以下类来实现公共钥匙加密算法(非对称加密算法):

    DSACryptoServiceProvider

    RSACryptoServiceProvider

    下面是一个RSACryptoServiceProvider类的应用实例:

    //获取密钥和公钥
    public void RSAKey(out string xmlKeys, out string xmlPublicKey)
    {
    try
    {
    System.Security.Cryptography.RSACryptoServiceProvider rsa = newRSACryptoServiceProvider();
    xmlKeys = rsa.ToXmlString(true);
    xmlPublicKey = rsa.ToXmlString(false);
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }
    //RSA的加密函数
    public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
    {
    try
    {
    byte[] PlainTextBArray;
    byte[] CypherTextBArray;
    string Result;
    System.Security.Cryptography.RSACryptoServiceProvider rsa = newRSACryptoServiceProvider();
    rsa.FromXmlString(xmlPublicKey);
    PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString);
    CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
    Result = Convert.ToBase64String(CypherTextBArray);
    return Result;
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }
    //RSA的加密函数
    public string RSAEncrypt(string xmlPublicKey, byte[] EncryptString)
    {
    try
    {
    byte[] CypherTextBArray;
    string Result;
    System.Security.Cryptography.RSACryptoServiceProvider rsa = newRSACryptoServiceProvider();
    rsa.FromXmlString(xmlPublicKey);
    CypherTextBArray = rsa.Encrypt(EncryptString, false);
    Result = Convert.ToBase64String(CypherTextBArray);
    return Result;
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }


    //RSA的解密函数
    public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)
    {
    try
    {
    byte[] PlainTextBArray;
    byte[] DypherTextBArray;
    string Result;
    System.Security.Cryptography.RSACryptoServiceProvider rsa = newRSACryptoServiceProvider();
    rsa.FromXmlString(xmlPrivateKey);
    PlainTextBArray = Convert.FromBase64String(m_strDecryptString);

    //XP版本以上为true
    DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
    Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
    return Result;
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }

    //RSA的解密函数
    public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString)
    {
    try
    {
    byte[] DypherTextBArray;
    string Result;
    System.Security.Cryptography.RSACryptoServiceProvider rsa = newRSACryptoServiceProvider();
    rsa.FromXmlString(xmlPrivateKey);
    DypherTextBArray = rsa.Decrypt(DecryptString, false );
    Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
    return Result;
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }

    数字签名

    数字签名是指使用密码算法对待发的数据(报文、票证等)进行加密处理,生成一段信息,附着在原文上一起发送,这段信息类似现实中的签名或印章,接收方对其进行验证,判断原文真伪。

    目的:提供数据完整性保护和抗否认功能。

    .NET Framework提供了以下类来实现数字签名加密算法:

    DSACryptoServiceProvider

    RSACryptoServiceProvider

    Hash 算法

    Hash算法也称作散列算法或报文摘要(digital digest)。Hash算法将任意长度数据转化为固定长度字符序列。Hash结果是始终维一的。任意二个序列的Hash结果是不同的。Hash结果亦称为数字指纹(Finger Print),它有固定的长度,且相同的明文摘要必定一致。这样这串摘要使可成为验证明文是否是"真身"的"指纹"了。

    Hash算法数字签字通用的加密标准有: SHA-1,MD5等。

    .NET Framework提供了以下类来实现加密Hash算法:

    HMACSHA1

    MACTripleDES

    MD5CryptoServiceProvider

    SHA1Managed

    SHA256Managed

    SHA384Managed

    SHA512Managed

    下面是一个SHA512Managed类的应用实例:

    面的示例计算 dataSHA512Managed 哈希值,并将它存储在 result 中。此示例假定存在一个预定义的常数 DATA_SIZE

    byte[] data = new byte[DATA_SIZE];

    byte[] result;

     

    SHA512 shaM= new SHA512Managed();

    result =shaM.ComputeHash(data);

    其他

    自定义算法:

    在machine.config中 .NET 定义了cryptography 设置的Schema。 我们可以通过在machine.config 中的定义,来实现替代某些已有算法并调用自定义算法:

    具体的方法,可以参考MSDN中的信息:

    Cryptography Settings Schema

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/gngrfcryptographysettingsschema.asp

    Configuring Cryptography

    <mscorlib><cryptographySettings> <cryptoNameMapping> <cryptoClasses><cryptoClass myMD5="System.Security.Cryptography.MD5CryptoServiceProvider, mscorlib,Ver=1.0.2411.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/></cryptoClasses> <nameEntry name="dan"class="myMD5"/> <nameEntryname="System.Security.Cryptography.HashAlgorithm"class="myMD5"/> </cryptoNameMapping></cryptographySettings></mscorlib>

    X.509数字证书

    在System.Security.Cryptography.X509Certificates命名空间中,.NET Framework包含了X.509 v.3数字证书的实现。

    XML数字签名

    在System.Security.Cryptography.XML命名空间中,.NET Framework包含了XML数字签名实现。通过调用该命名空间中的类,我们可以实现对XML对象进行数字签名。

    总结

    总而言之,.NETFramework 中的System.Security.Cryptography命名空间实现了各类加密,签名的实现。通过调用相应的类库,我们可以很方便地实现各类加密,签名的操作。

    System.Security.Cryptography 命名空间的具体定义,我们可以在以下链接找到:

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemsecuritycryptography.asp

    http://msdn.microsoft.com/zh-cn/library/system.security.cryptography.aspx

  • 相关阅读:
    一些Vim使用的小技巧
    virtualbox centos安装增强工具和Centos与VirtualBox共享文件夹设置
    (转) centos7 RPM包之rpm命令
    (转)Navicat_12安装与破解,亲测可用!!!
    (转)2019年 React 新手学习指南 – 从 React 学习线路图说开去
    (转)react 项目构建
    (转)python3:类方法,静态方法和实例方法以及应用场景
    (转)SQLAlchemy入门和进阶
    (转)面向对象(深入)|python描述器详解
    (转)CentOS 7.6 上编译安装httpd 2.4.38
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/5039335.html
Copyright © 2020-2023  润新知