Python generate random md5

Случайный хеш в Python

Случайно как в чем-либо? Или для объекта? Если вам нужен случайный MD5, просто выберите несколько цифр.

Я переименовываю файлы перед загрузкой и хочу имя файла вроде этого: timestamp_randommd5.extension Cheers!

Вы можете просто переименовать их в timestamp_randomnumber.ext. На самом деле нет причины, по которой md5 (randomnumber) будет лучше, чем само randomnumber.

лучший ответ для Python 3 — последний import uuid; uuid.uuid().hex hexoverflow.com/a/20060712/3218806

8 ответов

A md5-hash — это всего лишь 128-битное значение, поэтому, если вы хотите случайный:

import random hash = random.getrandbits(128) print "hash value: %032x" % hash 

Я действительно не вижу смысла. Может быть, вы должны уточнить, зачем вам это нужно.

+1 — конечно, это лучше, чем мой ответ, может использоваться также так: hex (random.getrandbits (128)) [2: -1] это дает тот же результат, что и метод md5 hexdigest.

Я думаю, что вы ищете универсальный уникальный идентификатор. Тогда модуль UUID в python — это то, что вы ищете.

UUID4 дает вам случайный уникальный идентификатор, который имеет ту же длину, что и сумма md5. Hex будет представлять собой шестую строку вместо возврата объекта uuid.

Это работает как для python 2.x, так и для 3.x

import os import binascii print(binascii.hexlify(os.urandom(16))) '4a4d443679ed46f7514ad6dbe3733c3d' 

Еще один подход. Вам не нужно форматировать int, чтобы получить его.

import random import string def random_string(length): pool = string.letters + string.digits return ''.join(random.choice(pool) for i in xrange(length)) 

Дает вам гибкость в отношении длины строки.

>>> random_string(64) 'XTgDkdxHK7seEbNDDUim9gUBFiheRLRgg7HyP18j6BZU5Sa7AXiCHP1NEIxuL2s0' 

Я, вероятно, изменил бы string.letters на ‘abcdf’, чтобы отразить шестнадцатеричные цифры. Но отличное решение!

В Python 3.6+ добавлен secrets module. Он обеспечивает криптографически безопасные случайные значения с помощью одного вызова. Функции принимают необязательный аргумент nbytes , по умолчанию 32 (байты * 8 бит = маркеры с 256 бит). MD5 имеет 128-битные хэши, поэтому для маркеров типа «MD5-like» предусмотрены 16.

>>> import secrets >>> secrets.token_hex(nbytes=16) '17adbcf543e851aa9216acc9d7206b96' >>> secrets.token_urlsafe(16) 'X7NYIolv893DXLunTzeTIQ' >>> secrets.token_bytes(128 // 8) b'\x0b\xdcA\xc0.\x0e\x87\x9b`\x93\\Ev\x1a|u' 

Другой подход к этому конкретному вопросу:

import random, string def random_md5like_hash(): available_chars= string.hexdigits[:16] return ''.join( random.choice(available_chars) for dummy in xrange(32)) 

Я не говорю это быстрее или предпочтительнее любого другого ответа; просто что это другой подход:)

Читайте также:  Edit Profile

Источник

Generate Random Hash in Python

A hash function is any function that maps input of varied sizes into a fixed-size output. The values returned by the hash function are called hashes, hash values, hash codes, checksums, or hash digests.

Depending on the hashing algorithm used, two inputs may be mapped into the same output. This is called hashing collision. An example of such a collision is shown below.

In this article, we will use Python to generate random hashes and also discuss how to implement the popular hashing algorithms, namely, Message-Diggest (MD) and Secure Hash Algorithm (SHA).

Method 1: Generate Random Hashes with random Module

In the random package, we can specify the number of bits for the hash we wish to generate, and random hash values are generated on execution. For example,

Output (random):

2ad98ac316a093cd32f2b05296d98e3b

The above example generates a 128-bit long random number and converts it into hexadecimal using %x string formatting. %032x represents the random bits as a hex string of 32 characters. If the hex does not contain at least 32 characters, pad it with zeros on the left. The same concept can be code-written as:

Output (random):

0x2d708d53a3e2ec2cb13b852aec465cefL 2d708d53a3e2ec2cb13b852aec465cef

The hex() function generates the hexadecimal equivalent of a randomly generated 128-bit long number. The output of hex() contains some characters we are not interested in – 0x at the beginning and the trailing L. We remove those by indexing the characters we want.

Important note (Are computer-generated random characters really random?)

In most cases, the random characters generated by computers (using packages like random and NumPy) are not genuinely random – they are pseudo-random. This is because these characters are generated using a mathematical formula and are therefore predictable.

In the world of cryptography, therefore, using pseudo-random characters is not recommended; instead, characters with “true” randomness are used. Genuine random characters can be generated on this site: https://www.random.org/.

Method 2: Using the secrets package

