加密原理:将文本文件每行读取,取其中的字母,偏移若干位数,区分大小写。
因为只混淆了字母,所以保持了标点、数字和格式。
操作步骤:
- 将脚本挂在空物体上
- 将文本保存在txt文件中,并拖入textAsset
- 执行加密文件
- 加密后的文本显示在text中
using System.Text;
using UnityEngine;
public class EncryptionTool : MonoBehaviour
{
public string text;//加密或解密后直接从Inspector中复制就行
public TextAsset textAsset;
public int key=1;//自定义key值
char a = 'a';
char z = 'z';
char A = 'A';
char Z = 'Z';
//获取偏移后的字符
char GetChar(char _c, int _offest)
{
_offest %= 26;
if (_offest == 0)
{
return _c;
}
if (_c >= A && _c <= Z)
{
_c = (char)(_offest + _c);
if (_c > Z)
{
_c = (char)(_c - Z + A - 1);
}
else if (_c < A)
{
_c = (char)(Z - (A - _c) + 1);
}
}
else if (_c >= a && _c <= z)
{
_c = (char)(_offest + _c);
if (_c > z)
{
_c = (char)(_c - z + a - 1);
}
else if (_c < a)
{
_c = (char)(z - (a - _c) + 1);
}
}
return _c;
}
//是字母
bool IsLetter(char v)
{
return (v <= 'z' && v >= 'a')|| (v <= 'Z' && v >= 'A');
}
[ContextMenu("加密文件")]
public void EncryptionFile()
{
text = textAsset.text;//通过文件读的话就可以避免没有换行
var _temp = new StringBuilder();
for (var i = 0; i < text.Length; i++)
{
if (IsLetter(text[i]))
{
_temp.Append(GetChar(text[i], Fun(i)));
}
else
{
_temp.Append(text[i]);
}
}
text = _temp.ToString();
}
[ContextMenu("破译文件")]
public void DecipheringFile()
{
var _temp = new StringBuilder();
for (var i = 0; i < text.Length; i++)
{
if (IsLetter(text[i]))
{
_temp.Append(GetChar(text[i], -Fun(i)));
}
else
{
_temp.Append(text[i]);
}
}
text = _temp.ToString();
}
int Fun(int v)
{
return v+(key+1)*10;//自定义的加密算法
}
[ContextMenu("加密一段")]
public void EncryptionLine()
{
var _temp = new StringBuilder();
for (var i = 0; i < text.Length; i++)
{
if (IsLetter(text[i]))
{
_temp.Append(GetChar(text[i], Fun(i)));
}
else
{
_temp.Append(text[i]);
}
}
text = _temp.ToString();
}
[ContextMenu("破译一段")]
public void DecipheringFLine()
{
var _temp = new StringBuilder();
for (var i = 0; i < text.Length; i++)
{
if (IsLetter(text[i]))
{
_temp.Append(GetChar(text[i], -Fun(i)));
}
else
{
_temp.Append(text[i]);
}
}
text = _temp.ToString();
}
}
返回目录:https://blog.csdn.net/yzy1987523/article/details/107739933