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;
}

2 Answers2

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.

Andrey
  • 2,236
  • 17
  • 14
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!

domen
  • 1,040
  • 10
  • 21