How do I add an if-else statement without running an infinite loop?

306 views Asked by At

How do i create an if else statement to make sure the privatekey will not be printed the same? I want to make sure that the keys generated are not the same. Its just a precaution. But when i put the if-else statement in the codes, it runs an infinite loop. I need to print the keys at least 5 times. How can I fix this? I'd really appreciate any help with this code! Got these codes from https://github.com/truh/CryptoFun.

e.g
if box.sk == box.sk:
   generatekeys()

else:
   print("Success!")

where do i put the if else statement in the code below so that it doesnt run an infinite loop?

def generatekeys():

 count = 0
 while (count<5):

    import libnacl.public
    import libnacl.secret
    import libnacl.utils

    msg = b'But then of course African swallows are not migratory.'
    # This methods creates a keypar(public,private) for the Clients

    alice = libnacl.public.SecretKey()


    alice_box = libnacl.public.Box(alice.sk, alice.pk)


    box = libnacl.secret.SecretBox()
    print(box.sk)


    alice_ctxt = alice_box.encrypt(box.sk)
    print(alice_ctxt)


    aclear = alice_box.decrypt(alice_ctxt)
    print(aclear)

    # Alice encrypts a message with the shared key and send it to Bob
    encr = box.encrypt(msg)
    print(encr)

    box2 = libnacl.secret.SecretBox(aclear)
    decr= box2.decrypt(encr)
    print(decr)


  generatekeys()

I intend to just use alice so i dont have 4 keys. I just need one secret(private)key and public key. How do i create 2 if else statements to make use the private keys are not printed the same and another one for the public key?

2

There are 2 answers

2
Glen Pierce On

As written,

if box.sk == box.sk:
   generatekeys()

Will always cause an infinite loop within generatekeys(). This is because bok.sk will always be equal to itself. Which two keys are you worried will be identical in this code? Perhaps you mean this:

 bob = libnacl.public.SecretKey()
 alice = libnacl.public.SecretKey()
 if bob.sk == alice.sk:
       generatekeys()
 else:
       count++
       ...the rest of your code

By the way, the chances of those secret keys being identical should be very, very, very small. If you are commonly getting identical secret keys, there's a problem in your cryptographic algorithm.

1
Theo On

You are not decrementing count in the body of the loop. So the expression count<5 remains True forever.

In this use case, it can be easier to use a for loop instead of a while loop.

for n in range(5)