Dec 16, 2013 In order to generate random character strings in Excel, you need to be able to generate random numbers, upper and lowercase letters, and special symbols. Excel has this functionality built in to help generate random character strings. Generate Random Number String. To generate a random number string in Excel, simply use a formula like this. Store all the possible letters into a string. Generate random index from 0 to string length-1. Print the letter at that index. Perform this step n times (where n is the length of string required).
-->The Get-Random
cmdlet gets a randomly selected number. If you submit a collection of objects toGet-Random
, it gets one or more randomly selected objects from the collection.
Without parameters or input, a Get-Random
command returns a randomly selected 32-bit unsignedinteger between 0 (zero) and Int32.MaxValue (0x7FFFFFFF
, 2,147,483,647
).
You can use the parameters of Get-Random
to specify a seed number, minimum and maximum values, andthe number of objects returned from a submitted collection.
Example 1: Get a random integer
This command gets a random integer between 0 (zero) and Int32.MaxValue.
Example 2: Get a random integer between 0 and 99
Example 3: Get a random integer between -100 and 99
Example 4: Get a random floating-point number
This command gets a random floating-point number greater than or equal to 10.7 and less than 20.92.
Example 5: Get a random integer from an array
This command gets a randomly selected number from the specified array.
Example 6: Get several random integers from an array
This command gets three randomly selected numbers in random order from an array.
Example 7: Randomize an entire collection
This command returns the entire collection in random order.
The value of the Count parameter is the MaxValue static property of integers.
To return an entire collection in random order, enter any number that is greater than or equal tothe number of objects in the collection.
Example 8: Get a random non-numeric value
This command returns a random value from a non-numeric collection.
Example 9: Use the SetSeed parameter
This example shows the effect of using the SetSeed parameter.
Because SetSeed produces non-random behavior, it's typically used only to reproduce results,such as when debugging or analyzing a script.
Example 10: Get random files
These commands get a randomly selected sample of 50 files from the C:
drive of the local computer.
Example 11: Roll fair dice
This example rolls a fair die 1200 times and counts the outcomes. The first command, For-EachObject
repeats the call to Get-Random
from the piped in numbers (1-6). The results are grouped by theirvalue with Group-Object
and formatted as a table with Select-Object
.
Example 12: Use the Count parameter
PuTTYgen is an key generator tool for creating SSH keys for PuTTY. It is analogous to the ssh-keygen tool used in some other SSH implementations. The basic function is to create public and private key pairs. PuTTY stores keys in its own format in.ppk files. However, the tool can also convert keys to and from other formats. Run the puttygen.exe application by double-clicking the file you downloaded (it does not need to be installed) and select 'Import Key' from the 'Conversions' menu as shown in the example screenshot below. This will open a standard Windows open dialog; locate the RSA or DSA private key file and click the 'Open' button. Generate rsa key windows putty download. Generate keys. In Windows, use PuTTYgen to generate your public and private keys. If needed, download PuTTYgen from the PuTTY download page. (PuTTYgen might have been installed previously with PuTTY or WinSCP.) Launch the program, and then click the Generate button. The program generates the keys. Generating an SSH Key Pair on Windows Using the PuTTY Key Generator. Step 1 a.Find puttygen.exe in the PuTTY folder on your computer and double-click it. B.Accept the default key type, SSH-2 RSA,and set the Number of bits in a generated key to 2048, if it is not already set.
You can now use the Count parameter without piping objects to Get-Random
.The following example gets three random numbers less than 10.
Example 13: Use the InputObject parameter with an empty string or $null
In this example, the InputObject parameter specifies an array that contains an empty string('
) and $null
.
Get-Random
will return either a
, empty string, or $null
. The empty sting displays as a blankline and $null
returns to a PowerShell prompt.
Specifies the number of random objects or numbers to return. The default is 1.
When used with InputObject
, if the value of Count exceeds the number of objects in thecollection, Get-Random
returns all of the objects in random order.
Type: | Int32 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a collection of objects. Get-Random
gets randomly selected objects in random order fromthe collection up to the number specified by Count. Enter the objects, a variable that containsthe objects, or a command or expression that gets the objects. You can also pipe a collection ofobjects to Get-Random
.
Beginning in PowerShell 7, the InputObject parameter accepts arrays that can contain an emptystring or $null
. The array can be sent down the pipeline or as an InputObject parameter value.
Type: | Object[] |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True (ByValue) |
Accept wildcard characters: | False |
Specifies a maximum value for the random number. Get-Random
returns a value that is less than themaximum (not equal). Enter an integer, a double-precision floating-point number, or an object thatcan be converted to an integer or double, such as a numeric string ('100').
The value of Maximum must be greater than (not equal to) the value of Minimum. If the valueof Maximum or Minimum is a floating-point number, Get-Random
returns a randomly selectedfloating-point number.
On a 64-bit computer, if the value of Minimum is a 32-bit integer, the default value ofMaximum is Int32.MaxValue.
If the value of Minimum is a double (a floating-point number), the default value of Maximumis Double.MaxValue. Otherwise, the default value is Int32.MaxValue.
Type: | Object |
Position: | 0 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a minimum value for the random number. Enter an integer, a double-precision floating-pointnumber, or an object that can be converted to an integer or double, such as a numeric string('100'). The default value is 0 (zero).
The value of Minimum must be less than (not equal to) the value of Maximum. If the value ofMaximum or Minimum is a floating-point number, Get-Random
returns a randomly selectedfloating-point number.
Type: | Object |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a seed value for the random number generator. This seed value is used for the currentcommand and for all subsequent Get-Random
commands in the current session until you useSetSeed again or close the session. You can't reset the seed to its default value.
The SetSeed parameter is not required. By default, Get-Random
uses theRandomNumberGenerator()method to generate a seed value. Because SetSeed results in non-random behavior, it's typicallyused only when trying to reproduce behavior, such as when debugging or analyzing a script thatincludes Get-Random
commands.
Type: | Int32 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
You can pipe one or more objects. Get-Random
selects values randomly from the piped objects.
System.Int32, System.Int64, System.Double
Get-Random
returns an integer or floating-point number, or an object selected randomly from asubmitted collection.
Get-Random
sets a default seed for each session based on the system time clock when the sessionstarts.
Get-Random
does not alway return the same data type as the input value. The following table showsthe output type for each of the numeric input types.
Input Type | Output Type |
---|---|
SByte | Double |
Byte | Double |
Int16 | Double |
UInt16 | Double |
Int32 | Int32 |
UInt32 | Double |
Int64 | Int64 |
UInt64 | Double |
Double | Double |
Single | Double |
Beginning in Windows PowerShell 3.0, Get-Random
supports 64-bit integers. In Windows PowerShell2.0, all values are cast to System.Int32.
Beginning in PowerShell 7, the InputObject parameter in the RandomListItemParameterSetparameter set accepts arrays that contain an empty string or $null
. In earlier PowerShellversions, only the Maximum parameter in the RandomNumberParameterSet parameter set acceptedan empty string or $null
.
How would it be possible to generate a random, unique string using numbers and letters for use in a verify link? Like when you create an account on a website, and it sends you an email with a link, and you have to click that link in order to verify your account…yeah…one of those.
How can I generate one of those using PHP?
Update: Just remembered about uniqid()
. It’s a PHP function that generates a unique identifier based on the current time in microseconds. I think I’ll use that.
Security Notice: This solution should not be used in situations where the quality of your randomness can affect the security of an application. In particular, rand()
and uniqid()
are not cryptographically secure random number generators. See Scott’s answer for a secure alternative.
If you do not need it to be absolutely unique over time:
md5(uniqid(rand(), true))
Otherwise (given you have already determined a unique login for your user):
I was just looking into how to solve this same problem, but I also want my function to create a token that can be used for password retrieval as well. This means that I need to limit the ability of the token to be guessed. Because uniqid
is based on the time, and according to php.net “the return value is little different from microtime()”, uniqid
does not meet the criteria. PHP recommends using openssl_random_pseudo_bytes()
instead to generate cryptographically secure tokens.
A quick, short and to the point answer is:
which will generate a random string of alphanumeric characters of length = $bytes * 2. Unfortunately this only has an alphabet of [a-f][0-9]
, but it works.
Below is the strongest function I could make that satisfies the criteria (This is an implemented version of Erik’s answer).
crypto_rand_secure($min, $max)
works as a drop in replacement for rand()
or mt_rand
. It uses openssl_random_pseudo_bytes to help create a random number between $min and $max.
getToken($length)
creates an alphabet to use within the token and then creates a string of length $length
.
EDIT: I neglected to cite source – http://us1.php.net/manual/en/function.openssl-random-pseudo-bytes.php#104322
EDIT (PHP7): With the release of PHP7, the standard library now has two new functions that can replace/improve/simplify the crypto_rand_secure function above. random_bytes($length)
and random_int($min, $max)
Example:
I’ve created an object-oriented solution based on Scott‘s answer:
You can use custom alphabet if required.
Just pass a string with supported chars to the constructor or setter:
I hope it will help someone. Cheers!
This function will generate a random key using numbers and letters:
Example output:
You can use UUID(Universally Unique Identifier), it can be used for any purpose, from user authentication string to payment transaction id.
A UUID is a 16-octet (128-bit) number. In its canonical form, a UUID is represented by 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens).
//calling funtion
some example outputs will be like:
hope it helps someone in future 🙂
I use this one-liner:
where length is the length of the desired string (divisible by 4, otherwise it gets rounded down to the nearest number divisible by 4)
I’m late but I’m here with some good research data based on the functions provided by Scott’s answer. So I set up a Digital Ocean droplet just for this 5-day long automated test and stored the generated unique strings in a MySQL database.
During this test period, I used 5 different lengths (5, 10, 15, 20, 50) and +/-0.5 million records were inserted for each length. During my test, only the length 5 generated +/-3K duplicates out of 0.5 million and the remaining lengths didn’t generate any duplicates. So we can say that if we use a length of 15 or above with Scott’s functions, then we can generate highly reliable unique strings. Here is the table showing my research data:
I hope this helps.
e.g (in pseudo code)
Here is ultimate unique id generator for you. made by me.
you can echo any ‘var’ for your id as you like. but $mdun is better, you can replace md5 to sha1 for better code but that will be very long which may you dont need.
Thank you.
Use below code to generate the random number of 11 characters or change the number as per your requirement.
Here is what I use:
I like to use hash keys when dealing verification links. I would recommend using the microtime and hashing that using MD5 since there should be no reason why the keys should be the same since it hashes based off of the microtime.
$key = md5(rand());
$key = md5(microtime());
Scott, yes you are very write and good solution! Thanks.
I am also required to generate unique API token for my each user. Following is my approach, i used user information (Userid and Username):
Please have a look and let me know if any improvement i can do. Thanks Generate 4096 bit ssl key openssl.
after reading previous examples I came up with this:
I duplicate 10 times the array[0-9,A-Z] and shuffle the elements, after I get a random start point for substr() to be more ‘creative’ 🙂
you can add [a-z] and other elements to array, duplicate more or less, be more creative than me
above function will generate you a random string which is length of 11 characters.
I believe the problem with all the existing ideas is that they are probably unique, but not definitely unique (as pointed out in Dariusz Walczak’s reply to loletech). I have a solution that actually is unique. It requires that your script have some sort of memory. For me this is a SQL database. You could also simply write to a file somewhere. There are two implementations:
First method: have TWO fields rather than 1 that provide uniqueness. The first field is an ID number that is not random but is unique (The first ID is 1, the second 2…). If you are using SQL, just define the ID field with the AUTO_INCREMENT property. The second field is not unique but is random. This can be generated with any of the other techniques people have already mentioned. Scott’s idea was good, but md5 is convenient and probably good enough for most purposes:
Second method: Basically the same idea, but initially pick a maximum number of strings that will ever be generated. This could just be a really big number like a trillion. Then do the same thing, generate an ID, but zero pad it so that all IDs are the same number of digits. Then just concatenate the ID with the random string. It will be random enough for most purposes, but the ID section will ensure that it is also unique.
Here is what I’m using on one of my projects, it’s working great and it generates a UNIQUE RANDOM TOKEN:
Please note that I multiplied the timestamp by three to create a confusion for whoever user might be wondering how this token is generated 😉
I hope it helps 🙂
You can use this code,
I hope it will be helpful for you.
Details about Random code generator in PHP
Simplifying Scotts code above by removing unnecessary loops which is slowing down badly and does not make it any more secure than calling openssl_random_pseudo_bytes just once
Tags: dom, phpphp, random, string