Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Pedroalves

[Resolvido] Encriptção

Recommended Posts

alguem me pode ajudar a passar o codigo de incriptação do joomla para c#

o codigo esta em php e javascript e queria passar para c#

<?php
/**
* @package     Joomla.Platform
* @subpackage  User
*
* @copyright   Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license     GNU General Public License version 2 or later; see LICENSE
*/

defined('JPATH_PLATFORM') or die;

/**
* Authorisation helper class, provides static methods to perform various tasks relevant
* to the Joomla user and authorisation classes
*
* This class has influences and some method logic from the Horde Auth package
*
* @package     Joomla.Platform
* @subpackage  User
* @since       11.1
*/
abstract class JUserHelper
{
/**
 * Method to add a user to a group.
 *
 * @param   integer  $userId   The id of the user.
 * @param   integer  $groupId  The id of the group.
 *
 * @return  mixed  Boolean true on success, Exception on error.
 *
 * @since   11.1
 */
public static function addUserToGroup($userId, $groupId)
{
	// Get the user object.
	$user = new JUser((int) $userId);

	// Add the user to the group if necessary.
	if (!in_array($groupId, $user->groups))
	{
		// Get the title of the group.
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query->select($db->quoteName('title'));
		$query->from($db->quoteName('#__usergroups'));
		$query->where($db->quoteName('id') . ' = ' . (int) $groupId);
		$db->setQuery($query);
		$title = $db->loadResult();

		// Check for a database error.
		if ($db->getErrorNum())
		{
			return new Exception($db->getErrorMsg());
		}

		// If the group does not exist, return an exception.
		if (!$title)
		{
			return new Exception(JText::_('JLIB_USER_EXCEPTION_ACCESS_USERGROUP_INVALID'));
		}

		// Add the group data to the user object.
		$user->groups[$title] = $groupId;

		// Store the user object.
		if (!$user->save())
		{
			return new Exception($user->getError());
		}
	}

	// Set the group data for any preloaded user objects.
	$temp = JFactory::getUser((int) $userId);
	$temp->groups = $user->groups;

	// Set the group data for the user object in the session.
	$temp = JFactory::getUser();
	if ($temp->id == $userId)
	{
		$temp->groups = $user->groups;
	}

	return true;
}

/**
 * Method to get a list of groups a user is in.
 *
 * @param   integer  $userId  The id of the user.
 *
 * @return  mixed  Array on success, JException on error.
 *
 * @since   11.1
 */
public static function getUserGroups($userId)
{
	// Get the user object.
	$user = JUser::getInstance((int) $userId);

	return isset($user->groups) ? $user->groups : array();
}

/**
 * Method to remove a user from a group.
 *
 * @param   integer  $userId   The id of the user.
 * @param   integer  $groupId  The id of the group.
 *
 * @return  mixed  Boolean true on success, JException on error.
 *
 * @since   11.1
 */
public static function removeUserFromGroup($userId, $groupId)
{
	// Get the user object.
	$user = JUser::getInstance((int) $userId);

	// Remove the user from the group if necessary.
	$key = array_search($groupId, $user->groups);
	if ($key !== false)
	{
		// Remove the user from the group.
		unset($user->groups[$key]);

		// Store the user object.
		if (!$user->save())
		{
			return new JException($user->getError());
		}
	}

	// Set the group data for any preloaded user objects.
	$temp = JFactory::getUser((int) $userId);
	$temp->groups = $user->groups;

	// Set the group data for the user object in the session.
	$temp = JFactory::getUser();
	if ($temp->id == $userId)
	{
		$temp->groups = $user->groups;
	}

	return true;
}

/**
 * Method to set the groups for a user.
 *
 * @param   integer  $userId  The id of the user.
 * @param   array    $groups  An array of group ids to put the user in.
 *
 * @return  mixed  Boolean true on success, Exception on error.
 *
 * @since   11.1
 */
public static function setUserGroups($userId, $groups)
{
	// Get the user object.
	$user = JUser::getInstance((int) $userId);

	// Set the group ids.
	JArrayHelper::toInteger($groups);
	$user->groups = $groups;

	// Get the titles for the user groups.
	$db = JFactory::getDbo();
	$query = $db->getQuery(true);
	$query->select($db->quoteName('id') . ', ' . $db->quoteName('title'));
	$query->from($db->quoteName('#__usergroups'));
	$query->where($db->quoteName('id') . ' = ' . implode(' OR ' . $db->quoteName('id') . ' = ', $user->groups));
	$db->setQuery($query);
	$results = $db->loadObjectList();

	// Check for a database error.
	if ($db->getErrorNum())
	{
		return new Exception($db->getErrorMsg());
	}

	// Set the titles for the user groups.
	for ($i = 0, $n = count($results); $i < $n; $i++)
	{
		$user->groups[$results[$i]->id] = $results[$i]->title;
	}

	// Store the user object.
	if (!$user->save())
	{
		return new Exception($user->getError());
	}

	// Set the group data for any preloaded user objects.
	$temp = JFactory::getUser((int) $userId);
	$temp->groups = $user->groups;

	// Set the group data for the user object in the session.
	$temp = JFactory::getUser();
	if ($temp->id == $userId)
	{
		$temp->groups = $user->groups;
	}

	return true;
}

/**
 * Gets the user profile information
 *
 * @param   integer  $userId  The id of the user.
 *
 * @return  object
 *
 * @since   11.1
 */
public function getProfile($userId = 0)
{
	if ($userId == 0)
	{
		$user	= JFactory::getUser();
		$userId	= $user->id;
	}

	// Get the dispatcher and load the user's plugins.
	$dispatcher	= JDispatcher::getInstance();
	JPluginHelper::importPlugin('user');

	$data = new JObject;
	$data->id = $userId;

	// Trigger the data preparation event.
	$dispatcher->trigger('onContentPrepareData', array('com_users.profile', &$data));

	return $data;
}

/**
 * Method to activate a user
 *
 * @param   string  $activation  Activation string
 *
 * @return  boolean  True on success
 *
 * @since   11.1
 */
public static function activateUser($activation)
{
	// Initialize some variables.
	$db = JFactory::getDbo();
	$query = $db->getQuery(true);

	// Let's get the id of the user we want to activate
	$query->select($db->quoteName('id'));
	$query->from($db->quoteName('#__users'));
	$query->where($db->quoteName('activation') . ' = ' . $db->quote($activation));
	$query->where($db->quoteName('block') . ' = 1');
	$query->where($db->quoteName('lastvisitDate') . ' = ' . $db->quote('0000-00-00 00:00:00'));
	$db->setQuery($query);
	$id = intval($db->loadResult());

	// Is it a valid user to activate?
	if ($id)
	{
		$user = JUser::getInstance((int) $id);

		$user->set('block', '0');
		$user->set('activation', '');

		// Time to take care of business.... store the user.
		if (!$user->save())
		{
			JError::raiseWarning("SOME_ERROR_CODE", $user->getError());
			return false;
		}
	}
	else
	{
		JError::raiseWarning("SOME_ERROR_CODE", JText::_('JLIB_USER_ERROR_UNABLE_TO_FIND_USER'));
		return false;
	}

	return true;
}

/**
 * Returns userid if a user exists
 *
 * @param   string  $username  The username to search on.
 *
 * @return  integer  The user id or 0 if not found.
 *
 * @since   11.1
 */
public static function getUserId($username)
{
	// Initialise some variables
	$db = JFactory::getDbo();
	$query = $db->getQuery(true);
	$query->select($db->quoteName('id'));
	$query->from($db->quoteName('#__users'));
	$query->where($db->quoteName('username') . ' = ' . $db->quote($username));
	$db->setQuery($query, 0, 1);
	return $db->loadResult();
}

/**
 * Formats a password using the current encryption.
 *
 * @param   string   $plaintext     The plaintext password to encrypt.
 * @param   string   $salt          The salt to use to encrypt the password. []
 *                                  If not present, a new salt will be
 *                                  generated.
 * @param   string   $encryption    The kind of password encryption to use.
 *                                  Defaults to md5-hex.
 * @param   boolean  $show_encrypt  Some password systems prepend the kind of
 *                                  encryption to the crypted password ({SHA},
 *                                  etc). Defaults to false.
 *
 * @return  string  The encrypted password.
 *
 * @since   11.1
 */
public static function getCryptedPassword($plaintext, $salt = '', $encryption = 'md5-hex', $show_encrypt = false)
{
	// Get the salt to use.
	$salt = JUserHelper::getSalt($encryption, $salt, $plaintext);

	// Encrypt the password.
	switch ($encryption)
	{
		case 'plain':
			return $plaintext;

		case 'sha':
			$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext));
			return ($show_encrypt) ? '{SHA}' . $encrypted : $encrypted;

