C#实现简单的异或加密,方便处理

将本地的mp4和ts文件加密为“dj”文件,无法播放。解密则是将“dj”文件解密为mp4或ts文件。

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

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("请输入操作方式(1加密、0解密):");
            var key = Console.ReadLine();
            if (key == "1")
            {
                Encrypt();
            }
            else
            {
                Dencrypt();
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 加密处理
        /// </summary>
        static void Encrypt()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            string[] extends = new string[] { "*.ts", "*.mp4" };
            foreach (var ex in extends)
            {
                foreach (var file in Directory.GetFiles(path, ex))
                {
                    Encrypt(file, file + ".dj");
                    Console.WriteLine($"[{file}]加密成功");
                    File.Delete(file);
                }
            }
            Console.WriteLine("所有文件加密成功");
        }

        static void Dencrypt()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            foreach (var file in Directory.GetFiles(path, "*.dj"))
            {
                Encrypt(file, file.Replace(".dj", ""));
                Console.WriteLine($"[{file}]解密成功");
                File.Delete(file);
            }
            Console.WriteLine("所有文件解密成功");
        }

        static void Encrypt(string sourceFileName, string targetFileName)
        {
            using (var writeStream = File.OpenWrite(targetFileName))
            {
                //int start = 0;
                int len = 0;
                byte[] readBytes = new byte[1024];
                using (var readStream = File.OpenRead(sourceFileName))
                {
                    var totalLenth = readStream.Length;
                    while ((len = readStream.Read(readBytes, 0, readBytes.Length)) > 0)
                    {
                        writeStream.Write(Encry(readBytes), 0, len);
                        Console.WriteLine($"[{sourceFileName}]读取中[{readStream.Position}/{totalLenth}]");
                    }
                }
            }
        }

        static byte[] Encry(byte[] bs)
        {
            for (int i = 0; i < bs.Length; i++)
            {
                bs[i] = (byte)(bs[i] ^ 0x12);
            }
            return bs;
        }
    }
}

 

posted @ 2022-12-18 20:36  段江涛IT  阅读(248)  评论(0编辑  收藏  举报
页脚HTML代码