Search code examples
pythonpython-2.7diffie-hellman

Get a cryptographically secure random numder as an integer in python


I try to perform some modular exponentiation in order to perform some chained Diffie Hellman key agreement (for research puproce).

Thus I generate the random key like that:

priv_value=Random.get_random_bytes(128)

And I generate the Diffie Hellman public value like that:

def dh_public(secret):
    g=2

    p="""FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1
      29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD
      EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245
      E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED
      EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D
      C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F
      83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D
      670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B
      E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9
      DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510
      15728E5A 8AACAA68 FFFFFFFF FFFFFFFF"""
    p=re.sub(r"[\n\t\s]*", "", p)
    p=int(p,16)
    return pow(g,secret,p)

So my script that does the calculation is:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- Mode: python; c-basic-offset: 4 -*-

from Crypto import Random
import re

priv=Random.get_random_bytes(128)

def dh_public(secret):
    g=2

    p="""FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1
      29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD
      EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245
      E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED
      EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D
      C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F
      83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D
      670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B
      E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9
      DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510
      15728E5A 8AACAA68 FFFFFFFF FFFFFFFF"""
    p=re.sub(r"[\n\t\s]*", "", p)
    p=int(p,16)
    return pow(g,secret,p)

print dh_public(priv)

With g and p values that are based upon RFC3526.

But when I try to run it I get the following error:

Traceback (most recent call last):
  File "/home/pcmagas/Kwdikas/python/DHKeylist/dh_demo.py", line 28, in <module>
    print dh_public(priv)
  File "/home/pcmagas/Kwdikas/python/DHKeylist/dh_demo.py", line 26, in dh_public
    return pow(g,secret,p)
TypeError: unsupported operand type(s) for pow(): 'int', 'str', 'long'

So my problem is on how to convert the Random.get_random_bytes value to integer. (I do not know the base to convert them with python's int method.)


Solution

  • The key to your solution is the following...

    Replace

    return pow(g,secret,p)
    

    with (for python 3)

    return pow(g, int.from_bytes(secret, byteorder='big'), p)
    

    or (for python 2.7)

    return pow(g, int(secret.encode('hex'), 16), p)