		case 'crypt':
		case 'crypt-des':
		case 'crypt-md5':
		case 'crypt-blowfish':
			return ($show_encrypt ? '{crypt}' : '') . crypt($plaintext, $salt);

		case 'md5-base64':
			$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext));
			return ($show_encrypt) ? '{MD5}' . $encrypted : $encrypted;

		case 'ssha':
			$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext . $salt) . $salt);
			return ($show_encrypt) ? '{SSHA}' . $encrypted : $encrypted;

		case 'smd5':
			$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext . $salt) . $salt);
			return ($show_encrypt) ? '{SMD5}' . $encrypted : $encrypted;

		case 'aprmd5':
			$length = strlen($plaintext);
			$context = $plaintext . '$apr1$' . $salt;
			$binary = JUserHelper::_bin(md5($plaintext . $salt . $plaintext));

			for ($i = $length; $i > 0; $i -= 16)
			{
				$context .= substr($binary, 0, ($i > 16 ? 16 : $i));
			}
			for ($i = $length; $i > 0; $i >>= 1)
			{
				$context .= ($i & 1) ? chr(0) : $plaintext[0];
			}

			$binary = JUserHelper::_bin(md5($context));

			for ($i = 0; $i < 1000; $i++)
			{
				$new = ($i & 1) ? $plaintext : substr($binary, 0, 16);
				if ($i % 3)
				{
					$new .= $salt;
				}
				if ($i % 7)
				{
					$new .= $plaintext;
				}
				$new .= ($i & 1) ? substr($binary, 0, 16) : $plaintext;
				$binary = JUserHelper::_bin(md5($new));
			}

			$p = array();
			for ($i = 0; $i < 5; $i++)
			{
				$k = $i + 6;
				$j = $i + 12;
				if ($j == 16)
				{
					$j = 5;
				}
				$p[] = JUserHelper::_toAPRMD5((ord($binary[$i]) << 16) | (ord($binary[$k]) << 8) | (ord($binary[$j])), 5);
			}

			return '$apr1$' . $salt . '$' . implode('', $p) . JUserHelper::_toAPRMD5(ord($binary[11]), 3);

		case 'md5-hex':
		default:
			$encrypted = ($salt) ? md5($plaintext . $salt) : md5($plaintext);
			return ($show_encrypt) ? '{MD5}' . $encrypted : $encrypted;
	}
}

