[pycrypto] Confused about some code in PubKey/RSA/_slowmath.py

Shoufu Luo luoshoufu at gmail.com
Mon Nov 5 00:26:46 EST 2012


Hi all,

I'm trying to encrypt a message with my private key and release the encrypted to others who will use my public key to decrypt. But, I failed. 

I was confused by the follwing code from PubKey/RSA/_slowmath.py of pyCrypto-2.6. If anyone can give any clues to answer the following questions, I will appreciate. 

1. Theoretically, if I encrypt date using private key, I can decrypt the encrypted data using public key, and vice versa. Why the key must be a private key in decryption function, line 51-52? Can't I use private key to decrypt?

2. _sign() should be the signature process using private key to encrypt a piece of data, why it is trying to decrypt at line 70, and it should be decryption in '_verify', but why it is _encrypt()? 

 49     def _decrypt(self, c):
 50         # compute c**d (mod n)
 51         if not self.has_private():
 52             raise TypeError("No private key")
 53         if (hasattr(self,'p') and hasattr(self,'q') and hasattr(self,'u')):
 54             m1 = pow(c, self.d % (self.p-1), self.p)
 55             m2 = pow(c, self.d % (self.q-1), self.q)
 56             h = m2 - m1
 57             if (h<0):
 58                 h = h + self.q
 59             h = h*self.u % self.q
 60             return h*self.p+m1
 61         return pow(c, self.d, self.n)
 62 
 63     def _encrypt(self, m):
 64         # compute m**d (mod n)
 65         return pow(m, self.e, self.n)
 66 
 67     def _sign(self, m):   # alias for _decrypt
 68         if not self.has_private():
 69             raise TypeError("No private key")
 70         return self._decrypt(m)
 71 
 72     def _verify(self, m, sig):
 73         return self._encrypt(sig) == m


Thanks,
Shoufu



More information about the pycrypto mailing list