Unity数据的加密与解密

好久没有更新博客了

在这里分享在Unity中对数据的加密与解密的处理


加密与解密一般可以应用到文件配置,但是我主要运用到客户端与服务器端交互时候

【加密】

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

public class Encryption : MonoBehaviour 
{
    /// 
    /// 需要加密内容
    /// 
    public InputField inputCtt;

    /// 
    /// 加密结果
    /// 
    public InputField inputRes;

    /// 
    /// 32位任意数值,作为是加密解码约定数字
    /// 
    private string keyValue = "01234567890123456789012345678901";

	public void OnBtnEncryption()
    {
        if (inputCtt.text.Length != 0)
        {
            string str = ConductEncryption(inputCtt.text, keyValue);
            inputRes.text = str;
        }
        else
        {
            Debug.Log("请输入加密内容");
        }
    }


    /// 
    /// 加密
    /// 
    /// 在输入框中需要加密内容
    /// 
    /// 
    private string ConductEncryption(string _input,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(_input);
        byte[] resultArray = cTransform.TransformFinalBlock(_EncryptArray, 0, _EncryptArray.Length);
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }
}

【解密】

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


public class Decrypt : MonoBehaviour 
{
    /// 
    /// 获得需要解密的字符串
    /// 
    public InputField valueDense;

    /// 
    /// 32位任意数值,作为是加密解码约定数字
    /// 
    private string keyValue = "01234567890123456789012345678901";

    public void OnBtnDecrypt()
    {
        if (valueDense.text.Length != 0)
        {
            string str = ConductDecrypt(valueDense.text,keyValue);
            valueDense.text = str;
        }
        else
        {
            Debug.Log("请输入需要解密的值");
        }
    }

    private string ConductDecrypt(string _valueDense, string _keyValue)
    {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes(_keyValue);

        RijndaelManaged decipher = new RijndaelManaged();
        decipher.Key = keyArray;
        decipher.Mode = CipherMode.ECB;
        decipher.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = decipher.CreateDecryptor();
        byte[] _EncryptArray = Convert.FromBase64String(_valueDense);
        byte[] resultArray = cTransform.TransformFinalBlock(_EncryptArray, 0, _EncryptArray.Length);
        return UTF8Encoding.UTF8.GetString(resultArray);
    }
	
}

【检测】

Unity数据的加密与解密_第1张图片

在第一个输入框上输入需要加密的内容,当点击加密按钮后,加密后的数据便输出在第二个输入框中

再点击解密按钮后,便有解密后的数据输出



你可能感兴趣的:(移动游戏开发,移动游戏开发,unity3d,unity3d,Unity游戏开发)