Take the 2-minute tour ×
Cryptography Stack Exchange is a question and answer site for software developers, mathematicians and others interested in cryptography. It's 100% free, no registration required.

I'd like to use Python's random.choice seeded with a HMAC-SHA1 tag to generate a MAC encoded in a variable set of chars.

import random, hmac, hashlib, string

SECRET = 'something secret'
MESSAGE = 'some message'
MAC_CHARS = string.ascii_letters + string.digits
MAC_LEN = 10

random.seed(hmac.new(SECRET, MESSAGE, hashlib.sha256).digest())
mac = ''.join([random.choice(MAC_CHARS) for _ in xrange(MAC_LEN)])
random.seed()  # resets seed from /dev/random

Are the properties of the mac variable at equivalent to that of an HMAC tag?

share|improve this question
    
Do you want to tell us more about why you want to use Python's random.choice in this way? There might be a better solution. (P.S. Welcome to Crypto.SE!) –  D.W. Apr 18 '13 at 10:29
    
Thanks! Indeed there probably are. In this case, I'm trying to pick randomly from a custom alphabet. I thought of doing ALPHABET[MAC mod ALPHABET_SIZE], but it seems like some elements in the alphabet will get picked over others. I'll post the problem I'm trying to solve in a separate question. –  Andrey Fedorov Apr 19 '13 at 1:38

2 Answers 2

up vote 1 down vote accepted

A simple solution to your real problem would be to seed a cryptographic-strength PRNG using the output of the MAC as the seed, then use the crypto PRNG to pick randomly from your alphabet. In that case the result of your random picks does form a secure MAC (assuming it is long enough).

For example, you could let $T = \text{SHA256-HMAC}(K,M)$, then use AES-CTR mode as your crypto-strenth PRNG: initially you set a counter $c$ to 0; whenever you need a new random value, you increment $c$ and then output $Y = \text{AES}_T(c)$ (the AES-ECB encryption of the counter, under key $T$). This defines the sequence of outputs from the crypto PRNG. You can then convert these outputs to characters from your alphabet via standard methods, e.g., to get a value from the range $0\ldots n-1$, you can use $Y \bmod n$ (assuming $n$ is much smaller than $2^{128}$).

share|improve this answer

No. It looks like random.seed uses the hash of the argument, which is a 4-byte int.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.