Search code examples
phpcryptographyrngcryptoserviceprovider

In PHP what is the equivalent of C#'s RNGCryptoServiceProvider?


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


Solution

  • 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))