The secrets module was added in Python 3.6+. It provides cryptographically strong random values. The functions take an optional nbytes argument, the default is 32 (32 bytes * 8 bits = 256-bit tokens). Examples,

Читайте также:  Php league oauth2 server

Output (random):

2bd8d5ea4040abae052804b905e6445a XaiTTn1LBBv9JZ_0QQ5WOw b'CJZ|\xa1\x948\xb2hVgG&\xb48\xc2'

A 128-bit long hash has 16 bytes, so we set nbytes to 16.

Method 3: Using os and binascii

The os module has urandom() method that can be used to generate a string of random bytes suitable for cryptographic use. Once the random string is generated, it is converted into hex using binascii, as shown below.

Output (random):

b'\x1d3"\xed\x93\xdb\xc3\xab\xaa\xbdb\xad_\xf93?' 1d3322ed93dbc3abaabd62ad5ff9333f

Note: the above code works for Python 2 and Python 3, but in the latter, the output is in bytes and therefore needs to be decoded. In Python 2, that is not necessary.

Method 4: Using string and random modules

From the previous examples, notice that the digests we generated contain letters and numbers. Given that fact, we can use alphabetical letters and numbers to create random hashes as follows randomly.

Output (random):

3xnroUdRq2kvtAaSWZE0GVsu19TbgBJK

In the example above, string.ascii_letters contain a-z and A-Z letters, whereas string.digits has numbers 0 through 9. These make 62 characters. From these characters, we sample 32 of them.

If you want hexadecimal output, you need to sample from the possible characters, that is, “abcdef” and “0123456789”. In this case, it is impossible to sample 32 characters from the 15 available in hex format. Therefore, we will use sampling with a replacement achieved with random.choice() function. See below.

Output (random):

a07c706a7d1d731de23c763889bfc56a

In the next two methods, we will use Python to implement the two most commonly used hashing algorithms – MD5 and SHA256.

These algorithms are used for cryptographic purposes, but MD5 has been found to suffer from extensive vulnerabilities. For this reason, it is mainly used as a checksum for data integrity but not as a backbone for secured encryption.

Method 5: Implementing MD5 hashing in Python

MD stands for Message-Digest algorithm. The number 5 in MD5 is just the series number. MD5 generates a 128-bit digest given an input key. In Python, this algorithm can be implemented using the hashlib library. Here are some examples,

Output (not random):

74a11ef33c5252edfa87c4eb8b566c2a fb4de79cd3ef366102d02c7f465cb760 95d8ac53b544781d2e2f4f63567c940d

Unlike the previous methods, the MD5 function maps inputs to a unique (in most cases – hash collision can happen but rarely) non-random fixed-size output.

Читайте также:  Javascript display text in div

Notice that any slight change in the string input, like in “secret word” and “secret word ” (there’s a trailing white space), leads to a significant change in the hash digest. This is called the avalanche effect – a phenomenon adopted by hashing algorithms to make them unpredictable.

MD5 does not only work with strings and other data types in Python. MD5 hashing is also used to check the integrity of files.

Two different files cannot have the same MD5 checksum. In this case, we can use MD5 to check if the two files have the same content. When downloading files, you can also use MD5 hash values to check if the file downloaded is corrupted or not. Here are some examples:

Источник

sillygwailo / random_md5.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

#!/usr/bin/env python
# Prints an MD5 hash from a random string.
# Helpful resources:
# http://stackoverflow.com/questions/785058/random-strings-in-python-2-6-is-this-ok
# http://docs.python.org/library/hashlib.html
import random , string , hashlib , argparse , sys
parser = argparse . ArgumentParser ( description = ‘Generates a random string, hashes it with MD5 and outputs it.’ )
parser . add_argument ( ‘-s’ , ‘—slug’ , action = ‘store_true’ , default = False , help = ‘show a slug (first 6 characters of the hash, GitHub-style)’ )
parser . add_argument ( ‘-c’ , ‘—no-newline’ , action = ‘store_true’ , default = False , help = ‘remove newline (only if one hash requested)’ )
parser . add_argument ( ‘-n’ , ‘—number’ , action = ‘store’ , type = int , default = 1 , help = ‘number of hashes to show’ )
def random_md5 ( string_length = 25 , slug = False , number = 1 ):
hashes = []
for n in range ( number ):
r = » . join ( random . choice ( string . letters + string . digits ) for i in xrange ( string_length ))
m = hashlib . md5 ()
m . update ( r )
if slug == True :
hashes . append ( m . hexdigest ()[: 6 ])
else :
hashes . append ( m . hexdigest ())
return hashes
if __name__ == ‘__main__’ :
arguments = parser . parse_args ()
hashes = random_md5 ( slug = arguments . slug , number = arguments . number )
if ( arguments . number == 1 and arguments . no_newline == True ):
sys . stdout . write ( hashes [ 0 ])
else :
for hash in hashes :
print hash

Источник

Оцените статью