您的位置:首页 > 移动开发 > Unity3D

【Unity】如何使用MD5加密方式传递资料

2017-04-10 15:57 459 查看
在实际专案中,如果需要用到资料传递,可以利用
MD5 来为资料进行加密,考虑到有些人还不会,下面就给大家介绍下Unity MD5 加密,一起来看看吧。

  实际利用如下:

先建立 CreateMD5.cs 脚本

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

public class CreateMD5 : MonoBehaviour
{
public string inputString;
public string hashString;

void Awake()
{
MD5 md5Hash = MD5.Create();
hashString = GetMD5Hash(md5Hash, inputString);
hashString = hashString.ToUpper();
}

private string GetMD5Hash(MD5 md5Hash, string input)
{
//Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

//Create a new StringBuilder to collect the bytes and create a string.
StringBuilder builder = new StringBuilder();

//Loop through each byte of the hashed data and format each one as a hexadecimal strings.
for(int cnt = 0; cnt < data.Length; cnt++)
{
builder.Append(data[cnt].ToString("x2"));
}

//Return the hexadecimal string
return builder.ToString();
}

private bool VerifyMD5Hash(MD5 md5Hash, string input, string hash)
{
//Hash the input
string hashOfInput = GetMD5Hash(md5Hash, input);

//Create a StringComparer to compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;

return 0 == comparer.Compare(hashOfInput, hash);
}
}


  接著将脚本赋予场上物件并随意输入字串
  开始游戏后即可获得由输入字串所产生的加密字串



  若需要对加密字串进行验证
  只需要呼叫 VerifyMd5Hash 方法即可以对字串验证
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