/**
 * Returns a salt for the appropriate kind of password encryption.
 * Optionally takes a seed and a plaintext password, to extract the seed
 * of an existing password, or for encryption types that use the plaintext
 * in the generation of the salt.
 *
 * @param   string  $encryption  The kind of password encryption to use.
 *                               Defaults to md5-hex.
 * @param   string  $seed        The seed to get the salt from (probably a
 *                               previously generated password). Defaults to
 *                               generating a new seed.
 * @param   string  $plaintext   The plaintext password that we're generating
 *                               a salt for. Defaults to none.
 *
 * @return  string  The generated or extracted salt.
 *
 * @since   11.1
 */
public static function getSalt($encryption = 'md5-hex', $seed = '', $plaintext = '')
{
	// Encrypt the password.
	switch ($encryption)
	{
		case 'crypt':
		case 'crypt-des':
			if ($seed)
			{
				return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 2);
			}
			else
			{
				return substr(md5(mt_rand()), 0, 2);
			}
			break;

		case 'crypt-md5':
			if ($seed)
			{
				return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 12);
			}
			else
			{
				return '$1$' . substr(md5(mt_rand()), 0, 8) . '$';
			}
			break;

		case 'crypt-blowfish':
			if ($seed)
			{
				return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 16);
			}
			else
			{
				return '$2$' . substr(md5(mt_rand()), 0, 12) . '$';
			}
			break;

		case 'ssha':
			if ($seed)
			{
				return substr(preg_replace('|^{SSHA}|', '', $seed), -20);
			}
			else
			{
				return mhash_keygen_s2k(MHASH_SHA1, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
			}
			break;

		case 'smd5':
			if ($seed)
			{
				return substr(preg_replace('|^{SMD5}|', '', $seed), -16);
			}
			else
			{
				return mhash_keygen_s2k(MHASH_MD5, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
			}
			break;

		case 'aprmd5': /* 64 characters that are valid for APRMD5 passwords. */
			$APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

			if ($seed)
			{
				return substr(preg_replace('/^\$apr1\$(.{8}).*/', '\\1', $seed), 0, 8);
			}
			else
			{
				$salt = '';
				for ($i = 0; $i < 8; $i++)
				{
					$salt .= $APRMD5{rand(0, 63)};
				}
				return $salt;
			}
			break;

		default:
			$salt = '';
			if ($seed)
			{
				$salt = $seed;
			}
			return $salt;
			break;
	}
}

