Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


MatsK

Member Since 21 Feb 2008
Offline Last Active Today, 01:20 PM

Topics I've Started

Cryptography - am I doing it right?

27 March 2014 - 10:24 AM

I'm trying to establish a secure connection in C#, and I'm not sure I'm doing it right. :(

 

Here is my encryption class:

/*The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.

The Original Code is the GonzoNet.

The Initial Developer of the Original Code is
Mats 'Afr0' Vederhus. All Rights Reserved.

Contributor(s): ______________________________________.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace GonzoNet.Encryption
{
    public class ARC4Encryptor : Encryptor
    {
        private DESCryptoServiceProvider m_CryptoService = new DESCryptoServiceProvider();
        private ICryptoTransform m_DecryptTransformer, m_EncryptTransformer;
        public byte[] EncryptionKey;

        public ARC4Encryptor(string Password)
            : base(Password)
        {
            PasswordDeriveBytes Pwd = new PasswordDeriveBytes(Encoding.ASCII.GetBytes(Password), 
                Encoding.ASCII.GetBytes("SALT"), "SHA1", 10);
            EncryptionKey = Pwd.GetBytes(8);
            m_DecryptTransformer = m_CryptoService.CreateDecryptor(EncryptionKey, Encoding.ASCII.GetBytes("@1B2c3D4e5F6g7H8"));
            m_EncryptTransformer = m_CryptoService.CreateEncryptor(EncryptionKey, Encoding.ASCII.GetBytes("@1B2c3D4e5F6g7H8"));
        }

        public ARC4Encryptor(string Password, byte[] EncKey)
            : base(Password)
        {
            PasswordDeriveBytes Pwd = new PasswordDeriveBytes(Encoding.ASCII.GetBytes(Password),
                Encoding.ASCII.GetBytes("SALT"), "SHA1", 10);
            EncryptionKey = EncKey;
            m_DecryptTransformer = m_CryptoService.CreateDecryptor(EncryptionKey, Encoding.ASCII.GetBytes("@1B2c3D4e5F6g7H8"));
            m_EncryptTransformer = m_CryptoService.CreateEncryptor(EncryptionKey, Encoding.ASCII.GetBytes("@1B2c3D4e5F6g7H8"));
        }

        public override DecryptionArgsContainer GetDecryptionArgsContainer()
        {
            DecryptionArgsContainer DArgsContainer = new DecryptionArgsContainer();
            DArgsContainer.ARC4DecryptArgs = new ARC4DecryptionArgs();
            DArgsContainer.ARC4DecryptArgs.Transformer = m_DecryptTransformer;

            return DArgsContainer;
        }

        public override byte[] FinalizePacket(byte PacketID, byte[] PacketData)
        {
            MemoryStream FinalizedPacket = new MemoryStream();
            BinaryWriter PacketWriter = new BinaryWriter(FinalizedPacket);

            MemoryStream TempStream = new MemoryStream();
            CryptoStream EncryptedStream = new CryptoStream(TempStream,
                m_EncryptTransformer, CryptoStreamMode.Write);
            EncryptedStream.Write(PacketData, 0, PacketData.Length);
            EncryptedStream.FlushFinalBlock();

            PacketWriter.Write(PacketID);
            //The length of the encrypted data can be longer or smaller than the original length,
            //so write the length of the encrypted data.
            PacketWriter.Write((ushort)((long)PacketHeaders.ENCRYPTED + TempStream.Length));
            //Also write the length of the unencrypted data.
            PacketWriter.Write((ushort)PacketData.Length);
            PacketWriter.Flush();

            PacketWriter.Write(TempStream.ToArray());
            PacketWriter.Flush();

            byte[] ReturnPacket = FinalizedPacket.ToArray();

            PacketWriter.Close();

            return ReturnPacket;
        }

        public override MemoryStream DecryptPacket(PacketStream EncryptedPacket, DecryptionArgsContainer DecryptionArgs)
        {
            CryptoStream CStream = new CryptoStream(EncryptedPacket, m_DecryptTransformer, CryptoStreamMode.Read);

            byte[] DecryptedBuffer = new byte[DecryptionArgs.UnencryptedLength];
            CStream.Read(DecryptedBuffer, 0, DecryptedBuffer.Length);

            return new MemoryStream(DecryptedBuffer);
        }
    }
}

Then I initialize it as such on the client and server side:

            //Doing the encryption this way eliminates the need to send key across the wire! :D
            SaltedHash Hash = new SaltedHash(new SHA512Managed(), Args.Username.Length);
            byte[] HashBuf = Hash.ComputePasswordHash(Args.Username, Args.Password);
            Args.Enc = new GonzoNet.Encryption.ARC4Encryptor(Convert.ToBase64String(HashBuf));

Then when establishing the secure connection, I'm sending the hash across. What I'm wondering is: Could the hash be used to generate the key by a man-in-the-middle attacker?

If so, would it help to Blowfish the hash using itself as they key, so that if the hash stored in the DB is correct, it will be able to decrypt itself?

Should I just rewrite the protocol using Diffie-Helllman?


Rotating with versors...

17 October 2012 - 11:01 AM

Can someone please explain how to rotate using a versor in XNA?
I'm trying to setup a skeletal render using the SKEL format in XNA;

"Rotation - A normalized quaternion, called a "versor", consisting of X,Y,Z,W coordinates, each a 32-bit little-endian float, which specify the default direction of rotation"

It seems the common way to rotate in XNA is to create matrix from a Vector3 instance. I've tried creating a matrix using Matrix.CreateFromQuaternion(), but that doesn't seem to work very well. Here's the code I'm currently using;

	    /// <summary>
	    /// Compute the absolute transformation for this bone.
	    /// </summary>
	    public void ComputeAbsoluteTransform()
	    {
		    if (ParentName != "NULL")
		    {
				    m_AbsoluteTransform = Matrix.CreateFromQuaternion(GlobalRotation) * Matrix.CreateTranslation(GlobalTranslation) * Parent.AbsoluteTransform;
		    }
		    //This bone didn't have a parent, which means it is probably the root bone.
		    else
		    {
			    m_AbsoluteTransform =  Matrix.CreateFromQuaternion(GlobalRotation) * Matrix.CreateTranslation(GlobalTranslation);
		    }
	    }

I've searched for examples, and the most relevant I've been able to find so far is this one. It doesn't help me very much though...

Please help, how do I do this??

Screen to world coordinates

05 August 2012 - 11:22 AM

Hi!
I'm rendering 3D on top of 2D, and it seems to be working, but I need to be able to render a specific mesh at, say - 10, 10 in screen coordinates.
How?

My current approach involves using Viewport.Unproject(), but it doesn't seem to be working;

[source lang="csharp"] Vector3 NearScreenPoint = new Vector3(0, 0, 0); Vector3 FarScreenPoint = new Vector3(0, 0, 1); Vector3 NearWorldPoint = m_Scene.SceneMgr.Device.Viewport.Unproject(NearScreenPoint, m_Scene.SceneMgr.ProjectionMatrix, m_Scene.SceneMgr.ViewMatrix, m_Scene.SceneMgr.WorldMatrix); Vector3 FarWorldPoint = m_Scene.SceneMgr.Device.Viewport.Unproject(FarScreenPoint, m_Scene.SceneMgr.ProjectionMatrix, m_Scene.SceneMgr.ViewMatrix, m_Scene.SceneMgr.WorldMatrix); Vector3 Direction = FarWorldPoint - NearWorldPoint; Direction.Normalize(); if (m_CurrentHeadMeshes.Count > 0) { for (int i = 0; i < m_CurrentHeadMeshes[0].VertexTexNormalPositions.Length; i++) { /*Vector4 Position = new Vector4(m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position, 1); Matrix WorldMat = Matrix.CreateWorld(new Vector3(0, 0, 0), Vector3.Forward, new Vector3(0, 1, 0)); Vector4.Transform(ref Position, ref WorldMat, out Position); Position /= Position.W; m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position.X = Position.X; m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position.Y = Position.Y; m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position.Z = Position.Z;*/ m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position *= Direction; } }[/source]

