C# 字符串加密

  最近在学习一些加密的东西,现在对C#加密代码进行整理:

1、对称加密;

 /// <summary>
    /// 加密
    /// </summary>
    /// <param name="pToEncrypt"></param>
    /// <param name="sKey"></param>
    /// <returns></returns>
    public static string Encrypt(string pToEncrypt, string sKey)
    {
        System.Security.Cryptography.DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
        des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
        des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        StringBuilder ret = new StringBuilder();
        foreach (byte b in ms.ToArray())
        {
            ret.AppendFormat("{0:X2}", b);
        }
        ret.ToString();
        return ret.ToString();

    }

2、对称解密

 ///解密
    public static string Decrypt(string pToDecrypt, string sKey)
    {
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();

        byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
        for (int x = 0; x < pToDecrypt.Length / 2; x++)
        {
            int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
            inputByteArray[x] = (byte)i;
        }

        des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
        des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();

        StringBuilder ret = new StringBuilder();

        return System.Text.Encoding.Default.GetString(ms.ToArray());
    }
3、MD5加密

 //md5 加密
    public static string MD5Encrypt(string strText)
    {
        // Create a new instance of the MD5CryptoServiceProvider object.
        MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();

        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(strText));

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

        // 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();
    } 

4、通过流路径得到MD5值

public static string GetMd5Hash(Stream input)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] data = md5Hasher.ComputeHash(input);
            input.Seek(0, SeekOrigin.Begin);
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }

5、通过文件路径获取文件MD5值

public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }

6、字符串MD5比较

// Verify a hash against a string. md5值不区分大小写
       public static bool VerifyMd5Hash(string input, string hash)
        {
            // Hash the input.
            string hashOfInput = getMd5Hash(input);

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

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


7、RSA非对称加密

//RSA加密,随机生成公私钥对并作为出参返回
    public static string RSA_Encrypt(string str_Plain_Text, out string str_Public_Key, out string str_Private_Key)
    {
        str_Public_Key = "";
        str_Private_Key = "";
        UnicodeEncoding ByteConverter = new UnicodeEncoding();
        byte[] DataToEncrypt = ByteConverter.GetBytes(str_Plain_Text);
        try
        {
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            str_Public_Key = Convert.ToBase64String(RSA.ExportCspBlob(false));
            str_Private_Key = Convert.ToBase64String(RSA.ExportCspBlob(true));
          
            //OAEP padding is only available on Microsoft Windows XP or later. 
            byte[] bytes_Cypher_Text = RSA.Encrypt(DataToEncrypt, false);
            str_Public_Key = Convert.ToBase64String(RSA.ExportCspBlob(false));
            str_Private_Key = Convert.ToBase64String(RSA.ExportCspBlob(true));
            string str_Cypher_Text = Convert.ToBase64String(bytes_Cypher_Text);
            return str_Cypher_Text;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);
            return null;
        }
    }
<pre name="code" class="csharp">//RSA解密
    static public string RSA_Decrypt(string str_Cypher_Text, string str_Private_Key)
    {
        byte[] DataToDecrypt = Convert.FromBase64String(str_Cypher_Text);
        try
        {
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            //RSA.ImportParameters(RSAKeyInfo);
            byte[] bytes_Public_Key = Convert.FromBase64String(str_Private_Key);
            RSA.ImportCspBlob(bytes_Public_Key);
           
            //OAEP padding is only available on Microsoft Windows XP or later. 
            byte[] bytes_Plain_Text = RSA.Decrypt(DataToDecrypt, false);
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            string str_Plain_Text = ByteConverter.GetString(bytes_Plain_Text);
            return str_Plain_Text;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.ToString());
            return null;
        }
    }


 

更多内容请参考:

http://www.cnblogs.com/jfzhu/p/4020928.html

http://www.cnblogs.com/tongyi/p/4274092.html

http://blog.sina.com.cn/s/blog_4dd7300501008b5x.html

http://pmd5.com/?action=getpwd#  MD5解密地址



  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值