/**
 * Generate a random password
 *
 * @param   integer  $length  Length of the password to generate
 *
 * @return  string  Random Password
 *
 * @since   11.1
 */
public static function genRandomPassword($length = 8)
{
	$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	$base = strlen($salt);
	$makepass = '';

	/*
	 * Start with a cryptographic strength random string, then convert it to
	 * a string with the numeric base of the salt.
	 * Shift the base conversion on each character so the character
	 * distribution is even, and randomize the start shift so it's not
	 * predictable.
	 */
	$random = JCrypt::genRandomBytes($length + 1);
	$shift = ord($random[0]);
	for ($i = 1; $i <= $length; ++$i)
	{
		$makepass .= $salt[($shift + ord($random[$i])) % $base];
		$shift += ord($random[$i]);
	}

	return $makepass;
}

/**
 * Converts to allowed 64 characters for APRMD5 passwords.
 *
 * @param   string   $value  The value to convert.
 * @param   integer  $count  The number of characters to convert.
 *
 * @return  string  $value converted to the 64 MD5 characters.
 *
 * @since   11.1
 */
protected static function _toAPRMD5($value, $count)
{
	/* 64 characters that are valid for APRMD5 passwords. */
	$APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

	$aprmd5 = '';
	$count = abs($count);
	while (--$count)
	{
		$aprmd5 .= $APRMD5[$value & 0x3f];
		$value >>= 6;
	}
	return $aprmd5;
}

/**
 * Converts hexadecimal string to binary data.
 *
 * @param   string  $hex  Hex data.
 *
 * @return  string  Binary data.
 *
 * @since   11.1
 */
private static function _bin($hex)
{
	$bin = '';
	$length = strlen($hex);
	for ($i = 0; $i < $length; $i += 2)
	{
		$tmp = sscanf(substr($hex, $i, 2), '%x');
		$bin .= chr(array_shift($tmp));
	}
	return $bin;
}
}

 

estou com problema no md5+ salt

não estou a conseguir por a minha pass assim 4e9e4bcc5752d6f939aedb42408fd3aa:0vURRbyY8Ea0tlvnTFn7xcKpjTFyn0YT

ele fica me assim C5X4y+5rWepXyOk/Z9CsTQ==.

segue-se o código

a password tem que ser igual ao que tenho na minha base de dados

eu estou a juntar uma applicação em c# ao joomla 2.5

e não estou a conseguir