I also want to rotate the mesh around it's X-axis, but I commented out the code for doing that since it complicated things. Anyway, here is my entire code:

[source lang="csharp"]using System;using System.Collections.Generic;using System.Text;using System.IO;using SimsLib.ThreeD;using Microsoft.Xna.Framework;using Microsoft.Xna.Framework.Graphics;using LogThis;namespace TSOClient.ThreeD{ /// <summary> /// Represents a surface for rendering 3D elements (sims) on top of UI elements. /// </summary> public class UI3DView : ThreeDElement { private List<BasicEffect> m_Effects; private float m_Rotation; private List<Mesh> m_CurrentHeadMeshes; private List<Texture2D> m_HeadTextures; private int m_Width, m_Height; private bool m_SingleRenderer = true; private SpriteBatch m_SBatch; private Camera2D Cam = new Camera2D(); /// <summary> /// Constructs a new UI3DView instance. /// </summary> /// <param name="Width">The width of this UI3DView surface.</param> /// <param name="Height">The height of this UI3DView surface.</param> /// <param name="SingleRenderer">Will this surface be used to render a single, or multiple sims?</param> /// <param name="Screen">The ThreeDScene instance with which to create this UI3DView instance.</param> /// <param name="StrID">The string ID for this UI3DView instance.</param> public UI3DView(int Width, int Height, bool SingleRenderer, ThreeDScene Screen, string StrID) : base(Screen) { m_Effects = new List<BasicEffect>(); m_Width = Width; m_Height = Height; m_SingleRenderer = SingleRenderer; m_CurrentHeadMeshes = new List<Mesh>(); m_HeadTextures = new List<Texture2D>(); m_SBatch = new SpriteBatch(m_Scene.SceneMgr.Device); m_Scene.SceneMgr.Device.DeviceReset += new EventHandler(GraphicsDevice_DeviceReset); } /// <summary> /// Occurs when the graphicsdevice was reset, meaning all 3D resources /// have to be recreated. /// </summary> private void GraphicsDevice_DeviceReset(object sender, EventArgs e) { for (int i = 0; i < m_Effects.Count; i++) m_Effects[i] = new BasicEffect(m_Scene.SceneMgr.Device, null); m_Scene.SceneMgr.Device.VertexDeclaration = new VertexDeclaration(m_Scene.SceneMgr.Device, VertexPositionNormalTexture.VertexElements); m_Scene.SceneMgr.Device.RenderState.CullMode = CullMode.None; // Create camera and projection matrix m_Scene.SceneMgr.WorldMatrix = Matrix.Identity; m_Scene.SceneMgr.ViewMatrix = Matrix.CreateLookAt(Vector3.Right * 5, Vector3.Zero, Vector3.Down); m_Scene.SceneMgr.ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.Pi / 4.0f, (float)m_Scene.SceneMgr.Device.PresentationParameters.BackBufferWidth / (float)m_Scene.SceneMgr.Device.PresentationParameters.BackBufferHeight, 1.0f, 100.0f); } /// <summary> /// Loads a head mesh. /// </summary> /// <param name="MeshID">The ID of the mesh to load.</param> /// <param name="TexID">The ID of the texture to load.</param> public void LoadHeadMesh(Outfit Outf, int SkinColor) { Appearance Apr; switch (SkinColor) { case 0: Apr = new Appearance(ContentManager.GetResourceFromLongID(Outf.LightAppearanceID)); break; case 1: Apr = new Appearance(ContentManager.GetResourceFromLongID(Outf.MediumAppearanceID)); break; case 2: Apr = new Appearance(ContentManager.GetResourceFromLongID(Outf.DarkAppearanceID)); break; default: Apr = new Appearance(ContentManager.GetResourceFromLongID(Outf.LightAppearanceID)); break; } Binding Bnd = new Binding(ContentManager.GetResourceFromLongID(Apr.BindingIDs[0])); if (m_CurrentHeadMeshes.Count > 0) { if (!m_SingleRenderer) { m_Effects.Add(new BasicEffect(m_Scene.SceneMgr.Device, null)); m_CurrentHeadMeshes.Add(new Mesh(ContentManager.GetResourceFromLongID(Bnd.MeshAssetID), false)); m_CurrentHeadMeshes[m_CurrentHeadMeshes.Count - 1].ProcessMesh(); m_HeadTextures.Add(Texture2D.FromFile(m_Scene.SceneMgr.Device, new MemoryStream(ContentManager.GetResourceFromLongID(Bnd.TextureAssetID)))); } else { m_Effects[0] = new BasicEffect(m_Scene.SceneMgr.Device, null); m_CurrentHeadMeshes[0] = new Mesh(ContentManager.GetResourceFromLongID(Bnd.MeshAssetID), false); m_CurrentHeadMeshes[m_CurrentHeadMeshes.Count - 1].ProcessMesh(); m_HeadTextures[0] = Texture2D.FromFile(m_Scene.SceneMgr.Device, new MemoryStream(ContentManager.GetResourceFromLongID(Bnd.TextureAssetID))); Vector3 NearScreenPoint = new Vector3(0, 0, 0); Vector3 FarScreenPoint = new Vector3(0, 0, 1); Vector3 NearWorldPoint = m_Scene.SceneMgr.Device.Viewport.Unproject(NearScreenPoint, m_Scene.SceneMgr.ProjectionMatrix, m_Scene.SceneMgr.ViewMatrix, m_Scene.SceneMgr.WorldMatrix); Vector3 FarWorldPoint = m_Scene.SceneMgr.Device.Viewport.Unproject(FarScreenPoint, m_Scene.SceneMgr.ProjectionMatrix, m_Scene.SceneMgr.ViewMatrix, m_Scene.SceneMgr.WorldMatrix); Vector3 Direction = FarWorldPoint - NearWorldPoint; Direction.Normalize(); if (m_CurrentHeadMeshes.Count > 0) { for (int i = 0; i < m_CurrentHeadMeshes[0].VertexTexNormalPositions.Length; i++) { /*Vector4 Position = new Vector4(m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position, 1); Matrix WorldMat = Matrix.CreateWorld(new Vector3(0, 0, 0), Vector3.Forward, new Vector3(0, 1, 0)); Vector4.Transform(ref Position, ref WorldMat, out Position); Position /= Position.W; m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position.X = Position.X; m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position.Y = Position.Y; m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position.Z = Position.Z;*/ m_CurrentHeadMeshes[0].VertexTexNormalPositions[i].Position *= Direction; } } } } else { m_Effects.Add(new BasicEffect(m_Scene.SceneMgr.Device, null)); m_CurrentHeadMeshes.Add(new Mesh(ContentManager.GetResourceFromLongID(Bnd.MeshAssetID), false)); m_CurrentHeadMeshes[m_CurrentHeadMeshes.Count - 1].ProcessMesh(); m_HeadTextures.Add(Texture2D.FromFile(m_Scene.SceneMgr.Device, new MemoryStream(ContentManager.GetResourceFromLongID(Bnd.TextureAssetID)))); } } public override void Update(GameTime GTime) { /*m_Rotation += 0.01f; m_Scene.SceneMgr.WorldMatrix = Matrix.CreateRotationX(m_Rotation);*/ base.Update(GTime); } public override void Draw() { base.Draw(); for (int i = 0; i < m_Effects.Count; i++) { for (int j = 0; j < m_HeadTextures.Count; j++) { if (m_HeadTextures[j] != null) { m_Effects[i].World = m_Scene.SceneMgr.WorldMatrix; m_Effects[i].View = m_Scene.SceneMgr.ViewMatrix; m_Effects[i].Projection = m_Scene.SceneMgr.ProjectionMatrix; m_Effects[i].Texture = m_HeadTextures[j]; m_Effects[i].TextureEnabled = true; m_Effects[i].EnableDefaultLighting(); m_Effects[i].CommitChanges(); // Draw m_Effects[i].Begin(); for (int k = 0; k < m_Effects[i].Techniques.Count; k++) { foreach (EffectPass Pass in m_Effects[i].Techniques[k].Passes) { Pass.Begin(); foreach (Mesh Msh in m_CurrentHeadMeshes) { foreach (Face Fce in Msh.Faces) { if (Msh.VertexTexNormalPositions != null) { VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = Msh.VertexTexNormalPositions[Fce.AVertexIndex]; Vertex[1] = Msh.VertexTexNormalPositions[Fce.BVertexIndex]; Vertex[2] = Msh.VertexTexNormalPositions[Fce.CVertexIndex]; Vertex[0].TextureCoordinate = Msh.VertexTexNormalPositions[Fce.AVertexIndex].TextureCoordinate; Vertex[1].TextureCoordinate = Msh.VertexTexNormalPositions[Fce.BVertexIndex].TextureCoordinate; Vertex[2].TextureCoordinate = Msh.VertexTexNormalPositions[Fce.CVertexIndex].TextureCoordinate; m_Scene.SceneMgr.Device.DrawUserPrimitives<VertexPositionNormalTexture>( PrimitiveType.TriangleList, Vertex, 0, 1); } } } Pass.End(); m_Effects[i].End(); } } } } } }}[/source]
Also, here's my View, World and Projection:

[source lang="csharp"] m_WorldMatrix = Matrix.Identity; m_ViewMatrix = Matrix.CreateLookAt(Vector3.Backward * 5, Vector3.Zero, Vector3.Right); m_ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.Pi / 4.0f, (float)Device.PresentationParameters.BackBufferWidth / (float)Device.PresentationParameters.BackBufferHeight, 1.0f, 100.0f);[/source]

