C#常用加密解密方法(MD5加密解密)

在日常开发过程中,总会遇到需要加密解密的需求,这里我整理了C#常用的加密解密方法分享给大家。

先看看加密的基本概念:

"加密",是一种限制对网络上传输数据的访问权的技术。原始数据(也称为明文,plaintext)被加密设备(硬件或软件)和密钥加密而产生的经过编码的数据称为密文(ciphertext)。将密文还原为原始明文的过程称为解密,它是加密的反向处理,但解密者必须利用相同类型的加密设备和密钥对密文进行解密。

加密的基本功能包括:

1. 防止不速之客查看机密的数据文件;

2. 防止机密数据被泄露或篡改;

3. 防止特权用户(如系统管理员)查看私人数据文件;

4. 使入侵者不能轻易地查找一个系统的文件。

一、本节摘要

本节主要分享MD5加密解密: 

MD5全称是message-digest algorithm 5,简单的说就是单向的加密,也就是说无法根据密文推导出明文。

MD5主要用途:
1、对一段信息生成信息摘要,该摘要对该信息具有唯一性,可以作为数字签名
2、用于验证文件的有效性(是否有丢失或损坏的数据)
3、对用户密码的加密
4、在哈希函数中计算散列值

二、源码分享 

1、主方法

private void Test()
{
    string o = "i love u";
    o = AddMD5Profix(o);
    //o += " ";
    Console.WriteLine(o);
    Console.WriteLine(ValidateValue(o));

    o = RemoveMD5Profix(o);
    Console.WriteLine(o);

}

2、MD5加密解密类

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

namespace Commons
{
    /// <summary>
    /// MD5各种长度加密字符、验证MD5等操作辅助类
    /// </summary>
    public class MD5Util
    {
        public MD5Util()
        {
        }

        /// <summary>
        /// 获得32位的MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string GetMD5_32(string input)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(input));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i].ToString("x2"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 获得16位的MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string GetMD5_16(string input)
        {
            return GetMD5_32(input).Substring(8, 16);
        }

        /// <summary>
        /// 获得8位的MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string GetMD5_8(string input)
        {
            return GetMD5_32(input).Substring(8, 8);
        }

        /// <summary>
        /// 获得4位的MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string GetMD5_4(string input)
        {
            return GetMD5_32(input).Substring(8, 4);
        }

        /// <summary>
        /// 添加MD5的前缀,便于检查有无篡改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string AddMD5Profix(string input)
        {
            return GetMD5_4(input) + input;
        }

        /// <summary>
        /// 移除MD5的前缀
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string RemoveMD5Profix(string input)
        {
            return input.Substring(4);
        }

        /// <summary>
        /// 验证MD5前缀处理的字符串有无被篡改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool ValidateValue(string input)
        {
            bool res = false;
            if (input.Length >= 4)
            {
                string tmp = input.Substring(4);
                if (input.Substring(0, 4) == GetMD5_4(tmp))
                {
                    res = true;
                }
            }
            return res;
        }

