Python暗号学_RSA公開鍵と秘密鍵の生成

2405 ワード

RSAシステムの鍵は2つの数字で構成され、約3つのステップがあります.
1)2つの非常に大きな乱数:qとpを作成し,乗算してnを得る.
2)(q-1)*(p-1)と相互作用する乱数eを作成する
3)eの逆モードを計算してdを得る
以下にプログラムと詳細なコメントを示します.
import random,sys,os,cryptomath
import rabinMiller
def main():
    print('     .....')
    #    al_sweigart'   1024  makeKeyFiles()  
    #       al_sweigart-pubkey.txt al_sweigart-privkey.txt
    makeKeyFiles('al_sweigart',1024)
    print('       ')

def generateKey(keysize):
    print('       p......')
    p=rabinMiller.generateLargePrime(keysize)
    print('       q......')
    q=rabinMiller.generateLargePrime(keysize)
    #            n
    n=q*p
    #     e,  q-1 p-1    
    print('     e......')
    while True:
        #      e
        e=random.randrange(2**(keysize-1),2**(keysize))
        #  e q - 1 p - 1      
        #        ,     
        if cryptomath.gcd(e,(p-1)*(q-1))==1:break
    print('  e   d......')
    d=cryptomath.findModInverse(e,(p-1)*(q-1))
    #               
    publicKey=(n,e)
    privateKey=(n,d)
    #    
    print('PublicKey:',publicKey)
    print('PrivateKey',privateKey)
    return (publicKey,privateKey)

#        txt  
def makeKeyFiles(name,keySize):
    #           ,          
    if os.path.exists('%s_pubkey.txt'%name) or os.path.exists('%s_privkey.txt'%name):
        sys.exit('WARNING')
    #      ,       ,      publicKey privateKey 
    publicKey,privateKey=generateKey(keySize)
    #      :      ,n  ,e/d  
    #    
    print()
    print('The public key is a %s and a %s digit number.' % (len(str(publicKey[0])), len(str(publicKey[1]))))
    print('Writing public key to file %s_pubkey.txt...' % (name))
    fo = open('%s_pubkey.txt' % (name), 'w')
    fo.write('%s,%s,%s' % (keySize, publicKey[0], publicKey[1]))
    fo.close()
    #    
    print()
    print('The private key is a %s and a %s digit number.' % (len(str(publicKey[0])), len(str(publicKey[1]))))
    print('Writing private key to file %s_privkey.txt...' % (name))
    fo = open('%s_privkey.txt' % (name), 'w')
    fo.write('%s,%s,%s' % (keySize, privateKey[0], privateKey[1]))
    fo.close()

if __name__ == '__main__':
    main()

rabinMiller.pyファイルコード:https://blog.csdn.net/qq_41938259/article/details/86675887