I've been Googling around for answers to this issue for some time now, but everything seems to revolve around picking, which isn't helping me.

Drawing skeleton dots

07 July 2012 - 08:39 PM

I'm trying to render a number of vertices (dots) in order to ensure that my skeleton is setup correctly. But I can't figure out how to do the equivalent of:

static void DrawBonesSkeleton(Bone_t& Bone)
{
	glPointSize(5.0);
	glTranslatef(Bone.Translation.x, Bone.Translation.y, Bone.Translation.z);
	float RotationMatrix[16];
	FindQuaternionMatrix(RotationMatrix, &Bone.Rotation);
	glMultMatrixf(RotationMatrix);

	if(!strcmp(Bone.Name, "ROOT"))
		glColor3f(1.0, 0.0, 0.0);
	else if(!strcmp(Bone.Name, "HEAD"))
		glColor3f(1.0, 1.0, 0.0);
	else
		glColor3f(0.0, 1.0, 0.0);
	glBegin(GL_POINTS); glVertex3f(0, 0, 0); glEnd();

	if(Bone.ChildrenCount == 1){
		DrawBonesSkeleton(*Bone.Children[0]);
	}else if(Bone.ChildrenCount > 1){
		for(unsigned i=0; i<Bone.ChildrenCount; i++){
			glPushMatrix();
			DrawBonesSkeleton(*Bone.Children[i]);
			glPopMatrix();
		}
	}
}

