C# 加密引擎

C# 加密引擎,c#,.net,encryption,C#,.net,Encryption,现在我正在制作一个库,它将在C#Net中执行常见任务。基本上,我的目标是C#初学者,这样他们就可以从我的库中获益,并使用它来最大限度地减少他们遇到的困难。我目前正在将加密功能添加到我的库中,并取得了一些成功。但我的加密标准不是很难和复杂。这样,将来任何黑客都可以突破并解密重要数据(如密码等)。因此,请告诉我如何编写自己的复杂标准来加密密码。这个图书馆是免费的,仅供初学者使用 谢谢我建议您不要在没有很好理由的情况下编写自己的加密引擎,因为已经有很多加密引擎了-首先,请查看中的加密API。它对初学者

现在我正在制作一个库,它将在C#Net中执行常见任务。基本上,我的目标是C#初学者,这样他们就可以从我的库中获益,并使用它来最大限度地减少他们遇到的困难。我目前正在将加密功能添加到我的库中,并取得了一些成功。但我的加密标准不是很难和复杂。这样,将来任何黑客都可以突破并解密重要数据(如密码等)。因此,请告诉我如何编写自己的复杂标准来加密密码。这个图书馆是免费的,仅供初学者使用


谢谢

我建议您不要在没有很好理由的情况下编写自己的加密引擎,因为已经有很多加密引擎了-首先,请查看中的加密API。它对初学者非常友好


如果您仍决心编写自己的框架,请查看Enterprise Library,以及其他类似的工具,看看其他框架是如何组合在一起的-您将学到很多东西,这是尝试和改进现有框架的最佳方法。

当存在大量现有库时,不要选择您自己的库。你不会从中受益,也不会有任何用处。一句谚语:不要只为了喝一杯茶而购买自助餐厅。

你可以围绕.NET加密方法编写易于使用的包装

Aes示例(我自己的包装器):

