C#加密解密大全

简介:

1、方法一 (不可逆加密)

 

复制代码
复制代码

    public string EncryptPassword(string PasswordString,string PasswordFormat ) 
    { 
       string  encryptPassword = null;
       if (PasswordFormat="SHA1")
       { 
          encryptPassword=FormsAuthortication.HashPasswordForStoringInConfigFile(PasswordString ,"SHA1"); 
       } 
       elseif (PasswordFormat="MD5") 
       { 
          encryptPassword=FormsAuthortication.HashPasswordForStoringInConfigFile(PasswordString ,"MD5"); 
       }
         return encryptPassword ;
    }
复制代码
复制代码

2、方法二 (可逆加密)

 

复制代码
复制代码

 public interface IBindesh
    {
    string encode(string str);
    string decode(string str);
     }

    public class EncryptionDecryption : IBindesh
    {
        public string encode(string str)
         {
            string htext = ""; 

            for ( int i = 0; i < str.Length; i++)
            {
                htext = htext + (char) (str[i] + 10 - 1 * 2);
            }
            return htext;
     }

        public string decode(string str)
        {
            string dtext = ""; 

            for ( int i=0; i < str.Length; i++)
            {
                dtext = dtext + (char) (str[i] - 10 + 1*2);
            }
            return dtext;
        }
复制代码
复制代码

3、方法三 (可逆加密)

 

复制代码
复制代码

 const string KEY_64 = "VavicApp";//注意了,是8个字符,64位

        const string IV_64 = "VavicApp"; 
        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);
            return sr.ReadToEnd();
        }
复制代码
复制代码

 

4、MD5不可逆加密    (32位加密)

 

复制代码
复制代码

     public string GetMD5(string s, string _input_charset)
     {

        /**//// <summary>
        /// 与ASP兼容的MD5加密算法
        /// </summary>

        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 GetMd5Str(string ConvertString)
    {
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
        t2 = t2.Replace("-", "");
        return t2;
    } 
复制代码
复制代码

 

5、加解文本文件

 

复制代码
复制代码


         //加密文件
    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();
    }
复制代码
复制代码

6.

复制代码
复制代码

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

namespace Component
 {
    public class Security
     {
        public Security()
        
        
        }

        //默认密钥向量
        private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        /**//**//**//// <summary>
        /// DES加密字符串
        /// </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解密字符串
        /// </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;
            }
        } 


    }
}
复制代码
复制代码