static void DrawSkeleton()
{
	glPushMatrix();
	DrawBonesSkeleton(Skeleton.Bones[0]);
	glPopMatrix();
}

in XNA - my current attempt involves one call to DrawUserPrimitives() when rendering, but the output obviously isn't correct because DrawBonesSkeleton is a recursive function. Please, if you have any ideas - reply!

Edit: Why isn't the entire code displayed?
Edit2 by Hodgman: We seem to be having some bugs with the source tag at the moment, the code tag still seems to work though...

Recursive calls with pass-by-reference indexers!

06 March 2012 - 04:12 AM

I'm trying to render a skeleton to the screen, and making it render properly requires me to use recursion and pass by reference. But I can't do that, because I get the error A property or indexer may not be passed as an out or ref parameter.
Here's what I'm trying to do:

public static void DrawBonesSkeleton(ref Bone Bne)
		{
			Gl.glPointSize(5.0f);
			Gl.glTranslatef(Bne.GlobalTranslation.X, Bne.GlobalTranslation.Y, Bne.GlobalTranslation.Z);
			float[] RotationMatrix = FindQuaternionMatrix(Bne.GlobalRotation);
			Gl.glMultMatrixf(RotationMatrix);
			if (Bne.BoneName == "ROOT")
				Gl.glColor3f(1.0f, 0.0f, 0.0f);
			else if (Bne.BoneName == "HEAD")
				Gl.glColor3f(1.0f, 1.0f, 0.0f);
			else
				Gl.glColor3f(0.0f, 1.0f, 0.0f);
			Gl.glBegin(Gl.GL_POINTS); Gl.glVertex3f(0, 0, 0); Gl.glEnd();
			if (Bne.Children.Count == 1)
				DrawBonesSkeleton(ref Bne.Children[0]);
			else if (Bne.Children.Count > 1)
			{
				for (int i = 0; i < Bne.Children.Count; i++)
					DrawBonesSkeleton(ref Bne.Children[i]);
			}
		}

