- #1
chaoseverlasting
- 1,050
- 3
What exactly are hash functions and how do you use them to create a random string? What other ways are there to create random strings.
#include <ctime> // For time()
#include <cstdlib> // For srand() and rand()
srand(time(0));
chaoseverlasting said:How would you get the system time in c++ and use it to create a random string?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int
main(int argc, char *argv[])
{
if(argc < 2){
printf("USAGE: %s [Length of string]\n", argv[0]);
return 0;
}
int length = atoi(argv[1]);
char *randstr = malloc(length + 1);
randstr[length] = '\0';
time_t ltime = time(NULL);
srand(ltime);
int i;
for(i = 0; i < length; i++)
randstr[i] = (rand() % 26) + 65;
printf("%s\n", randstr);
return 0;
}
$ ./randstr
USAGE: ./randstr [Length of string]
$ ./randstr 20
MTZEKHHTQJGPDNHBNSTN
$ ./randstr 20
IEMBTDVFDEDMFWXEYESX
$ ./randstr 20
EMCYCCJOTCAJHCNHMQOH
$
A hash function is a mathematical algorithm that takes in an input of any size and produces an output of fixed size. It is designed to be a one-way function, meaning it is easy to compute the output from the input, but difficult to determine the input from the output. This makes it useful for creating random strings as the output appears to be random and is difficult to predict.
Hash functions are used in the creation of random strings by taking in a specific input (such as a password) and generating a unique output (hash). This hash can then be used as a random string as it is difficult to predict and cannot be easily reversed to determine the input. This makes it useful for generating secure passwords and other random strings.
Yes, it is possible for a hash function to generate the same output for two different inputs. This is known as a hash collision and can occur due to the fixed size of the output. However, a good hash function should have a low probability of producing a collision, making it a reliable method for creating random strings.
Yes, there are other methods for creating random strings, such as using random number generators or cryptographic algorithms. However, hash functions are a popular choice as they are efficient, easy to implement, and have a low probability of collisions.
One limitation of using hash functions for creating random strings is the fixed size of the output. This means that the generated strings may not always be of the desired length. Additionally, if the input is known or can be easily guessed, it may be possible to determine the output. Therefore, it is important to use a strong and secure hash function for creating random strings.