Calculating very large exponents in python

后端 未结 3 1789
挽巷
挽巷 2020-12-19 08:17

Currently i am simulating my cryptographic scheme to test it. I have developed the code but i am stuck at one point.

I am trying to take: g**x where <

相关标签:
3条回答
  • 2020-12-19 08:41

    It's not hanging, it's just processing. It will eventually give you the answer, provided it doesn't run out of memory first.

    I haven't heard of the result of such a process being used in cryptography though; usually it's the modulus of said power that matters. If it's the same in your case then you can just use the 3-argument form of pow() instead.

    0 讨论(0)
  • 2020-12-19 08:48

    You shouldn't try to calculate x^y directly for huge values of y - as has already been pointed out, this is pretty difficult to do (takes lots of space and processing power). You need to look at algorithms that solve the problem for you with fewer multiplication operations. Take a look at: http://en.wikipedia.org/wiki/Exponentiation_by_squaring for starters.

    Modular exponentiation is also pretty well understood: http://en.wikipedia.org/wiki/Modular_exponentiation.

    You will need to use a python library for large numbers, such as http://gmpy.sourceforge.net/.

    If it's any help, I did modular exponentiation in C using mpir. I'll attach that code, you'll need to convert it to python of course.

    int power_modn( mpz_t c, mpz_t b, mpz_t e, mpz_t n)
    {
            mpz_t result;
            mpz_t one;
            mpz_t r;
    
            mpz_t modulus; mpz_t exponent; mpz_t base;
    
            mpz_init(modulus); mpz_init(exponent); mpz_init(base);
            mpz_init(result); mpz_init(one); mpz_init(r);
    
            mpz_set_ui(result, 1);
            mpz_set_ui(one, 1);
    
            mpz_set(base, b);
            mpz_set(exponent, e);  
            mpz_set(modulus, n);
    
            while ( mpz_cmp_ui(exponent, 0) > 0 )
            {
                   if ( mpz_mod_ui( r, exponent, 2) == 1 )
                   { 
                            mpz_mul(result, result, base);
                            mpz_mod(result, result, modulus);
                   };
                   mpz_mul(base, base, base);
                   mpz_mod(base, base, modulus);
                   mpz_fdiv_q_ui(exponent, exponent, 2);
            }
    
            mpz_set(c, result);
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-19 08:50

    I'm not quite sure you appreciate the sheer magnitude of what you're asking Python to do. Raising something to a power x where x is 256 bits long, is doing the equivalent of 2**256 multiplications, or 115792089237316195423570985008687907853269984665640564039457584007913129639936 multiplications. As you can imagine, this may take some time. And space, which I guarantee you don't have enough of.

    0 讨论(0)
提交回复
热议问题