The original code is:

void DrawBonesSkeleton(Bone_t& Bone)
341 {
342	 glPointSize(5.0);
343	 glTranslatef(Bone.Translation.x, Bone.Translation.y, Bone.Translation.z);
344	 float RotationMatrix[16];
345	 FindQuaternionMatrix(RotationMatrix, &Bone.Rotation);
346	 glMultMatrixf(RotationMatrix);
347
348	 if(!strcmp(Bone.Name, "ROOT"))
349		 glColor3f(1.0, 0.0, 0.0);
350	 else if(!strcmp(Bone.Name, "HEAD"))
351		 glColor3f(1.0, 1.0, 0.0);
352	 else
353		 glColor3f(0.0, 1.0, 0.0);
354	 glBegin(GL_POINTS); glVertex3f(0, 0, 0); glEnd();
355
356	 if(Bone.ChildrenCount == 1){
357		 DrawBonesSkeleton(*Bone.Children[0]);
358	 }else if(Bone.ChildrenCount > 1){
359		 for(unsigned i=0; i<Bone.ChildrenCount; i++){
360			 glPushMatrix();
361			 DrawBonesSkeleton(*Bone.Children[i]);
362			 glPopMatrix();
363		 }
364	 }
365 }

Please keep in mind that I'm trying to do this *without* pointers. Pointers are my last resort. Is there any way to get around this problem, or am I stuck with having to use pointers?

Note: I already tried looping through the bones using foreach, but it results in the skeleton being rendered incorrectly.

PARTNERS