最近,心血来潮想复习一下文本的读写,以及字符串的加解密。虽然网上已经有了很多文档,但还是想自己做下笔记。
本次笔记文档不包含复杂的操作,只是简单的读写和加解密。
首先,先明确一点,文本的读写方式有很多,但涉及到加解密操作,最好使用二进制读写方式。
文本加解密
加解密功能参考代码来源:C#实现最简单的文本加密方法
稍加修改后就变成了:
public static char[] TextEncryptBinary(string content, string secretKey)
{
char[] data = content.ToCharArray();
char[] key = secretKey.ToCharArray();
for (int i = 0; i < data.Length; i++)
{
data[i] ^= key[i % key.Length];
}
return data;
}
public static string TextDecryptBinary(string content, string secretKey)
{
char[] data = content.ToCharArray();
char[] key = secretKey.ToCharArray();
for (int i = 0; i < data.Length; i++)
{
data[i] ^= key[i % key.Length];
}
return new string(data);
}
public static string TextDecryptBinary(char[] data, string secretKey)
{
char[] key = secretKey.ToCharArray();
for (int i = 0; i < data.Length; i++)
{
data[i] ^= key[i % key.Length];
}
return new string(data);
}
public static string TextDecryptBinary(byte[] content, string secretKey)
{
char[] data = UTF8Encoding.UTF8.GetChars(content);
char[] key = secretKey.ToCharArray();
for (int i = 0; i < data.Length; i++)
{
data[i] ^= key[i % key.Length];
}
return new string(data);
}
关键点就在 类型转换 和 异或运算符使用
byte[] 转 char[]
string 转 char[]
char[] 转 string
Encrypt:将文本string 转字节集char[] 加密数据
Decrypt:将加密数据 string 或 char[] 或 byte[] 转文本 string 加密数据
文本读写操作
文本读写网上已有很多,在这里用的是二进制读写方式,代码片段:
//文本读取
public static string TextBinaryReader(string path)
{
byte[] bBuffer;
using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open))
{
BinaryReader binReader = new BinaryReader(fs);
bBuffer = new byte[fs.Length];
binReader.Read(bBuffer, 0, (int)fs.Length);
binReader.Close();
fs.Close();
}
return UTF8Encoding.UTF8.GetString(bBuffer);
}
//文本保存
public static void TextBinaryWrite(string path, byte[] bytes)
{
using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
{
BinaryWriter binWriter = new BinaryWriter(fs);
binWriter.Write(bytes, 0, bytes.Length);
binWriter.Close();
}
}
这样文本就实现了简单加解密,并进行了读写操作。
缺点:加密后的文件会变得很大,待验证解决