1

I'm studying basic security for asp.net and php, I was already able to implement the application on asp.net now what I want to do is come up with the same thing using php

Here is the code that I'm using for my asp.net application that I want to convert to php if it's possible:

public static byte[] GenerateSalt()
    {
        const int MinSaltSize = 4;
        const int MaxSaltSize = 8;

        // Generate a random number to determine the salt size.
        Random random = new Random();
        int saltSize = random.Next(MinSaltSize, MaxSaltSize);

        // Allocate a byte array, to hold the salt.
        byte[] saltBytes = new byte[saltSize];

        // Initialize the cryptographically secure random number generator.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

        // Fill the salt with cryptographically strong byte values.
        rng.GetNonZeroBytes(saltBytes);

        return saltBytes;
    }

I would also like to know what function to use for rng.GetNonZeroBytes() in php

Then I would use base64_encode/base64_decode for the data. Sir/Ma'am your answers would be of great help. Thank you++ :D

Randel Ramirez
  • 3,671
  • 20
  • 49
  • 63

2 Answers2

1

mcrypt_create_iv(size, MCRYPT_DEV_URANDOM) should be OK, despite the weird name. It's pretty much equivalent to rng.GetBytes.

Using DEV_URANDOM is essential, DEV_RANDOM is very slow for a negligible increase in security, and RAND is insecure.

Not sure why you'd want non-zero bytes. After Base64 encoding the zero-bytes will be normal printable characters.

I recommend using something like base64_encode(mcrypt_create_iv(9, MCRYPT_DEV_URANDOM))

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • Thank you for the immediate reply I would just like to know what is the meaning of 9 in the parameters. Thank you++ :D – Randel Ramirez Nov 03 '12 at 11:12
  • 1
    The size of the salt in bytes. The standard recommendation is to use at least 64 bit salts. 9 meets that recommendation, and since it's a multiple of three the Base64 encoding doesn't add any useless padding. – CodesInChaos Nov 03 '12 at 11:14
0

mcrypt_create_iv is depreciated and removed after PHP 7.2.0 Now that you can use:

echo base64_encode(random_bytes(9));

Hakan
  • 240
  • 3
  • 4