class Password

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace Client
{
   class Password
   {
           private string _password;
           private int _salt;

           public Password(string strPassword, int nSalt)
           {
               _password = strPassword;
               _salt = nSalt;
           }

           public static string CreateRandomPassword(int PasswordLength)
           {
               String _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789";
               Byte[] randomBytes = new Byte[PasswordLength];
               RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
               rng.GetBytes(randomBytes);
               char[] chars = new char[PasswordLength];
               int allowedCharCount = _allowedChars.Length;

               for (int i = 0; i < PasswordLength; i++)
               {
                   chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];
               }

               return new string(chars);
           }

           public static int CreateRandomSalt()
           {
               Byte[] _saltBytes = new Byte[4];
               RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
               rng.GetBytes(_saltBytes);

               return ((((int)_saltBytes[0]) << 24) + (((int)_saltBytes[1]) << 16) +
                   (((int)_saltBytes[2]) << 8) + ((int)_saltBytes[3]));
           }

           public string ComputeSaltedHash()
           {
               // Create Byte array of password string
               ASCIIEncoding encoder = new ASCIIEncoding();
               Byte[] _secretBytes = encoder.GetBytes(_password);

               // Create a new salt
               Byte[] _saltBytes = new Byte[4];
               _saltBytes[0] = (byte)(_salt >> 24);
               _saltBytes[1] = (byte)(_salt >> 16);
               _saltBytes[2] = (byte)(_salt >> 8);
               _saltBytes[3] = (byte)(_salt);

               // append the two arrays
               Byte[] toHash = new Byte[_secretBytes.Length + _saltBytes.Length];
               Array.Copy(_secretBytes, 0, toHash, 0, _secretBytes.Length);
               Array.Copy(_saltBytes, 0, toHash, _secretBytes.Length, _saltBytes.Length);

               MD5 sha1 = MD5.Create();
               Byte[] computedHash = sha1.ComputeHash(toHash);

               return encoder.GetString(computedHash);
           }
       }


   }

Logon.cs

using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Shared.User;
using Client;
using System.Security.Cryptography;
using System.Text;
namespace Client
{

   public partial class Logon : Form
   {

       //Logon Instance { get; set; }
       public Logon()
       {
           InitializeComponent();
       }
      /*     static 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 sBuilder = new StringBuilder();

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

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

       // Verify a hash against a string.
       static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
       {
           // Hash the input.
           string hashOfInput = GetMd5Hash(md5Hash, input);

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

           if (0 == comparer.Compare(hashOfInput, hash))
           {
               return true;
           }
           else
           {
               return false;
           }
       }

   */
       public class SimpleHash
       {
           /// <summary>
           /// Generates a hash for the given plain text value and returns a
           /// base64-encoded result. Before the hash is computed, a random salt
           /// is generated and appended to the plain text. This salt is stored at
           /// the end of the hash value, so it can be used later for hash
           /// verification.
           /// </summary>
           /// <param name="plainText">
           /// Plaintext value to be hashed. The function does not check whether
           /// this parameter is null.
           /// </param>
           /// <param name="hashAlgorithm">
           /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
           /// "SHA256", "SHA384", and "SHA512" (if any other value is specified
           /// MD5 hashing algorithm will be used). This value is case-insensitive.
           /// </param>
           /// <param name="saltBytes">
           /// Salt bytes. This parameter can be null, in which case a random salt
           /// value will be generated.
           /// </param>
           /// <returns>
           /// Hash value formatted as a base64-encoded string.
           /// </returns>
           public static string ComputeHash(string plainText,
                                            string hashAlgorithm,
                                            byte[] saltBytes)
           {
               // If salt is not specified, generate it on the fly.
               if (saltBytes == null)
               {
                   // Define min and max salt sizes.
                   int minSaltSize = 32;
                   int maxSaltSize = 32;

                   // Generate a random number for the size of the salt.
                   Random random = new Random();
                   int saltSize = random.Next(minSaltSize, maxSaltSize);

                   // Allocate a byte array, which will hold the salt.
                   saltBytes = new byte[saltSize];

                   // Initialize a random number generator.
                   RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

                   // Fill the salt with cryptographically strong byte values.
                   rng.GetNonZeroBytes(saltBytes);
               }

               // Convert plain text into a byte array.
               byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

               // Allocate array, which will hold plain text and salt.
               byte[] plainTextWithSaltBytes =
                       new byte[plainTextBytes.Length + saltBytes.Length];

               // Copy plain text bytes into resulting array.
               for (int i = 0; i < plainTextBytes.Length; i++)
                   plainTextWithSaltBytes[i] = plainTextBytes[i];

               // Append salt bytes to the resulting array.
               for (int i = 0; i < saltBytes.Length; i++)
                   plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];

