How to Create a Random Hash/String

What is the best way to create a random hash/string?

You can use PHP's built-in hashing functions, sha1 and md5. Choose one, not both.

One may think that using both, sha1(md5($pass)) would be a solution. Using both does not make your password more secure, its causes redundant data and does not make much sense.

Take a look at PHP Security Consortium: Password Hashing they give a good article with weaknesses and improving security with hashing.

Nonce stands for "numbers used once". They are used on requests to prevent unauthorized access, they send a secret key and check the key each time your code is used.

You can check out more at PHP NONCE Library from FullThrottle Development

Generate random string/characters in JavaScript

I think this will work for you:

function makeid(length) {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
let counter = 0;
while (counter < length) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
counter += 1;
}
return result;
}

console.log(makeid(5));

Random hash in Python

A md5-hash is just a 128-bit value, so if you want a random one:

import random

hash = random.getrandbits(128)

print("hash value: %032x" % hash)

I don't really see the point, though. Maybe you should elaborate why you need this...

Generate random numbers that depend on string hash

I agree with nihlon, if what you want is a function f() returning an int such that f(string1) != f(string2) for any string1, string2 in some set of strings S, then you're looking for a perfect hash.
Obviously, if S is the set of all possible strings, there are way more than 2^32, or even 2^64, so no such f() can exist returning an int or even long. Hence, the question is: how is S characterized?

Also, are you sure you need unique numbers for different strings? In most problem domains regular hashing is adequate...

C# Generate a random Md5 Hash

You could create a random string using Guid.NewGuid() and generate its MD5 checksum.

How to generate a random alpha-numeric string

Algorithm

To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.

Implementation

Here's some fairly simple and very flexible code for generating random identifiers. Read the information that follows for important application notes.

public class RandomString {

/**
* Generate a random string.
*/
public String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return new String(buf);
}

public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

public static final String lower = upper.toLowerCase(Locale.ROOT);

public static final String digits = "0123456789";

public static final String alphanum = upper + lower + digits;

private final Random random;

private final char[] symbols;

private final char[] buf;

public RandomString(int length, Random random, String symbols) {
if (length < 1) throw new IllegalArgumentException();
if (symbols.length() < 2) throw new IllegalArgumentException();
this.random = Objects.requireNonNull(random);
this.symbols = symbols.toCharArray();
this.buf = new char[length];
}

/**
* Create an alphanumeric string generator.
*/
public RandomString(int length, Random random) {
this(length, random, alphanum);
}

/**
* Create an alphanumeric strings from a secure generator.
*/
public RandomString(int length) {
this(length, new SecureRandom());
}

/**
* Create session identifiers.
*/
public RandomString() {
this(21);
}

}

Usage examples

Create an insecure generator for 8-character identifiers:

RandomString gen = new RandomString(8, ThreadLocalRandom.current());

Create a secure generator for session identifiers:

RandomString session = new RandomString();

Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:

String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
RandomString tickets = new RandomString(23, new SecureRandom(), easy);

Use as session identifiers

Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.

There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.

The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.

Use as object identifiers

Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.

Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.

Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." The probability of a collision, p, is approximately n2/(2qx), where n is the number of identifiers actually generated, q is the number of distinct symbols in the alphabet, and x is the length of the identifiers. This should be a very small number, like 2‑50 or less.

Working this out shows that the chance of collision among 500k 15-character identifiers is about 2‑52, which is probably less likely than undetected errors from cosmic rays, etc.

Comparison with UUIDs

According to their specification, UUIDs are not designed to be unpredictable, and should not be used as session identifiers.

UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.

UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.

How to generate random string and put it in HashTable?

You can use Apache Commons Lang to generate an alphabetic string

String generatedString = RandomStringUtils.randomAlphanumeric(10);

Try something like this

    Hashtable<Integer, String> Deck = new Hashtable();

for (int i = 0; i < 10; i++) {
String generatedString = RandomStringUtils.randomAlphanumeric(10);
int key = (int) (Math.random() *52) ;
Deck.put(key, generatedString);
}
System.out.println(Deck);

OutPut

{9=Ut7N87oMNp, 8=7kbARh5WIy, 7=pbU2ZCOGK1, 6=vAGAIw41Us, 5=VLnpY1FAuN, 4=UEIJNIvZlt, 3=z6Y3zXcDY1, 2=PxaMqXl8XW, 1=l72bkPdY6T, 0=FFdOsKpQgd}

If you want only Alphabets then use RandomStringUtils.randomAlphabetic(10); instaed of RandomStringUtils.randomAlphanumeric(10).

If you dont want third party api, then its your code snippet with some changes

while (k < 4) {
for (int j = 1; j <= 13; j++) {
Hashtable<Integer, String> Deck = new Hashtable();
StringBuilder sb = new StringBuilder();
int cnt = 0;
while (cnt++ != 10) {
int myChar = (int) (Math.random() * str.length());
sb.append(str.charAt(myChar));
}
int i = (int) (Math.random() * 52);
Deck.put(i, sb.toString());
System.out.print(Deck);
}

System.out.println();
k++;
}

Added while loop only...

How to generate random string in dart?

Or if you don't want to use a package you can make a simple implementation like:

import 'dart:math';

void main() {
print(getRandomString(5)); // 5GKjb
print(getRandomString(10)); // LZrJOTBNGA
print(getRandomString(15)); // PqokAO1BQBHyJVK
}

const _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
Random _rnd = Random();

String getRandomString(int length) => String.fromCharCodes(Iterable.generate(
length, (_) => _chars.codeUnitAt(_rnd.nextInt(_chars.length))));

I should add that you should not use this code to generate passwords or other kind of secrets. If you do that, please at least use Random.secure() to create the random generator.

How to generate random number by given string in python?

You can use a hash from hashlib. For example:

import hashlib
int(hashlib.sha256(b'yourstring').hexdigest(), base=16)


Related Topics



Leave a reply



Submit