自己创造一个格式,自定义文件后缀名
YES-CMS内容管理系统开发记录
插件导出想自创一个自定义格式,*.yesp,实际放入的是json字符串,但是希望不能用记事本打开(增加神秘感[手动滑稽])
自定义一个文件扩展名,打造一个输入自己的扩展名文件,自定义一个文件后缀名,并且对文件进行加密保存
指定后缀名
这个好办,后缀名指定一下就行,
文件流加密
废话不多说,直接上代码,
对象转json字符串,
然后对字符串进行加密,返回byte[]
byte[]直接写入文件
C# 全选
string fileName ="C:\\" + plugin.pluginName + ".yesp";
// 文件中内容
string content = Newtonsoft.Json.JsonConvert.SerializeObject(plugin);
// 加密
byte[] buffer= Encrypt(content);
FileStream fs = new FileStream(fileName, FileMode.Create);
fs.Write(buffer, 0, buffer.Length);
fs.Dispose();
加密和解密方法如下:
C# 全选
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace YESCMS.Libs
{
public class FileEntryHelper
{
/// <summary>
/// Des默认密钥向量
/// </summary>
static byte[] DesIv = { 0x10, 0x40, 0x66, 0x80, 0x70, 0xCB, 0xAD, 0xEF };
/// <summary>
/// Des加解密钥必须8位
/// </summary>
const string DesKey = "iyes2123";
public static byte[] Encrypt(string source)
{
using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
{
byte[] rgbKeys = Encoding.UTF8.GetBytes(DesKey);
byte[] rgbIvs = DesIv;
byte[] inputByteArray = Encoding.UTF8.GetBytes(source);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, desProvider.CreateEncryptor(rgbKeys, rgbIvs), CryptoStreamMode.Write))
{
cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
cryptoStream.FlushFinalBlock();
// 1.第一种
return memoryStream.ToArray();
}
}
}
}
public static string DecryptDes(Stream stream)
{
using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
{
byte[] rgbKeys = Encoding.UTF8.GetBytes(DesKey);
byte[] rgbIvs = DesIv;
stream.Seek(0, SeekOrigin.Begin);
byte[] inputByteArray = new byte[stream.Length];
stream.Read(inputByteArray, 0, inputByteArray.Length);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, desProvider.CreateDecryptor(rgbKeys, rgbIvs), CryptoStreamMode.Write))
{
cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
cryptoStream.FlushFinalBlock();
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
}
}
public static string DecryptDes(byte[] inputByteArray)
{
using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
{
byte[] rgbKeys = Encoding.UTF8.GetBytes(DesKey);
byte[] rgbIvs = DesIv;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, desProvider.CreateDecryptor(rgbKeys, rgbIvs), CryptoStreamMode.Write))
{
cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
cryptoStream.FlushFinalBlock();
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
}
}
}
}
测试
得到的文件
用记事本打开如下
搞定
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 管理员