shuihan20e 2014年02月10日
c# md5 加密byte[]
结构体声明如下

[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
struct TMsgHeadInfo
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public char[] MsgCode;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public char[] MsgType; public byte SenderType;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public char[] Sender; public byte ReceiverType;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public char[] Receiver; public int TotalLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public char[] VerifyCode;
}

[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
struct TDevCheck
{
public byte DevType;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public char[] DevCode;
public Int32 OutTime;
}

[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
struct TDevChecks
{
public TMsgHeadInfo MsgHead;
public TDevCheck DevCheck;
}


TDevChecks DevChecks;// = new TDevChecks();
DevChecks.MsgHead.MsgCode = "02".ToCharArray();
DevChecks.MsgHead.MsgType = "02".ToCharArray();
DevChecks.MsgHead.Receiver = "000000".ToCharArray();
DevChecks.MsgHead.ReceiverType = 4;
DevChecks.MsgHead.Sender = "280300".ToCharArray();//Global.sLocalCode.ToCharArray();
DevChecks.MsgHead.SenderType = 1;
DevChecks.MsgHead.TotalLength = 69;
DevChecks.MsgHead.VerifyCode = "235A3ECDB49A612AFDE4F4C3D6735D5D".ToCharArray();
DevChecks.DevCheck.DevCode = "2803004004".ToCharArray();
DevChecks.DevCheck.DevType = 1;
DevChecks.DevCheck.OutTime = Global.nCheckOutTime;
DevChecks.MsgHead.VerifyCode =MD5Byte(Global.tool.StructToBytes(DevChecks.DevCheck)).ToCharArray();
string md5 = new string(DevChecks.MsgHead.VerifyCode);
txt.Text = md5;

如上面的代码,C#算出的是
9ACFE5A41240B9D8AC6B47F46D9BA2F
其他语言算出的如下
9ACFE5A41240B9D8AC06B47F46D9BA2F
也就是少了一位,应该是32位,却是31位

MD5加密算法如下
        public string MD5Byte(byte[] by)
{
string pwd = "";
MD5 md5 = MD5.Create();
byte[] s = md5.ComputeHash(by);
for (int i = 0; i < s.Length; i++)
{
pwd = pwd + s[i].ToString("X");
}
return pwd;
}

结构体转byte[]算法如下
        public Byte[] StructToBytes(Object structure)
{
Int32 size = Marshal.SizeOf(structure);
//Console.WriteLine(size);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structure, buffer, false);
Byte[] bytes = new Byte[size];
Marshal.Copy(buffer, bytes, 0, size);
return bytes;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}


另外如何得到一个对象的大小Marshl.sizeof得到的值不对啊
...全文
130 1 收藏 4
写回复
4 条回复

还没有回复,快来抢沙发~

发动态
发帖子
C#
创建于2007-09-28

8.4w+

社区成员

64.0w+

社区内容

.NET技术 C#
社区公告
暂无公告