使用系统;
使用System.IO;
使用System.Security.Cryptography;
使用系统文本;
使用Synercoding.CodeGuard;
命名空间SynerCodeing.Encryption.Symmetric
{
/// 
///使用Rijndael AES加密进行加密和解密的类
/// 
公共密封类加密:IDisposable
{
专用字节[]m_salt;
私有RijndaelManaged m_aesAlg=new RijndaelManaged();//用于加密/解密数据的RijndaelManaged对象。
/// 
///使用标准salt创建新的AesEncryption对象
/// 
public AESEencryption():此(“850nW94vN39iUx”){}
/// 
///使用指定的salt创建新的AesEncryption对象
/// 
///用来腌制钥匙的盐。必须至少有8个字符长
公共加密(字符串盐)
{
需要(!string.IsNullOrEmpty(salt),“param salt不能为null或空。”);
Guard.Requires(salt.Length>=8,“param salt必须至少有8个字符长”);
m_salt=Encoding.ASCII.GetBytes(salt);
}
/// 
///salt以ASCII字符串格式显示
/// 
公共字符串
{
得到
{
返回Encoding.ASCII.GetString(m_salt);
}
}
/// 
///用于密钥和IV生成的盐。
/// 
公共字节[]盐
{
得到
{
返回m_盐;
}
}
/// 
///使用AES加密给定字符串。可以使用
///DecryptStringAES()。sharedSecret参数必须匹配。
/// 
///要加密的文本。
///用于生成加密密钥的密码。
公共字符串EncryptStringAES(字符串明文、字符串共享秘密)
{
需要(!string.IsNullOrEmpty(明文),“参数明文不能为null或空”);
需要(!string.IsNullOrEmpty(sharedSecret),“参数sharedSecret不能为null或空”);
Requires(m_aesAlg!=null,“此对象已被处置”);
string outStr=null;//要返回的加密字符串
//从共享密钥和salt生成密钥
Rfc2898DeriveBytes键=新的Rfc2898DeriveBytes(sharedSecret,Salt);
m_aesAlg.Key=Key.GetBytes(m_aesAlg.KeySize/8);
m_aesAlg.IV=key.GetBytes(m_aesAlg.BlockSize/8);
//创建decrytor以执行流变换。
ICryptoTransform encryptor=m_aesAlg.CreateEncryptor(m_aesAlg.Key,m_aesAlg.IV);
//创建用于加密的流。
使用(MemoryStream msEncrypt=new MemoryStream())
{
使用(CryptoStream csEncrypt=new CryptoStream(msEncrypt,encryptor,CryptoStreamMode.Write))
使用(StreamWriter swEncrypt=newstreamwriter(csEncrypt))
{
//将所有数据写入流。
书写(纯文本);
}
outStr=Convert.ToBase64String(msEncrypt.ToArray());
}
//从内存流返回加密的字节。
回报率;
}
/// 
///解密给定字符串。假定该字符串是使用
///EncryptStringAES(),使用相同的sharedSecret。
/// 
///要解密的文本。
///用于生成解密密钥的密码。
公共字符串解密字符串AES(字符串密文、字符串共享密文)
{
需要(!string.IsNullOrEmpty(cipherText),“参数cipherText不能为null或空”);
需要(!string.IsNullOrEmpty(sharedSecret),“参数sharedSecret不能为null或空”);
Requires(m_aesAlg!=null,“此对象已被处置”);
//声明用于保存的字符串
//解密的文本。
字符串明文=空;
//从共享密钥和salt生成密钥
Rfc2898DeriveBytes键=新的Rfc2898DeriveBytes(sharedSecret,Salt);
m_aesAlg.Key=Key.GetBytes(m_aesAlg.KeySize/8);
m_aesAlg.IV=key.GetBytes(m_aesAlg.BlockSize/8);
//创建decrytor以执行流变换。
ICryptoTransform decryptor=m_aesAlg.CreateDecryptor(m_aesAlg.Key,m_aesAlg.IV);
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

using Synercoding.CodeGuard;

namespace Synercoding.Encryption.Symmetrical
{
    /// <summary>
    /// A class to Encrypt and Decrypt with Rijndael AES encryption
    /// </summary>
    public sealed class AesEncryption : IDisposable
    {
        private byte[] m_salt;
        private RijndaelManaged m_aesAlg = new RijndaelManaged(); // RijndaelManaged object used to encrypt/decrypt the data.

        /// <summary>
        /// Create a new AesEncryption object with the standard salt
        /// </summary>
        public AesEncryption() : this("850nW94vN39iUx") { }

        /// <summary>
        /// Create a new AesEncryption object with the specified salt
        /// </summary>
        /// <param name="salt">The salt used for salting the key. Must be atleast 8 chars long</param>
        public AesEncryption(string salt)
        {
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(salt), "param salt can't be null or empty.");
            Guard.Requires<ArgumentException>(salt.Length >= 8, "param salt must be atleast 8 chars long.");
            m_salt = Encoding.ASCII.GetBytes(salt);
        }

        /// <summary>
        /// The salt in ASCII string format
        /// </summary>
        public string SaltString
        {
            get
            {
                return Encoding.ASCII.GetString(m_salt);
            }
        }

        /// <summary>
        /// The salt that is used for the key and IV generation.
        /// </summary>
        public byte[] Salt
        {
            get
            {
                return m_salt;
            }
        }

        /// <summary>
        /// Encrypt the given string using AES.  The string can be decrypted using 
        /// DecryptStringAES().  The sharedSecret parameters must match.
        /// </summary>
        /// <param name="plainText">The text to encrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
        public string EncryptStringAES(string plainText, string sharedSecret)
        {
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(plainText), "param plainText can't be null or empty");
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(sharedSecret), "param sharedSecret can't be null or empty");
            Guard.Requires<InvalidOperationException>(m_aesAlg != null, "this object is already disposed");

            string outStr = null;                       // Encrypted string to return

            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, Salt);

            m_aesAlg.Key = key.GetBytes(m_aesAlg.KeySize / 8);
            m_aesAlg.IV = key.GetBytes(m_aesAlg.BlockSize / 8);


            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = m_aesAlg.CreateEncryptor(m_aesAlg.Key, m_aesAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                {

                    //Write all data to the stream.
                    swEncrypt.Write(plainText);
                }

                outStr = Convert.ToBase64String(msEncrypt.ToArray());
            }

            // Return the encrypted bytes from the memory stream.
            return outStr;
        }

        /// <summary>
        /// Decrypt the given string.  Assumes the string was encrypted using 
        /// EncryptStringAES(), using an identical sharedSecret.
        /// </summary>
        /// <param name="cipherText">The text to decrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
        public string DecryptStringAES(string cipherText, string sharedSecret)
        {
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(cipherText), "param cipherText can't be null or empty");
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(sharedSecret), "param sharedSecret can't be null or empty");
            Guard.Requires<InvalidOperationException>(m_aesAlg != null, "this object is already disposed");

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, Salt);

            m_aesAlg.Key = key.GetBytes(m_aesAlg.KeySize / 8);
            m_aesAlg.IV = key.GetBytes(m_aesAlg.BlockSize / 8);

            // Create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = m_aesAlg.CreateDecryptor(m_aesAlg.Key, m_aesAlg.IV);
            // Create the streams used for decryption.                
            byte[] bytes = Convert.FromBase64String(cipherText);
            using (MemoryStream msDecrypt = new MemoryStream(bytes))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                }
            }

            return plaintext;
        }

        public void Dispose()
        {
            if (m_aesAlg != null)
            {
                m_aesAlg.Clear();
                m_aesAlg.Dispose();
                m_aesAlg = null;
            }
        }
    }
}
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

using Synercoding.CodeGuard;

