Unity 工具类 之 简单的数据加密解密类 DataEncryptionAndDecryptionManager 实现

Unity 工具类 之 简单的数据加密解密类 DataEncryptionAndDecryptionManager 实现

 

目录

Unity 工具类 之 简单的数据加密解密类 DataEncryptionAndDecryptionManager 实现

一、简单介绍

 二、实现原理

三、注意事项

四、效果预览

五、实现步骤

六、关键代码

七、参考工程


 

一、简单介绍

Unity 工具类,自己整理的一些游戏开发可能用到的模块,单独独立使用,方便游戏开发。

简单的数据加密解密类,单独做了一个单例类,提供数据加密解密的接口,供外界调用即可。

MD5的全称是message-digest algorithm 5(信息-摘要算法,在90年代初由mit laboratory for computer science和rsa data security inc的ronald l. rivest开发出来, 经md2、md3和md4发展而来。

MD5具有很好的安全性(因为它具有不可逆的特征,加过密的密文经过解密后和加密前的东东相同的可能性极小)
 

 
二、实现原理

1、单例类,保证整个场景中只有一个类管理数据加密解密;

2、使用 RijndaelManaged 进行相关加密解密;

3、使用 DataEncryptionAndDecryptionManager.Instance.ConductEncryption 即可加密数据;

4、使用 DataEncryptionAndDecryptionManager.Instance.ConductDecryption 即可解密数据;

 

三、注意事项

1、加密解密的key为32位数值,根据自己需要设定;

 

四、效果预览

 

五、实现步骤

1、打开Unity,新建空工程,在场景中添加 UI,用于输入加密内容,显示加密内容和解密后的结果,如下图

 

2、在工程中添加脚本,单例类保证类唯一,数据加密解密管理类为加密解密逻辑,测试脚本按下 E 键加密,按下 D 键解密,如下图

 

3、把测试脚本挂载到场景中,并对应赋值,如下图

 

4、运行场景,效果如下

 

六、关键代码

1、TestScript

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TestScript : MonoBehaviour
{

    public InputField Content_InputField;
    public Text Encryption_Text;
    public Text Decryption_Text;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E)) {

            Encryption_Text.text = 
            DataEncryptionAndDecryptionManager.Instance.ConductEncryption(Content_InputField.text,
                DataEncryptionAndDecryptionManager.Instance.KeyValue
                );
        }

        if (Input.GetKeyDown(KeyCode.D))
        {
            Decryption_Text.text =
            DataEncryptionAndDecryptionManager.Instance.ConductDecryption(Encryption_Text.text,
                DataEncryptionAndDecryptionManager.Instance.KeyValue
                );
        }
    }
}

2、DataEncryptionAndDecryptionManager

using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;

public class DataEncryptionAndDecryptionManager : Singleton<DataEncryptionAndDecryptionManager>
{

    /// <summary>
    /// 32位任意数值,作为是加密解码约定数字(可以根据需要修改成自己想要的32位任意数值)
    /// </summary>
    private string _keyValue = "01234567890123456789012345678901";

    public string KeyValue { get => _keyValue; set => _keyValue = value; }

    /// <summary>
    /// 数据加密
    /// </summary>
    /// <param name="content">需要加密内容</param>
    /// <param name="keyValue">加密的32位密码</param>
    /// <returns></returns>
    public string ConductEncryption(string content, string keyValue)
    {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes(keyValue);

        //加密格式
        RijndaelManaged encryption = new RijndaelManaged();
        encryption.Key = keyArray;
        encryption.Mode = CipherMode.ECB;
        encryption.Padding = PaddingMode.PKCS7;

        //生成加密锁
        ICryptoTransform cTransform = encryption.CreateEncryptor();
        byte[] _EncryptArray = UTF8Encoding.UTF8.GetBytes(content);
        byte[] resultArray = cTransform.TransformFinalBlock(_EncryptArray, 0, _EncryptArray.Length);
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }

    /// <summary>
    /// 数据解密
    /// </summary>
    /// <param name="content">需要解密的数据</param>
    /// <param name="keyValue">解密的32位密码</param>
    /// <returns></returns>
    public string ConductDecryption(string content, string keyValue)
    {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes(keyValue);

        // 解密格式
        RijndaelManaged decryption = new RijndaelManaged();
        decryption.Key = keyArray;
        decryption.Mode = CipherMode.ECB;
        decryption.Padding = PaddingMode.PKCS7;

        // 开始解密
        ICryptoTransform cTransform = decryption.CreateDecryptor();
        byte[] _DecryptArray = Convert.FromBase64String(content);
        byte[] resultArray = cTransform.TransformFinalBlock(_DecryptArray, 0, _DecryptArray.Length);
        return UTF8Encoding.UTF8.GetString(resultArray);
    }



}

3、Singleton

public abstract class Singleton<T> where T : class, new()
{
    private static T instance = null;

    // 多线程安全机制
    private static readonly object locker = new object();

    public static T Instance
    {
        get
        {
            lock (locker)
            {
                if (instance == null)
                    instance = new T();
                return instance;
            }
        }
    }
}

 

七、参考工程

点击下载工程

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Unity中的WebSocket加密解密可以通过使用SSL/TLS协议来实现。具体来说,可以使用Unity的`SslStream`来对WebSocket通信进行加密和解密。 在使用`SslStream`之前,需要先创建一个`TcpClient`对象来与WebSocket服务器建立连接。然后,可以使用`SslStream`的构造函数来创建一个加密的流对象。最后,可以使用`SslStream`的`Read()`和`Write()`方法来对WebSocket通信进行加密和解密。 以下是一个示例代码: ```csharp using System; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using UnityEngine; public class WebSocketClient : MonoBehaviour { private TcpClient tcpClient; private SslStream sslStream; private byte[] receiveBuffer = new byte[1024]; private async Task Connect(string serverIp, int serverPort) { tcpClient = new TcpClient(); await tcpClient.ConnectAsync(serverIp, serverPort); // Create SslStream object with client certificate validation sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); // Authenticate server and client with SSL/TLS connection try { await sslStream.AuthenticateAsClientAsync(serverIp); } catch (AuthenticationException e) { Debug.LogError($"SSL/TLS authentication failed: {e.Message}"); tcpClient.Close(); return; } // Start listening for incoming WebSocket messages await Receive(); } private async Task Receive() { // Read incoming data from WebSocket server int bytesReceived = await sslStream.ReadAsync(receiveBuffer, 0, receiveBuffer.Length); // Decrypt received data // Process decrypted data // Continue listening for incoming WebSocket messages await Receive(); } private void Send(string message) { // Encrypt outgoing data // Send encrypted data to WebSocket server byte[] sendBuffer = System.Text.Encoding.UTF8.GetBytes(message); sslStream.Write(sendBuffer, 0, sendBuffer.Length); } private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // Perform certificate validation if needed return true; } } ``` 请注意,以上代码仅提供了WebSocket加密解密的基本思路,具体实现可能因应用场景而有所不同。还需要根据实际情况进行一些改进,比如对接收到的数据进行解析和处理,对发送的数据进行封装和编码等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

仙魁XAN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值