               // Because we support multiple hashing algorithms, we must define
               // hash object as a common (abstract) base class. We will specify the
               // actual hashing algorithm class later during object creation.
               HashAlgorithm hash;

               // Make sure hashing algorithm name is specified.
               if (hashAlgorithm == null)
                   hashAlgorithm = "";

               // Initialize appropriate hashing algorithm class.
               switch (hashAlgorithm.ToUpper())
               {
                   case "SHA1":
                       hash = new SHA1Managed();
                       break;

                   case "SHA256":
                       hash = new SHA256Managed();
                       break;

                   case "SHA384":
                       hash = new SHA384Managed();
                       break;

                   case "SHA512":
                       hash = new SHA512Managed();
                       break;

                   default:
                       hash = new MD5CryptoServiceProvider();
                       break;
               }

               // Compute hash value of our plain text with appended salt.
               byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

               // Create array which will hold hash and original salt bytes.
               byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                                   saltBytes.Length];

               // Copy hash bytes into resulting array.
               for (int i = 0; i < hashBytes.Length; i++)
                   hashWithSaltBytes[i] = hashBytes[i];

               // Append salt bytes to the result.
               for (int i = 0; i < saltBytes.Length; i++)
                   hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];

               // Convert result into a base64-encoded string.
               string hashValue = Convert.ToBase64String(hashWithSaltBytes);