namespace Synercoding.Encryption.Hashing
{
    /// <summary>
    /// Class to verify and generate MD5 hashes
    /// </summary>
    public static class MD5Hash
    {
        /// <summary>
        /// Creates a MD5 hexadecimal string based on the input
        /// </summary>
        /// <param name="input">The string to hash</param>
        /// <returns>A MD5 hex string</returns>
        public static string GetHash(string input)
        {
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(input), "param input can't be null or empty");

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            using (MD5 md5Hash = MD5.Create())
            {
                // Convert the input string to a byte array and compute the hash.
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

                // Loop through each byte of the hashed data 
                // and format each one as a hexadecimal string.
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

        /// <summary>
        /// Creates a MD5 hexadecimal string based on the input
        /// </summary>
        /// <param name="input">The string to hash</param>
        /// <returns>A MD5 hash in byte format</returns>
        public static byte[] GetByteHash(string input)
        {
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(input), "param input can't be null or empty");

            byte[] data;
            using (MD5 md5Hash = MD5.Create())
            {
                // Convert the input string to a byte array and compute the hash.
                data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            }

            return data;
        }

        /// <summary>
        /// Verifies the input with the hash.
        /// </summary>
        /// <param name="input">The input to compare</param>
        /// <param name="hash">The hash to compare the input with</param>
        /// <returns>True is the input validates.</returns>
        public static bool VerifyHash(string input, string hash)
        {
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(input), "param input can't be null or empty");
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(hash), "param hash can't be null or empty");
            Guard.Requires<ArgumentNullException>(hash.Length == 32, "param hash must be 32 chars long");

            // Hash the input.
            string hashOfInput = GetHash(input);

            // Create a StringComparer an compare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Verifies the input with the hash.
        /// </summary>
        /// <param name="input">The input to compare</param>
        /// <param name="hash">The hash to compare the input with</param>
        /// <returns>True is the input validates.</returns>
        public static bool VerifyHash(string input, byte[] hash)
        {
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(input), "param input can't be null or empty");
            Guard.Requires<ArgumentNullException>(hash != null, "param hash can't be null");
            Guard.Requires<ArgumentNullException>(hash.Length == 128 / 8, "param hash must be 128bits (16 bytes) long");

            // Hash the input.
            byte[] hashOfInput = GetByteHash(input);

            if (hashOfInput.SequenceEqual(hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

using Synercoding.CodeGuard;

namespace Synercoding.Encryption.Hashing
{
    /// <summary>
    /// Class to verify and generate SHA512 hashes
    /// </summary>
    public static class SHA512Hash
    {
        /// <summary>
        /// Creates a SHA512 hexadecimal string based on the input
        /// </summary>
        /// <param name="input">The string to hash</param>
        /// <returns>A SHA512 hex string</returns>
        public static string GetHash(string input)
        {
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(input), "param input can't be null or empty");

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            using (SHA512 SHA512Hash = SHA512.Create())
            {
                // Convert the input string to a byte array and compute the hash.
                byte[] data = SHA512Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

                // Loop through each byte of the hashed data 
                // and format each one as a hexadecimal string.
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

        /// <summary>
        /// Creates a SHA512 hash based on the input
        /// </summary>
        /// <param name="input">The string to hash</param>
        /// <returns>A SHA512 hash in byte format</returns>
        public static byte[] GetByteHash(string input)
        {
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(input), "param input can't be null or empty");

            byte[] data;

            using (SHA512 SHA512Hash = SHA512.Create())
            {
                // Convert the input string to a byte array and compute the hash.
                data = SHA512Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            }

            return data;
        }

        /// <summary>
        /// Verifies the input with the hash.
        /// </summary>
        /// <param name="input">The input to compare</param>
        /// <param name="hash">The hash to compare the input with</param>
        /// <returns>True is the input validates.</returns>
        public static bool VerifyHash(string input, string hash)
        {
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(input), "param input can't be null or empty");
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(hash), "param hash can't be null or empty");
            Guard.Requires<ArgumentNullException>(hash.Length == 128, "param hash must be 128 chars long");

            // Hash the input.
            string hashOfInput = GetHash(input);

            // Create a StringComparer an compare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Verifies the input with the hash.
        /// </summary>
        /// <param name="input">The input to compare</param>
        /// <param name="hash">The hash to compare the input with</param>
        /// <returns>True is the input validates.</returns>
        public static bool VerifyHash(string input, byte[] hash)
        {
            Guard.Requires<ArgumentNullException>(!string.IsNullOrEmpty(input), "param input can't be null or empty");
            Guard.Requires<ArgumentNullException>(hash != null, "param hash can't be null");
            Guard.Requires<ArgumentNullException>(hash.Length == 512 / 8, "param hash must be 512bits (64 bytes) long");

            // Hash the input.
            byte[] hashOfInput = GetByteHash(input);

            if (hashOfInput.SequenceEqual(hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
System.IO.File.Encrypt("file.txt")
System.IO.File.Decrypt("file.txt")