javascriptidentifygenerate

How do I generate a unique code based on the content?


Picture that you're typing in a input. For each character you add (including special characters, like @ . # ¤ % & ~ and so on), a unique code will generate based on the content. Not a hash! This unique code will only be 20 characters long.

Example

Why I want this

I am working on a project where the visitors can login to their own accounts (if they have one). As soon as they type in their email address and password, a unique code will generate based on the string (in a hidden input), so the website can identify the user and get the right data from the database.

Why do I want it?

I encrypt everything in the database with 256-bit AES and each user have their own encryption key. To identify the entered email address and password (which is encrypted with the websites encryption key until they login for the first time), this unique code (based on the string) will identify the login. To do the identification of the login with the websites encryption keys is therefore impossible. Hence my question.

This can maybe be a security risk since the unique code will be stored in the databased hashed in MD5 or Whirlpool, but I have no idea of how I can identify the login in another way. If you know a better way, please tell me.

So, how do I accomplish this? Is it even possible to do?

I know how to generate a unique code which is not based on the content (for an example, generating passwords), but I don't know how to generate a code that are unique based on the content.


Solution

  • I don't know the purpose, but replying directly to your question on how to generate a unique code which is based on the content, you can have something like this

    function symmetricEncode(content){
      var output = [];
      for (var i=0; i<content.length; i++){    
        output.push(String.fromCharCode(~ content[i].charCodeAt()));
      }
      return output.join("");
    }
    
    var string = "Hey you there";
    var code = symmetricEncode(string);
    
    console.log("string to code: ", string);
    console.log("code: ", code);
    console.log(typeof code);
    console.log("decoded code: ", symmetricEncode(code));

    This code is not merely a hash, because you can decode it, meaning it is unique, that is, for every input, you get an unique output

    Other types of hashes (for example multiplying all the characters) do not fulfil these criteria, because for two different inputs you may get the same output (very unlikely though possible), not being then purely reversible. The ~ makes reference to the bitwise not operator.