本文转自左正博客园博客,原文链接:http://www.cnblogs.com/soundcode/p/6165389.html ,如需转载请自行联系原作者
相关文章
|
5天前
|
存储 安全 网络安全
C#编程的安全性与加密技术
【4月更文挑战第21天】C#在.NET框架支持下,以其面向对象和高级特性成为安全软件开发的利器。本文探讨C#在安全加密领域的应用,包括使用System.Security.Cryptography库实现加密算法,利用SSL/TLS保障网络传输安全,进行身份验证,并强调编写安全代码的重要性。实际案例涵盖在线支付、企业应用和文件加密,展示了C#在应对安全挑战的同时,不断拓展其在该领域的潜力和未来前景。
|
5月前
|
开发框架 网络协议 前端开发
一个对C#程序混淆加密,小巧但够用的小工具
一个对C#程序混淆加密,小巧但够用的小工具
86 1
|
4月前
|
算法 C# 数据安全/隐私保护
C# | 上位机开发新手指南(十)加密算法——ECC
本篇文章我们将继续探讨另一种非对称加密算法——ECC。 严格的说,其实ECC并不是一种非对称加密算法,它是一种基于椭圆曲线的加密算法,广泛用于数字签名和密钥协商。 与传统的非对称加密算法(例如RSA)不同,ECC算法使用椭圆曲线上的点乘法来生成密钥对和进行加密操作,而不是使用大数分解等数学算法。这使得ECC算法具有相同的安全性和强度,但使用更少的位数,因此在资源受限的环境中具有优势。 ECC算法虽然使用公钥和私钥进行加密和解密操作,但是这些操作是基于点乘法实现的,而不是基于大数分解等算法实现的。因此,ECC算法可以被视为一种非对称加密算法的变体,但是它与传统的非对称加密算法有所不同。
135 0
C# | 上位机开发新手指南(十)加密算法——ECC
|
4月前
|
XML 算法 安全
C# | 上位机开发新手指南(九)加密算法——RSA
RSA的特性 非对称性 RSA算法使用公钥和私钥两个不同的密钥,公钥用于加密数据,私钥用于解密数据。公钥可以公开,任何人都可以使用,而私钥只有密钥持有人可以访问。 安全性 RSA算法基于大数分解难题,即将一个大的合数分解成其质数因子的乘积。由于目前没有有效的算法可以在合理的时间内对大质数进行分解,因此RSA算法被认为是一种安全的加密算法。 可逆性 RSA算法既可以用于加密,也可以用于解密。加密和解密都是可逆的过程,只要使用正确的密钥,就可以还原原始数据。 签名 RSA算法可以用于数字签名,用于验证数据的完整性和真实性。签名过程是将数据使用私钥进行加密,验证过程是将签名使用公钥进行解密。
102 0
C# | 上位机开发新手指南(九)加密算法——RSA
|
4月前
|
算法 搜索推荐 安全
C# | 上位机开发新手指南(八)加密算法——AES
AES——这是在加密算法中相当重要的一种加密方式! 虽然这个世界上已经存在了非对称加密算法(比如RSA、ECC等),但是在对称加密算法中,AES的地位依然相当重要。与非对称加密算法不同,对称加密算法使用的是相同的密钥对数据进行加密和解密,因此其加密和解密速度更快,而且更加高效。而在对称加密算法中,AES是目前最安全、最可靠的加密算法之一,其加密强度和运行效率都非常高。因此,无论是在个人计算机、移动设备,还是在服务器和云计算等领域,AES都被广泛应用于数据的加密和解密过程中。
95 0
C# | 上位机开发新手指南(八)加密算法——AES
|
4月前
|
存储 算法 安全
C# | 上位机开发新手指南(七)加密算法
加密算法是信息安全领域中的重要技术之一,可以保护数据在传输、存储和处理过程中的安全性。 学习加密算法可以帮助我们更好地理解和应用其他相关技术。例如,数字证书、数字签名、安全协议等都与加密算法密切相关,掌握加密算法可以为我们理解和应用这些技术提供帮助。
54 0
C# | 上位机开发新手指南(七)加密算法
|
4月前
|
XML 存储 JSON
C# 对象存储 (轻松实现序列化 | Xml | Json | 加密 | 压缩 | 注册表 | Redis)
开发时经常会遇到需要保存配置的情况,最常见的实现方式是将对象序列化成Json,再写入文件并保存到本地磁盘。 本文将使用开源库**ApeFree.DataStore**来替换原有的对象存储过程,实现一个可以随意切换存储方式的对象存储方法。 ApeFree.DataStore是一款可配置的对象存储库,支持在不同平台/介质中对内存中的对象进行存储与还原(如本地存储、注册表存储)。支持配置序列化格式(如Json、Xml),支持配置压缩算法(如GZip、Defalte),支持配置加密算法(如AES、RSA)。
68 0
C# 对象存储 (轻松实现序列化 | Xml | Json | 加密 | 压缩 | 注册表 | Redis)
|
8月前
|
存储 API 数据库
c# 如何将程序加密隐藏?
c# 如何将程序加密隐藏?
85 0
c# 如何将程序加密隐藏?
|
9月前
|
安全 Linux 网络安全
C#生成putty格式的ppk文件(支持加密)
C#生成putty格式的ppk文件(支持加密)
95 0
|
C# 数据安全/隐私保护
C#使用SHA1加密类(RSAFromPkcs8)支持1024位和2048位私钥
C#使用SHA1加密类(RSAFromPkcs8)支持1024位和2048位私钥
230 0