               // Return the result.
               return hashValue;
           }

           /// <summary>
           /// Compares a hash of the specified plain text value to a given hash
           /// value. Plain text is hashed with the same salt value as the original
           /// hash.
           /// </summary>
           /// <param name="plainText">
           /// Plain text to be verified against the specified hash. The function
           /// does not check whether this parameter is null.
           /// </param>
           /// <param name="hashAlgorithm">
           /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1", 
           /// "SHA256", "SHA384", and "SHA512" (if any other value is specified,
           /// MD5 hashing algorithm will be used). This value is case-insensitive.
           /// </param>
           /// <param name="hashValue">
           /// Base64-encoded hash value produced by ComputeHash function. This value
           /// includes the original salt appended to it.
           /// </param>
           /// <returns>
           /// If computed hash mathes the specified hash the function the return
           /// value is true; otherwise, the function returns false.
           /// </returns>
           public static bool VerifyHash(string plainText,
                                         string hashAlgorithm,
                                         string hashValue)
           {
               // Convert base64-encoded hash value into a byte array.
               byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);

               // We must know size of hash (without salt).
               int hashSizeInBits, hashSizeInBytes;

               // Make sure that hashing algorithm name is specified.
               if (hashAlgorithm == null)
                   hashAlgorithm = "";

               // Size of hash is based on the specified algorithm.
               switch (hashAlgorithm.ToUpper())
               {
                   case "SHA1":
                       hashSizeInBits = 160;
                       break;

                   case "SHA256":
                       hashSizeInBits = 256;
                       break;

                   case "SHA384":
                       hashSizeInBits = 384;
                       break;

                   case "SHA512":
                       hashSizeInBits = 512;
                       break;

                   default: // Must be MD5
                       hashSizeInBits = 128;
                       break;
               }

               // Convert size of hash from bits to bytes.
               hashSizeInBytes = hashSizeInBits / 8;

               // Make sure that the specified hash value is long enough.
               if (hashWithSaltBytes.Length < hashSizeInBytes)
                   return false;

               // Allocate array to hold original salt bytes retrieved from hash.
               byte[] saltBytes = new byte[hashWithSaltBytes.Length -
                                           hashSizeInBytes];

               // Copy salt from the end of the hash to the new array.
               for (int i = 0; i < saltBytes.Length; i++)
                   saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i];

               // Compute a new hash string.
               string expectedHashString =
                           ComputeHash(plainText, hashAlgorithm, saltBytes);

               // If the computed hash matches the specified hash,
               // the plain text value must be correct.
               return (hashValue == expectedHashString);
           }
       }


       private void LoginBtnClick(object sender, EventArgs e)
       {
           string password      = usernameTxt.Text.Trim();  // original password
    //   string wrongPassword = "password";    // wrong password

       string passwordHashMD5 = 
              SimpleHash.ComputeHash(password, "MD5", null);
       string passwordHashSha1 = 
              SimpleHash.ComputeHash(password, "SHA1", null);
       string passwordHashSha256 = 
              SimpleHash.ComputeHash(password, "SHA256", null);
       string passwordHashSha384 = 
              SimpleHash.ComputeHash(password, "SHA384", null);
       string passwordHashSha512 = 
              SimpleHash.ComputeHash(password, "SHA512", null);

            MySqlConnection con = new MySqlConnection("host=localhost;user=root;database=Accounts");
            try
            { /*String salt= textBox1.Text.Trim();
            //String value = textBox1.Text.Trim();

             /*   using (MD5 md5Hash = MD5.Create())
                {
                    string hash = GetMd5Hash(md5Hash, textBox1.Text.Trim());

                   Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + hash + ".");
                    //Console.WriteLine("Verifying the hash...");

                   // if (VerifyMd5Hash(md5Hash, textBox1.Text.Trim(), hash))
                  //  {
                  //      Console.WriteLine("The hashes are the same.");
                  //  }
                  //  else
                  //  {
                   //     Console.WriteLine("The hashes are not same.");
                  //  }
                */
                password = Password.CreateRandomPassword(8);

                // Debug output
                Console.WriteLine(password);

                // Generate a new random salt
                int mySalt = Password.CreateRandomSalt();

                // Initialize the Password class with the password and salt
                Password pwd = new Password(password, mySalt);

                // Compute the salted hash
                // NOTE: you store the salt and the salted hash in the datbase
                string strHashedPassword = pwd.ComputeSaltedHash();

                // Debug output
                Console.WriteLine(strHashedPassword);
                byte[] data = System.Text.Encoding.ASCII.GetBytes(password + strHashedPassword);
                data = System.Security.Cryptography.MD5.Create().ComputeHash(data);
                String ola = Convert.ToBase64String(data);
                Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + ola + ".");
                    MySqlCommand cmd = new MySqlCommand("SELECT tipo FROM user WHERE username  = '" + usernameTxt.Text.Replace("'", "") + "' AND password = '" + ola+ "' ");
                    cmd.Connection = con;
                    con.Open();
                    object Tipo = cmd.ExecuteScalar();
                    if (Tipo != null && Tipo != DBNull.Value)
                    {

                        switch (System.Convert.ToInt32(Tipo))
                        {
                            case 1:
                                 // Form1 ola1 = new Form1();
                               //  ola1.Show();


                               //  Hide();
                               new Client(usernameTxt.Text.Trim(), this).Show();
                                Hide();
                                break;
                            case 2:
                                MessageBox.Show("GAME MASTER");
                                break;
                            case 3:
                                MessageBox.Show("Moderador");
                                break;
                            case 4:
                                MessageBox.Show("VIP");
                                break;
                            case 5:
                                MessageBox.Show("Membro");
                                break;
                            case 6:
                                MessageBox.Show("Registo nao foi Activado");
                                break;
                            case 7:
                                MessageBox.Show("O Utilizador foi banido\n Contacte a Equipa atravez do suporte para saber a razão pelo qual foi banido(a)");
                                break;
                        }




                    }
                    else
                    {
                        MessageBox.Show("Usuario ou Senha incorretos");
                    }
                }
          //  }
            catch (MySqlException msqle)
            {
                MessageBox.Show("Erro de acesso ao MySQL : " +
           msqle.Message, "Erro");
            }
           }


       private void UsernameTxtKeyPress(object sender, KeyPressEventArgs e)
       {
           if (e.KeyChar == (char)Keys.Enter)
               loginBtn.PerformClick(); //Perform Login button click if enter is pressed
       }

       internal static void Exit()
       {
           Application.Exit();
       }

       private void button1_Click(object sender, EventArgs e)
       {
           Application.Exit();
       }
   }
}

alguem me pode dizer onde esta o problema

 

alguem me pode ajudar a resolver o problema

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.