0

I have recently created a code for hashing password. Can you please give your advice over the security of my code? The function takes a password, then converts it to a number.

#include <string>
#include <cmath>

int mod(int x, int y) {
   return x - floor((double) x/y) * y;
}

int crypt(string str) {
   int z = 0;
   for(int i = 0; i < str.size(); i++)
      z += mod( ( str[i] * -(str[i]) ), ((i*29) + 2999) );
   return z;
}

int password = crypt("Password1");

bool auth(string pass, int x) {
   if (crypt(pass) == x) return true;
   else return false;
}
3

It is not. There are bunch of problems here:

  • You has function produces 32-bit value, which is nowhere near sufficient for password hashing. For such short hashes it's feasible (and easy) to simply find colliding password (i.e. password that's different from the original but still hashes to the same value);
  • Function looks simple enough to be "reversible" in the sense that for given hash value it might be easy to compute matching password (again, this will be not the original password, but a colliding one);
  • Function is fast and doesn't require much memory, which is considered a disadvantage for password hashing, as it allows use of GPUs/ASICs.

It's almost never a good idea to invent your own crypto, including password hashes. There are various well-studied alternatives that are considered secure so you should probably use them (examples: PBKDF2, script, bcrypt). If those functions don't work for you for any reason please specify why and what other constraints you may have. This information is important as it gives context for your question which is currently missing.

  • thanks! I was just fiddling, I will not use this. I normally use BCrypt – Ruhan Habib Sep 17 '14 at 12:09
3

As @Andrey said, problems, problems, problems.

And here's a list of few collisions to Password1. I can produce tens in a second with a simple program: HAPPOAAA AHPPOAAA HAPOPAAA AHPOPAAA HAOPPAAA AHOPPAAA ECPPPAAA CEPPPAAA NNFEOCAA NNEFOCAA EAPPPCAA AEPPPCAA NNFCOEAA NNCFOEAA CAPPPEAA ACPPPEAA NNCEOFAA ONOKOHAA NOOKOHAA AAPPOHAA AAPOPHAA AAOPPHAA ONOHOKAA NOOHOKAA NDPOONAA NDOPONAA NDOOPNAA HPAOAPAA APHOAPAA HOAPAPAA EPCPAPAA CPEPAPAA AOHPAPAA LPPPBPAA EPAPCPAA APEPCPAA ONNODPAA NONODPAA CPAPEPAA APCPEPAA APAOHPAA AOAPHPAA BPPPLPAA ONDONPAA NODONPAA PHAAOPAA PAHAOPAA PAAHOPAA FDBOOPAA DFBOOPAA FBDOOPAA BFDOOPAA DBFOOPAA BDFOOPAA LEPOOPAA ELPOOPAA LEOPOPAA

As said: Don't roll your own crypto!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.