C#序列化ASCII混淆 [英] c# serialization ascii confusion

查看:38
本文介绍了C#序列化ASCII混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码.

[Serializable]
public class HostedGame
{
    public int ID { get; set; }

    public int UID { get; set; }

    public String Name { get; set; }

    public Boolean Available { get; set; }

    public String Description { get; set; }

    public List<int> Users { get; set; }

    public int Port { get; set; }

    public HostedGame(int uid, String name, String description, int port)
    {
        UID = uid;
        Name = name;
        Description = description;
        Available = true;
        Port = port;
        Users = new List<int>();
    }

    public int CompareTo(Object obj)
    {
        int result = 1;
        if(obj != null && obj is HostedGame)
        {
            HostedGame w = obj as HostedGame;
            result = this.ID.CompareTo(w.ID);
        }
        return result;
    }

    static public int Compare(HostedGame x, HostedGame y)
    {
        int result = 1;
        if(x != null && y != null)
        {
            result = x.CompareTo(y);
        }
        return result;
    }

    public static HostedGame DeSerialize(byte[] data)
    {
        MemoryStream ms = new MemoryStream(data);
        BinaryFormatter bff = new BinaryFormatter();
        return (HostedGame)bff.Deserialize(ms);
    }

    public static byte[] Serialize(HostedGame obj)
    {
        BinaryFormatter bff = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bff.Serialize(ms, obj);
        return ms.ToArray();
    }
}

下面的代码似乎无法正常工作:

The code bellow doesn't seem to work right:

HostedGame hs = new HostedGame(12,"Name", "Description", 8088);
String s = Encoding.ASCII.GetString(HostedGame.Serialize(hs));
HostedGame HACK = HostedGame.DeSerialize(Encoding.ASCII.GetBytes(s));

HACK.Port 由于某种原因出现在7999吗?

HACK.Port for some reason comes out being 7999?

当我这样做时...

HostedGame HACK = HostedGame.DeSerialize(HostedGame.Serialize(hs));

它工作正常.

  1. 我为什么会得到错误的值?
  2. 是否有更好的方法将字节转换为字符串然后再次返回?

推荐答案

您不能使用 Encoding.ASCII.GetString 将任何字节数组转换为字符串.当您这样做时,您正在丢失一些数据.请使用 Convert.ToBase64String .这将从任何字节序列中构成一个字符串,而不会丢失数据.

You cannot use Encoding.ASCII.GetString to convert any byte array to a string. You are losing some data when you do this. Use Convert.ToBase64String instead. This one will make a string from any byte sequence without losing the data.

HostedGame hs = new HostedGame(12,"Name", "Description", 8088);
String s = Convert.ToBase64String(HostedGame.Serialize(hs));
HostedGame HACK= HostedGame.DeSerialize(Convert.FromBase64String(s));

这里是一个示例,显示了如何使用 Encoding.ASCII 丢失数据.

Here is an example, that shows how using Encoding.ASCII loses the data.

var testBytes = new byte[] { 250, 251, 252 };
var text = Encoding.ASCII.GetString(testBytes);
var bytes = Encoding.ASCII.GetBytes(result); // will be 63, 63, 63

这篇关于C#序列化ASCII混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