Pagina 1 din 1

Criptare si decriptare parole cu mcrypt nu functioneaza

Scris: Sâm Oct 27, 2018
de Jimmi
Salut, intampin cateva probleme cand incerc sa criptez parolele utilizatorilor.Problema e ca nu adauga parola criptata in Mysql dar o citeste daca o scriu eu normal.Insa, daca incerc sa ma loghez dupa ce mi-am facut contul nu se intampla nimic.Imi da eroare ca parola e gresita.Problema e ca in mysql dupa ce ma inregistrez nu se adauga si parola ci ramane spatiul alb.Cand adaug eu parola fara sa fie criptata o citeste la login.Nu am facut eu sistemul prin care se criptau parolele dar sper sa il pot reface eu ca incepator si eventual sa il imbunatatesc
Functiile adaugate pentru parole :

Cod: Selectaţi tot

public static function fnEncrypt($sValue, $sSecretKey)
 {
  return rtrim(
   base64_encode(
    mcrypt_encrypt(
     MCRYPT_RIJNDAEL_256,
     $sSecretKey, $sValue, 
     MCRYPT_MODE_ECB, 
     mcrypt_create_iv(
      mcrypt_get_iv_size(
       MCRYPT_RIJNDAEL_256, 
       MCRYPT_MODE_ECB
      ), 
      MCRYPT_RAND)
     )
    ), "\0"
   );
 }
 
 public static function fnDecrypt($sValue, $sSecretKey)
 {
  return rtrim(
   mcrypt_decrypt(
    MCRYPT_RIJNDAEL_256, 
    $sSecretKey, 
    base64_decode($sValue), 
    MCRYPT_MODE_ECB,
    mcrypt_create_iv(
     mcrypt_get_iv_size(
      MCRYPT_RIJNDAEL_256,
      MCRYPT_MODE_ECB
     ), 
     MCRYPT_RAND
    )
   ), "\0"
  );
}
La register am urmatoare interogare:

Cod: Selectaţi tot

<?php
if(isset($_POST['submit_reg']))
{
 $q = Config::$g_con->prepare('SELECT * FROM `users` WHERE `username` = ? OR `email` = ?');
 $q->execute(array($_POST['username'],$_POST['email']));
 if(!$q->rowCount())
 {
  if($_POST['password'] == $_POST['pass_conf'])
  {
   $Pass = "Passwort";  
   $crypted = Config::fnEncrypt($_POST['password'], $Pass);
   $q = Config::$g_con->prepare('INSERT INTO `users` (`username`,`email`,`password`,`first_name`,`last_name`) VALUES (?,?,?,?,?)');
   $q->execute(array($_POST['username'],$_POST['email'],$crypted,$_POST['first_name'],$_POST['last_name']));
   echo '<strong><font color="green">You have registered with successful! Now you can login.</font></strong><br><br>';
  } else echo '<strong><font color="red">Passwords aren\'t the same.</font></strong><br><br>';
 } else echo '<strong><font color="red">This username or email already exists! Please choose another.</font></strong><br><br>';
}
?>
Iar la login:

Cod: Selectaţi tot

<?php 
if(isset($_POST['submit_login']))
{
 $Pass = "Passwort";  
 $decrypt = Config::fnEncrypt($_POST['password'], $Pass);
 
 $q = Config::$g_con->prepare('SELECT * FROM `users` WHERE `username` = ? AND `password` = ?');
 $q->execute(array($_POST['username'],$decrypt));
 if($q->rowCount())
 {
  while($row = $q->fetch(PDO::FETCH_OBJ)) 
  {
   $_SESSION['user_web'] = $row->ID;
   header('location: '.Config::$_PAGE_URL.'index.php' );
  }
 } else {
  echo '<strong><font color="red">Incorrect username or password!</font></strong><br><br>';
 }
}
?>
Baza de date am facut-o eu pentru ca vechea baza de date a fost pierduta:

Cod: Selectaţi tot

-- phpMyAdmin SQL Dump
-- version 4.7.7
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Oct 27, 2018 at 12:58 PM
-- Server version: 5.6.41
-- PHP Version: 5.6.30

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `website_website`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `ID` int(11) NOT NULL,
  `username` varchar(20) NOT NULL,
  `password` varchar(56) NOT NULL,
  `email` varchar(30) NOT NULL,
  `first_name` varchar(11) NOT NULL,
  `last_name` varchar(11) NOT NULL,
  `validation` int(12) NOT NULL,
  `staff` int(5) NOT NULL,
  `currency` int(10) NOT NULL,
  `Newsletter` int(2) NOT NULL,
  `Skype` varchar(25) NOT NULL,
  `Phone` int(25) NOT NULL,
  `Birthday` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
  `Timezone` time(6) NOT NULL,
  `Company Name` varchar(25) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`ID`, `username`, `password`, `email`, `first_name`, `last_name`, `validation`, `staff`, `currency`, `Newsletter`, `Skype`, `Phone`, `Birthday`, `Timezone`, `Company Name`) VALUES