        #region MD5签名验证
        /// <summary>
        /// 对给定文件路径的文件加上标签
        /// </summary>
        /// <param name="path">要加密的文件的路径</param>
        /// <returns>标签的值</returns>
        public static bool AddMD5(string path)
        {
            bool IsNeed = true;

            if (CheckMD5(path))                                  //已进行MD5处理
                IsNeed = false;

            try
            {
                FileStream fsread = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                byte[] md5File = new byte[fsread.Length];
                fsread.Read(md5File, 0, (int)fsread.Length);                               // 将文件流读取到Buffer中
                fsread.Close();

                if (IsNeed)
                {
                    string result = MD5Buffer(md5File, 0, md5File.Length);             // 对Buffer中的字节内容算MD5
                    byte[] md5 = System.Text.Encoding.ASCII.GetBytes(result);       // 将字符串转换成字节数组以便写人到文件中
                    FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
                    fsWrite.Write(md5File, 0, md5File.Length);                               // 将文件,MD5值 重新写入到文件中。
                    fsWrite.Write(md5, 0, md5.Length);
                    fsWrite.Close();
                }
                else
                {
                    FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
                    fsWrite.Write(md5File, 0, md5File.Length);
                    fsWrite.Close();
                }
            }
            catch
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 对给定路径的文件进行验证
        /// </summary>
        /// <param name="path"></param>
        /// <returns>是否加了标签或是否标签值与内容值一致</returns>
        public static bool CheckMD5(string path)
        {
            try
            {
                FileStream get_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                byte[] md5File = new byte[get_file.Length];                                      // 读入文件
                get_file.Read(md5File, 0, (int)get_file.Length);
                get_file.Close();

                string result = MD5Buffer(md5File, 0, md5File.Length - 32);             // 对文件除最后32位以外的字节计算MD5,这个32是因为标签位为32位。
                string md5 = System.Text.Encoding.ASCII.GetString(md5File, md5File.Length - 32, 32);   //读取文件最后32位,其中保存的就是MD5值
                return result == md5;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 计算文件的MD5值
        /// </summary>
        /// <param name="MD5File">MD5签名文件字符数组</param>
        /// <param name="index">计算起始位置</param>
        /// <param name="count">计算终止位置</param>
        /// <returns>计算结果</returns>
        private static string MD5Buffer(byte[] MD5File, int index, int count)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] hash_byte = get_md5.ComputeHash(MD5File, index, count);
            string result = System.BitConverter.ToString(hash_byte);

            result = result.Replace("-", "");
            return result;
        } 
        #endregion

        private void Test()
        {
            string o = "i love u";
            o = AddMD5Profix(o);
            //o += " ";
            Console.WriteLine(o);
            Console.WriteLine(ValidateValue(o));

            o = RemoveMD5Profix(o);
            Console.WriteLine(o);

        }
    }
}

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
C#中的盐加密解密可以使用以下步骤: 1. 生成一个随机的盐值 2. 将盐值与要加密的数据进行拼接 3. 使用某种加密算法(如AES)对拼接后的字符串进行加密 4. 将盐值和加密后的数据一起存储 解密时,需要先取出盐值,然后使用相同的加密算法对剩余部分进行解密。以下是一个示例代码: ```csharp using System; using System.Security.Cryptography; using System.Text; class Program { static void Main(string[] args) { string password = "password123"; string salt = GenerateSalt(); string encryptedPassword = EncryptPassword(password, salt); Console.WriteLine("Original password: " + password); Console.WriteLine("Salt: " + salt); Console.WriteLine("Encrypted password: " + encryptedPassword); string decryptedPassword = DecryptPassword(encryptedPassword, salt); Console.WriteLine("Decrypted password: " + decryptedPassword); } static string GenerateSalt() { byte[] saltBytes = new byte[16]; using (var rng = new RNGCryptoServiceProvider()) { rng.GetBytes(saltBytes); } return Convert.ToBase64String(saltBytes); } static string EncryptPassword(string password, string salt) { byte[] saltBytes = Convert.FromBase64String(salt); byte[] passwordBytes = Encoding.UTF8.GetBytes(password); byte[] combinedBytes = new byte[saltBytes.Length + passwordBytes.Length]; Buffer.BlockCopy(saltBytes, 0, combinedBytes, 0, saltBytes.Length); Buffer.BlockCopy(passwordBytes, 0, combinedBytes, saltBytes.Length, passwordBytes.Length); byte[] encryptedBytes; using (var aes = Aes.Create()) { aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.GenerateIV(); aes.Key = Encoding.UTF8.GetBytes("mysecretpassword12345"); using (var encryptor = aes.CreateEncryptor()) { encryptedBytes = encryptor.TransformFinalBlock(combinedBytes, 0, combinedBytes.Length); } } return Convert.ToBase64String(encryptedBytes); } static string DecryptPassword(string encryptedPassword, string salt) { byte[] saltBytes = Convert.FromBase64String(salt); byte[] encryptedBytes = Convert.FromBase64String(encryptedPassword); byte[] decryptedBytes; using (var aes = Aes.Create()) { aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = Encoding.UTF8.GetBytes("mysecretpassword12345"); aes.IV = encryptedBytes.Take(16).ToArray(); using (var decryptor = aes.CreateDecryptor()) { decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 16, encryptedBytes.Length - 16); } } byte[] passwordBytes = new byte[decryptedBytes.Length - saltBytes.Length]; Buffer.BlockCopy(decryptedBytes, saltBytes.Length, passwordBytes, 0, passwordBytes.Length); return Encoding.UTF8.GetString(passwordBytes); } } ``` 注意,上述代码中的密码和加密密钥应该使用更加安全的方式进行管理,例如将其存储在安全的密钥库中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MarcoPro

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值