美文网首页
C#对一段文本内容加密和解密

C#对一段文本内容加密和解密

作者: 全新的饭 | 来源:发表于2024-04-16 17:02 被阅读0次

    说明

    1. 通过调用Encode方法,可将str加密成content,返回一个int值作为本次加密内容的标记。
    2. 通过调用TryDecode,传入加密内容content,若可解密(content格式满足要求),则解出str,并得到content的int标记。

    代码

    FanStrCoder.cs
    提供2个方法:Encode、TryDecode

    using System.Text;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using Unity.VisualScripting;
    using System.Security.Cryptography;
    using System.IO;
    using System.Diagnostics;
    
    /// <summary>
    /// 对string进行加密和解密
    /// </summary>
    public static class FanStrCoder
    {
        private const string SignSeparator = "_";
        private const byte SimpleKey = 0xFF;
        private static int CreateSign()
        {
            var str = DateTime.Now.Ticks.ToString();
            var length = str.Length;
            var subStr = str.Substring(length - 5, 5);
            var ret = int.Parse(subStr);
            return ret;
        }
        public static int Encode(string str, out string content)
        {
            var sign = CreateSign();
            var strWithSign = sign.ToString() + SignSeparator + str;
            content = EncryptDES(strWithSign, string.Empty);
            return sign;
        }
        public static bool TryDecode(string str, out int sign, out string content)
        {
            sign = 0;
            content = string.Empty;
            var strWithSign = DecryptDES(str, string.Empty);
            var strWithSigns = strWithSign.Split(SignSeparator);
            var signStr = strWithSigns[0];
            var ret = int.TryParse(signStr, out sign);
            if (ret)
            {
                content = strWithSign.Substring(signStr.Length + 1);
            }
            return ret;
        }
    
        private static Encoding Encoding => Encoding.UTF8;
    
        private static string EncryptDES(string encryptString, string key)
        {
            var input = Encoding.GetBytes(encryptString);
            var ouptputData = ProcessDES(input, key, true);
            var outputStr = Convert.ToBase64String(ouptputData);
    
            //base64编码中有不能作为文件名的'/'符号,这里把它替换一下,增强适用范围
            return outputStr.Replace('/', '@');
        }
    
        private static string DecryptDES(string decryptString, string key)
        {
            decryptString = decryptString.Replace('@', '/');
            try
            {
                var input = Convert.FromBase64String(decryptString);
                var data = ProcessDES(input, key, false);
                return Encoding.GetString(data);
            }
            catch (FormatException)
            {
                UnityEngine.Debug.LogError(nameof(DecryptDES) + ":字符串格式错误!");
                return string.Empty;
            }
        }
    
    
        private static byte[] ProcessDES(byte[] data, string key, bool isEncrypt)
        {
            using var dCSP = new DESCryptoServiceProvider();
            var keyData = Md5(key);
            var rgbKey = new ArraySegment<byte>(keyData, 0, 8).ToArray();
            var rgbIV = new ArraySegment<byte>(keyData, 8, 8).ToArray();
            var dCSPKey = isEncrypt ? dCSP.CreateEncryptor(rgbKey, rgbIV) : dCSP.CreateDecryptor(rgbKey, rgbIV);
    
            using var memory = new MemoryStream();
            using var cStream = new CryptoStream(memory, dCSPKey, CryptoStreamMode.Write);
            cStream.Write(data, 0, data.Length);
            cStream.FlushFinalBlock();
            return memory.ToArray();
        }
    
        public static byte[] Md5(string str)
        {
            using var md5 = MD5.Create();
            return md5.ComputeHash(Encoding.UTF8.GetBytes(str));
        }
    }
    

    FanTest.cs
    说明用法

    using UnityEngine;
    
    public class FanTest : MonoBehaviour
    {
        [SerializeField, TextArea]
        private string _needEncodeStr;
        [SerializeField, TextArea]
        private string _needDecodeStr;
    
        private void Start()
        {
    
        }
    
        private void OnDestroy()
        {
    
        }
    
        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.A))
            {
                var needEncodeStr = _needEncodeStr;
                var sign = FanStrCoder.Encode(needEncodeStr, out string str);
                Debug.Log("加密:" + sign + "\n" + str);
            }
            else if (Input.GetKeyUp(KeyCode.B))
            {
                var needDecodeStr = _needDecodeStr;
                if (FanStrCoder.TryDecode(needDecodeStr, out int sign, out string str))
                {
                    Debug.Log("解密成功:" + sign + "\n" + str);
                }
                else
                {
                    Debug.Log("解密失败");
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:C#对一段文本内容加密和解密

          本文链接:https://www.haomeiwen.com/subject/tsnjxjtx.html