0

I am able to successfully encrypt password field in my form field using jquery cryptojs library. I am using AES algorithm for that library. However, I am unable to decrypt it in php. I am attempting to use mcrypt_decrypt. I have looked for solutions online on various forums but haven't been able to figure whats going wrong.

Here is my html form:-

  <form id="userDetailsForm" action="/scripts/usernameTest.php" method="post">
<div class="clear"></div> <div class="clear"></div>
<p>Add User</p>
<div class="clear"></div>
<label for="usr">Username</label>
<input type="text" name="usr" id="usr">
<label for="pwd">Password</label>
<input type="password" name="pwd" id="pwd">
<button id="create" class="create" type="submit">Create</button>
</form>

Here is my jquery part:-

$("#create").click(function(){

    var passwordForNewUser=CryptoJS.AES.encrypt($("#pwd").val(),key).toString();
   // var decryptedPassword=CryptoJS.AES.decrypt(passwordForNewUser,key).toString(CryptoJS.enc.Utf8);
   // console.log("decrypted password: "+decryptedPassword);
    console.log("create clicked");
    formdata = {
        usr: $("#usr").val(),
        pwd: passwordForNewUser,
    };

    var userNamePresentInTable=$("#usr").val();
    var password=CryptoJS.AES.encrypt($("#pwd").val(),key).toString();
    if($("td:contains('" + formdata.usr + "')").text() === formdata.usr){
        $("#userErrorDiv").html("User already exists. Please enter another one").css("color","red");
        duplicateUser=true;
    }else{
        duplicateUser=false;

        /*before adding to table save it in localStorage*/
       /* myLocalStorage.setItem(formdata.usr,formdata.pwd);*/

        $("#userErrorDiv").html("");
        var tr=$('<tr></tr>');
        var enteredVal=$("#usr").val();

        var td_username=$('<td></td>',{
            text:  $("#usr").val()
        }).addClass("editableFields").appendTo(tr);

        var td_level=$('<td></td>', {
            text: "User"
        }).appendTo(tr);

        var td_buttons=$('<td></td>',{
            html: '<button class="edit">Edit</button> <button class="del">Delete</button> <button class="apply">Apply</button>'
        }).appendTo(tr);

        $(tr).find("button").button();
        $(".userTable").append(tr);

        //$("#userDetailsForm").submit();
    }
});

$('#userDetailsForm').on("submit",function(){

    var currentObj=$(this), url=currentObj.attr('action'),type=currentObj.attr('method');
    var data={};

    currentObj.find('[name]').each(function(index,value){
       var currentObj=$(this), name=currentObj.attr('name'), value=currentObj.val();
        data[name]=value;
        console.log(index+" "+data[name]);
    });

    $.ajax({
        url:url,
        type:type,
        data:data,
        success: function(response){
            console.log(response);
        }
    });
    return false;
});

And this is the php side:-

<?php
if(isset($_POST['usr'],$_POST['pwd'] )) {
    $username=$_POST['usr'];
    $password=$_POST['pwd'];
    $key="encyrptedPasswor";
    $decrypted_password=mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$key,$password,MCRYPT_MODE_ECB,'');
     echo nl2br("Username recieved:".$_POST["usr"]."<br/>"."Encrypted password recieved: ".$password."<br/>"."Decypted password recieved: ".$decrypted_password);
      }
    ?>

The issue is that even after im trying to echo decrypted password I still get the encrypted one as a response.

Rajat Bansal
  • 183
  • 1
  • 14
  • Whenever I'm doing something like this I always try to verify that the output of my encryption section is actually correct. I try to use a website like http://aes.online-domain-tools.com/ to check to see if it decrypt properly. Just pass a string into your jquery encrypter, and see if it decrypts from the website. Should help you figure out where the problem is. – Jazzepi Oct 26 '15 at 21:05
  • i have edited the post. var password basically is having the encryption part – Rajat Bansal Oct 26 '15 at 21:08
  • The question is what you want to do with this. If you want to use encryption or hashing on the client, then you still need to use SSL/TLS, because a man-in-the-middle attack might change the JavaScript that is sent from the server to the client and completely remove your encryption/hashing. See also [Javascript Cryptography Considered Harmful](https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/) – Artjom B. Oct 26 '15 at 21:18
  • @ArtjomB. then what could be a good way to transmit passwords. Basically, while doing post and when using developer tools, i dont want to see the password in clear text..thats why i was looking for a way to encrypt it before sending and then decrypt it on server side – Rajat Bansal Oct 26 '15 at 21:27
  • @RajatBansal It depends who you're trying to protect this from. If you want simple obfuscation, then this approach is ok. If you want it secure and a potential attacker cannot change the JavaScript code in transit, then embedding an RSA public key in the client code is the best way. You can then encrypt the password with RSA and sent it to the server which can decrypt it with its private key. If you think that an attack might change the JavaScript code in transit, then the *only* secure way to protect against this is to use TLS with a valid certificate (chain). – Artjom B. Oct 26 '15 at 21:36

1 Answers1

-1

I know this isn't an answer, and I know I'm writing it as an answer but I wanted to make this as clear as possible!

DO NOT ENCRYPT PASSWORDS.... HASH THEM and then compare the hashes when needed!

Encrypting the password means that the data (or password in this case) is still contained within, which means someone can extract it, given knowledge, time and effort.

And like Hendrik said, use BCrypt not MD5 for reasons stated...

An0nC0d3r
  • 1,275
  • 13
  • 33
  • So you mean to say that if i use an algorithm like MD5 and store it on server side as hashed? And then if that user is entering a password i just hash it again from client side and compare it with the hash already stored? – Rajat Bansal Oct 26 '15 at 21:13
  • Hashing on the client doesn't add any security, because the hash becomes the new password. – Artjom B. Oct 26 '15 at 21:14
  • Alright thank you for your incite – Rajat Bansal Oct 26 '15 at 21:15
  • 1
    Dont use MD5, because it is compromised and way too fast, which brings up rainbow tables. Use something like __BCrypt__ or similar. SHA256 is fast too. – Hendrik Oct 26 '15 at 21:16
  • @ArtjomB.: i cant believe that I didnt stumble upon that question. Maybe something wrong with the way I was querying google. Thanks for pointing that out. – Rajat Bansal Oct 26 '15 at 21:19
  • 1
    @ArtjomB In my opinion, user password should be hashed on client side, because it adds a bit of trust if the password is not sent over the net. Sure, this does not add any security to the application, but to the users private data, which is very important, how I think. – Hendrik Oct 26 '15 at 21:38
  • Random votedown haha... someone doesn't know the difference between encryption and hashing hahaha – An0nC0d3r Oct 26 '15 at 21:56
  • @Hendrik Yes, you're right. It would protect against use of that password on other sites. For this to actually work, the hashing needs to salted and iterated many times in order to prevent Rainbow Tables and fast trial of common passwords. I'm talking about PBKDF2 with 60000 iterations. Good thing that CryptoJS provides this. – Artjom B. Oct 26 '15 at 22:17