C#常用字符串加密解密方法封装代码

代码如下:

//方法一
//须添加对System.Web的引用
//using System.Web.Security;
/// <summary>
/// SHA1加密字符串
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>加密后的字符串</returns>
public string SHA1(string source)
{
    return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1");
}
/// <summary>
/// MD5加密字符串
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>加密后的字符串</returns>
public string MD5(string source)
{
    return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");;
}

//方法二(可逆加密解密):
//using System.Security.Cryptography;
public string Encode(string data)
{
    byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
    byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
    DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
    int i = cryptoProvider.KeySize;
    MemoryStream ms = new MemoryStream();
    CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
    StreamWriter sw = new StreamWriter(cst);
    sw.Write(data);
    sw.Flush();
    cst.FlushFinalBlock();
    sw.Flush();
    return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
}
public string Decode(string data)
{
    byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
    byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
    byte[] byEnc;
    try
    {
        byEnc = Convert.FromBase64String(data);
    }
    catch
    {
        return null;
    }
    DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
    MemoryStream ms = new MemoryStream(byEnc);
    CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
    StreamReader sr = new StreamReader(cst);

//方法三(MD5不可逆):
//using System.Security.Cryptography;
//MD5不可逆加密
//32位加密
public string GetMD5_32(string s, string _input_charset)
{
    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
    StringBuilder sb = new StringBuilder(32);
    for (int i = 0; i < t.Length; i++)
    {
        sb.Append(t[i].ToString("x").PadLeft(2, '0'));
    }
    return sb.ToString();
}
//16位加密
public static string GetMd5_16(string ConvertString)
{
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
    string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
    t2 = t2.Replace("-", "");
    return t2;
}

//方法四(对称加密):
//using System.IO;
//using System.Security.Cryptography;
private SymmetricAlgorithm mobjCryptoService;
private string Key;
/// <summary>  
/// 对称加密类的构造函数  
/// </summary>  
public SymmetricMethod()
{
    mobjCryptoService = new RijndaelManaged();
    Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
}
/// <summary>  
/// 获得密钥  
/// </summary>  
/// <returns>密钥</returns>  
private byte[] GetLegalKey()
{
    string sTemp = Key;
    mobjCryptoService.GenerateKey();
    byte[] bytTemp = mobjCryptoService.Key;
    int KeyLength = bytTemp.Length;
    if (sTemp.Length > KeyLength)
        sTemp = sTemp.Substring(0, KeyLength);
    else if (sTemp.Length < KeyLength)
        sTemp = sTemp.PadRight(KeyLength, ' ');
    return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
/// <summary>  
/// 获得初始向量IV  
/// </summary>  
/// <returns>初试向量IV</returns>  
private byte[] GetLegalIV()
{
    string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
    mobjCryptoService.GenerateIV();
    byte[] bytTemp = mobjCryptoService.IV;
    int IVLength = bytTemp.Length;
    if (sTemp.Length > IVLength)
        sTemp = sTemp.Substring(0, IVLength);
    else if (sTemp.Length < IVLength)
        sTemp = sTemp.PadRight(IVLength, ' ');
    return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
/// <summary>  
/// 加密方法  
/// </summary>  
/// <param name="Source">待加密的串</param>  
/// <returns>经过加密的串</returns>  
public string Encrypto(string Source)
{
    byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
    MemoryStream ms = new MemoryStream();
    mobjCryptoService.Key = GetLegalKey();
    mobjCryptoService.IV = GetLegalIV();
    ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
    CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
    cs.Write(bytIn, 0, bytIn.Length);
    cs.FlushFinalBlock();
    ms.Close();
    byte[] bytOut = ms.ToArray();
    return Convert.ToBase64String(bytOut);
}
/// <summary>  
/// 解密方法  
/// </summary>  
/// <param name="Source">待解密的串</param>  
/// <returns>经过解密的串</returns>  
public string Decrypto(string Source)
{
    byte[] bytIn = Convert.FromBase64String(Source);
    MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
    mobjCryptoService.Key = GetLegalKey();
    mobjCryptoService.IV = GetLegalIV();
    ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
    CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
    StreamReader sr = new StreamReader(cs);
    return sr.ReadToEnd();
}

//方法五:
//using System.IO;
//using System.Security.Cryptography;
//using System.Text;
//默认密钥向量
private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
/**//**//**//// <summary>
/// DES加密字符串 keleyi.com
/// </summary>
/// <param name="encryptString">待加密的字符串</param>
/// <param name="encryptKey">加密密钥,要求为8位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public static string EncryptDES(string encryptString, string encryptKey)
{
    try
    {
        byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
        byte[] rgbIV = Keys;
        byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
        DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
        MemoryStream mStream = new MemoryStream();
        CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
        cStream.Write(inputByteArray, 0, inputByteArray.Length);
        cStream.FlushFinalBlock();
        return Convert.ToBase64String(mStream.ToArray());
    }
    catch
    {
        return encryptString;
    }
}
/**//**//**//// <summary>
/// DES解密字符串 keleyi.com
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
public static string DecryptDES(string decryptString, string decryptKey)
{
    try
    {
        byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
        byte[] rgbIV = Keys;
        byte[] inputByteArray = Convert.FromBase64String(decryptString);
        DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
        MemoryStream mStream = new MemoryStream();
        CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
        cStream.Write(inputByteArray, 0, inputByteArray.Length);
        cStream.FlushFinalBlock();
        return Encoding.UTF8.GetString(mStream.ToArray());
    }
    catch
    {
        return decryptString;
    }
}

//方法六(文件加密):
//using System.IO;
//using System.Security.Cryptography;
//using System.Text;
//加密文件
private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
{
    //Create the file streams to handle the input and output files.
    FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
    FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
    fout.SetLength(0);
    //Create variables to help with read and write.
    byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
    long rdlen = 0;              //This is the total number of bytes written.
    long totlen = fin.Length;    //This is the total length of the input file.
    int len;                     //This is the number of bytes to be written at a time.
    DES des = new DESCryptoServiceProvider();
    CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
    //Read from the input file, then encrypt and write to the output file.
    while (rdlen < totlen)
    {
        len = fin.Read(bin, 0, 100);
        encStream.Write(bin, 0, len);
        rdlen = rdlen + len;
    }
    encStream.Close();
    fout.Close();
    fin.Close();
}
//解密文件
private static void DecryptData(String inName, String outName, byte[] desKey, byte[] desIV)
{
    //Create the file streams to handle the input and output files.
    FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
    FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
    fout.SetLength(0);
    //Create variables to help with read and write.
    byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
    long rdlen = 0;              //This is the total number of bytes written.
    long totlen = fin.Length;    //This is the total length of the input file.
    int len;                     //This is the number of bytes to be written at a time.
    DES des = new DESCryptoServiceProvider();
    CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
    //Read from the input file, then encrypt and write to the output file.
    while (rdlen < totlen)
    {
        len = fin.Read(bin, 0, 100);
        encStream.Write(bin, 0, len);
        rdlen = rdlen + len;
    }
    encStream.Close();
    fout.Close();
    fin.Close();
    return sr.ReadToEnd();
}

(0)

相关推荐

  • c#多种加解密示例(md5加密解密)

    复制代码 代码如下: using System;using System.Collections.Generic;using System.Globalization;using System.IO;using System.Security.Cryptography;using System.Text; /// <summary>/// 加解密/// </summary>public static class CryptHelper{    #region RSA加密 /// &

  • C# RSA分段加解密实现方法详解

    本文实例讲述了C# RSA分段加解密实现方法.分享给大家供大家参考,具体如下: RSA加解密: 1024位的证书,加密时最大支持117个字节,解密时为128: 2048位的证书,加密时最大支持245个字节,解密时为256. 加密时支持的最大字节数:证书位数/8 -11(比如:2048位的证书,支持的最大加密字节数:2048/8 - 11 = 245) .NET中的RSA加密算法为了提高安全性,在待加密数据前要添加一些随机数,因此,使用.NET中的RSA加密算法一次最多加密117字节数据(多于11

  • C#实现对AES加密和解密的方法

    AES简介 AES(The Advanced Encryption Standard)是美国国家标准与技术研究所用于加密电子数据的规范.它被预期能成为人们公认的加密包括金融.电信和政府数字信息的方法. AES 是一个新的可以用于保护电子数据的加密算法.明确地说,AES 是一个迭代的.对称密钥分组的密码,它可以使用128.192 和 256 位密钥,并且用 128 位(16字节)分组加密和解密数据.与公共密钥密码使用密钥对不同,对称密钥密码使用相同的密钥加密和解密数据.通过分组密码返回的加密数据

  • 基于C#对用户密码使用MD5加密与解密

    C#中常涉及到对用户密码的加密于解密的算法,其中使用MD5加密是最常见的的实现方式.本文总结了通用的算法并结合了自己的一点小经验,分享给大家. 一.使用16位.32位.64位MD5方法对用户名加密 1)16位的MD5加密 /// <summary> /// 16位MD5加密 /// </summary> /// <param name="password"></param> /// <returns></returns&

  • c# rsa注册实现加密文字

    复制代码 代码如下: RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); private void btencoding_Click(object sender, EventArgs e){    if (mbox.Text == "")    {        MessageBox.Show("加密文字信息不能为空!");        return;    }    if (publick

  • C#编写的Base64加密和解密类

    这个C#类是一个基于Base64的加密和解密类,用户可以可以使用默认的秘钥进行加密.解密,也可以自己设定秘钥进行加密和解密,非常实用 代码一:非常精简的代码 /// <summary> /// Base64加密,解密方法 /// </summary> /// <paramname="s">输入字符串</param> /// <paramname="c">true-加密,false-解密</param&

  • C#文件加密方法汇总

    本文实例汇总了C#文件加密方法.分享给大家供大家参考.具体实现方法如下: 1.AES加密类 复制代码 代码如下: using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace Utils {     /// <summary>     /// AES加密解密     /// </summary>     public class AES     {   

  • C#的3DES加密解密算法实例代码

    C#类如下: 复制代码 代码如下: using System;using System.Collections.Generic;using System.Text;using System.Security.Cryptography;using System.IO; namespace ConsoleApplication1{    /// <summary>    /// 加解密类    /// </summary>    public class EncryptHelper  

  • c# 实现MD5,SHA1,SHA256,SHA512等常用加密算法源代码

    复制代码 代码如下: using System; using System.IO; using System.Data; using System.Text; using System.Diagnostics; using System.Security; using System.Security.Cryptography; /**//* * .Net框架由于拥有CLR提供的丰富库支持,只需很少的代码即可实现先前使用C等旧式语言很难实现的加密算法.本类实现一些常用机密算法,供参考.其中MD5算

  • 基于私钥加密公钥解密的RSA算法C#实现方法

    本文实例讲述了基于私钥加密公钥解密的RSA算法C#实现方法,是一种应用十分广泛的算法.分享给大家供大家参考之用.具体方法如下: 一.概述 RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作. RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一.RSA的安全性依赖于大数的因子分解,但并没有从理论上证明破译RSA的难度与大数分解难度等价. RSA的安全性依赖于大数分解.公钥和私钥都是两个大素数( 大于 1

  • C#自定义RSA加密解密及RSA签名和验证类实例

    本文实例讲述了C#自定义RSA加密解密及RSA签名和验证类.分享给大家供大家参考.具体分析如下: 这个C#类自定义RSA加密解密及RSA签名和验证,包含了RSA加密.解密及签名所需的相关函数,带有详细的注释说明. using System; using System.Text; using System.Security.Cryptography; namespace DotNet.Utilities { /// <summary> /// RSA加密解密及RSA签名和验证 /// </

  • C#实现的AES加密解密完整实例

    本文实例讲述了C#实现的AES加密解密.分享给大家供大家参考,具体如下: /****************************************************************** * 创建人:HTL * 说明:C# AES加密解密 *******************************************************************/ using System; using System.Security.Cryptography;

  • C#加密解密文件小工具实现代码

    DebugLZQ在网上搜索相关文件加密的程序,发现给出的基本都是针对"字符创"."文本"的加密与解密.对视频文件.图片等一般文件的加密解密程序少之又少,故写下此文,实现一个对一般文件进行加密的小工具. 程序的主要功能是:用户通过文件选择框选择要加密的文件->输入密码进行加密:选择加密后的文件,输入密码进行解密. 程序的主界面如下: 三个按钮的Click事件处理程序如下: 复制代码 代码如下: private void btnSelectFile_Click(o

随机推荐