(2, 'Administratie', '123456789', 'teste_administratie@yahoo.com', 'T', 's', 0, 1, 0, 1, 'support_adn', 0, '2018-10-27 09:57:55.376499', '00:00:00.000000', '');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`ID`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Ca si cunostinte sunt incepator dar sper sa inteleg din explicatii.

Criptare si decriptare parole cu mcrypt nu functioneaza

Scris: Sâm Oct 27, 2018
de MarPlo
Salut,
Acele functii de criptare /decriptare folosesec modulul php_mcrypt.
Php trebuie sa aibe acel modul instalat.
Daca e instalat, verifica in codul tau ce valoare contine $crypted:

Cod: Selectaţi tot

var_dump($crypted);[
Daca valoarea e un sir (string), problema poate fi la functiile de adaugare date in mysql.

- Functia mcrypt e anulata incepand cu PHP 7.1.0, ca alternativa poti folosi: openssl_encrypt / openssl_decrypt.

Criptare si decriptare parole cu mcrypt nu functioneaza

Scris: Sâm Oct 27, 2018
de Jimmi
Banuiesc ca era activat din moment ce criptarea parolelor a functionat in trecut.
Am incercat totusi sa schimb functia mcrypt cu openssl_encrypt / openssl_decrypt daca pare mai promitatoare .Problema e ca in baza de date imi adauga textul Passwort nu parola.Oricum nu poate sa decripteze parola din ce am vazut.Fie ca bag parola setata de mine fie ca bag Passwort imi da ca e gresita parola
Poza din baza de date: i.imgur.com/dfASStg.png

Am modificat fiecare chestie cu cele pentru openssl_encrypt /decrypt dar nu pare sa functioneze:

Cod: Selectaţi tot

function encryptFile($source, $key, $dest)
{
    $key = substr(sha1($key, true), 0, 16);
    $iv = openssl_random_pseudo_bytes(16);

    $error = false;
    if ($fpOut = fopen($dest, 'w')) {
        fwrite($fpOut, $iv);
        if ($fpIn = fopen($source, 'rb')) {
            while (!feof($fpIn)) {
                $plaintext = fread($fpIn, 16 * FILE_ENCRYPTION_BLOCKS);
                $ciphertext = openssl_encrypt($plaintext, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
                $iv = substr($ciphertext, 0, 16);
                fwrite($fpOut, $ciphertext);
            }
            fclose($fpIn);
        } else {
            $error = true;
        }
        fclose($fpOut);
    } else {
        $error = true;
    }

    return $error ? false : $dest;
}
function decryptFile($source, $key, $dest)
{
    $key = substr(sha1($key, true), 0, 16);

    $error = false;
    if ($fpOut = fopen($dest, 'w')) {
        if ($fpIn = fopen($source, 'rb')) {
            $iv = fread($fpIn, 16);
            while (!feof($fpIn)) {
                $ciphertext = fread($fpIn, 16 * (FILE_ENCRYPTION_BLOCKS + 1));
                $plaintext = openssl_decrypt($ciphertext, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
                $iv = substr($ciphertext, 0, 16);
                fwrite($fpOut, $plaintext);
            }
            fclose($fpIn);
        } else {
            $error = true;
        }
        fclose($fpOut);
    } else {
        $error = true;
    }

    return $error ? false : $dest;
}
Si:register.php

Cod: Selectaţi tot

		<?php
		if(isset($_POST['submit_reg']))
		{
			$q = Config::$g_con->prepare('SELECT * FROM `users` WHERE `username` = ? OR `email` = ?');
			$q->execute(array($_POST['username'],$_POST['email']));
			if(!$q->rowCount())
			{
				if($_POST['password'] == $_POST['pass_conf'])
				{
					$plaintext = "Passwort";  
					$crypted = Config::encryptFile($_POST['password'], $plaintext);
					$q = Config::$g_con->prepare('INSERT INTO `users` (`username`,`email`,`password`,`first_name`,`last_name`) VALUES (?,?,?,?,?)');
					$q->execute(array($_POST['username'],$_POST['email'],$plaintext,$_POST['first_name'],$_POST['last_name']));
					echo '<strong><font color="green">You have registered with successful! Now you can login.</font></strong><br><br>';
				} else echo '<strong><font color="red">Passwords aren\'t the same.</font></strong><br><br>';
			} else echo '<strong><font color="red">This username or email already exists! Please choose another.</font></strong><br><br>';
		}
		?>
login.php

Cod: Selectaţi tot

		<?php 
		if(isset($_POST['submit_login']))
		{
			$plaintext = "Passwort";  
			$decrypt = Config::encryptFile($_POST['password'], $plaintext);
			
			$q = Config::$g_con->prepare('SELECT * FROM `users` WHERE `username` = ? AND `password` = ?');
			$q->execute(array($_POST['username'],$decrypt));
			if($q->rowCount())
			{
				while($row = $q->fetch(PDO::FETCH_OBJ)) 
				{
					$_SESSION['user_web'] = $row->ID;
					header('location: '.Config::$_PAGE_URL.'index.php' );
				}
			} else {
				echo '<strong><font color="red">Incorrect username or password!</font></strong><br><br>';
			}
		}
		?>

Criptare si decriptare parole cu mcrypt nu functioneaza

Scris: Dum Oct 28, 2018
de MarPlo
Probabil ca nu ai inteles cum se folosete openssl_encrypt /openssl_decrypt si ai copiat exemplu din documentatie, care nu e pentru ce iti trebuie.
Uite un exemplu mai simplu, daca-l studiezi si intelegi il poti aplica in scriptul tau:

Cod: Selectaţi tot

$password = 'user_pass'; //password added by user $_POST['password']
$key_enc = '1234'; //key for encrypt
$met_enc = 'aes128'; //method to encrypt: aes192, aes256, blowfish, cast-cbc
$iv = '16_characters_ok'; //a random string with 16 characters

//encrypts the password
$pass_enc = openssl_encrypt($password, $met_enc, $key_enc, 0, $iv);
echo $pass_enc;  // "//LhXo5JqiFFYdQUHwtU8A=="

//decrypts the encrypted password, it uses the same arguments: $met_enc, $key_enc, $opt=0, $iv
$pass_enc ='//LhXo5JqiFFYdQUHwtU8A==';  //the encrypted password
$pass = openssl_decrypt($pass_enc, $met_enc, $key_enc, 0, $iv);
echo '<br>'.$pass;  // "user_pass"

Criptare si decriptare parole cu mcrypt nu functioneaza

Scris: Dum Oct 28, 2018
de Jimmi
Pai si in cazul asta parola pe care o adauga dupa in baza de date este parola adaugata de mine fara sa treaca prin procesul de criptare

Cod: Selectaţi tot

		<?php
		if(isset($_POST['submit_reg']))
		{
			$q = Config::$g_con->prepare('SELECT * FROM `users` WHERE `username` = ? OR `email` = ?');
			$q->execute(array($_POST['username'],$_POST['email']));
			if(!$q->rowCount())
			{
				if($_POST['password'] == $_POST['pass_conf'])
				{
					$password = 'password'; //password added by user $_POST['password']
					$key_enc = '1234'; //key for encrypt
					$met_enc = 'aes128'; //method to encrypt: aes192, aes256, blowfish, cast-cbc
					$iv = '16_characters_ok'; //a random string with 16 characters
					$pass_enc = openssl_encrypt($password, $met_enc, $key_enc, 0, $iv);
					$q = Config::$g_con->prepare('INSERT INTO `users` (`username`,`email`,`password`,`first_name`,`last_name`) VALUES (?,?,?,?,?)');
					$q->execute(array($_POST['username'],$_POST['email'],$_POST['password'],$_POST['first_name'],$_POST['last_name']));
					echo '<strong><font color="green">You have registered with successful! Now you can login.</font></strong><br><br>';
				} else echo '<strong><font color="red">Passwords aren\'t the same.</font></strong><br><br>';
			} else echo '<strong><font color="red">This username or email already exists! Please choose another.</font></strong><br><br>';
		}
		?>

Criptare si decriptare parole cu mcrypt nu functioneaza

Scris: Dum Oct 28, 2018
de MarPlo
Encriptezi in $pass_enc valoarea de la $_POST['password'], apoi adaugi $pass_enc in mysql.

Cod: Selectaţi tot

$password = $_POST['password']; //password added by user $_POST['password']
$key_enc = '1234'; //key for encrypt
$met_enc = 'aes128'; //method to encrypt: aes192, aes256, blowfish, cast-cbc
$iv = '16_characters_ok'; //a random string with 16 characters
$pass_enc = openssl_encrypt($password, $met_enc, $key_enc, 0, $iv);
$q = Config::$g_con->prepare('INSERT INTO `users` (`username`,`email`,`password`,`first_name`,`last_name`) VALUES (?,?,?,?,?)');
$q->execute(array($_POST['username'],$_POST['email'],$pass_enc,$_POST['first_name'],$_POST['last_name']));