B = 15 privatekey = 0 #brute force O(n) for i in range(n): if pow(2, i, n) == B: privatekey = i break print("brute force result: ", privatekey) #shank algorithm O(sqrt(n)) terminate = False m = int(math.sqrt(n - 1)) + 1 for i in range(0, m): t1 = pow(a, m * i, n) #print(t1) for j in range(0, m): t2 = B * commons.modInverse(pow(a, j), n) % n #print("\t",t2) if t1 == t2: #print("two tables have ",t1," value") print("shank algorithm result: ", m * i + j) terminate = True break if terminate == True: break
e = random.randint(1, totient) print("public key: ",e) #------------------------------- #find multiplicative inverse of e mod totient #brute force """d=0 for i in range(totient): if (e*i) % totient == 1: d = i break """ d = commons.modInverse(e, totient) print("private key: ",d) print("key generation is complete in ",time.time() - starttime," seconds\n") publickey = e privatekey = d #-------------------------------- print("-------------------------") print("message encryption") print("-------------------------") m = 11
y = pow(g, x, p) print("private key: ",x) print("public key: ",y) print("public params: p=",p,", q=",q,", g=",g,"") #------------------------------- print("signing") k = 10 #random key h = 123 r = pow(g, k, p) % q s = commons.modInverse(k, q) * (h + x*r) % q print("signature: (r=",r,", s=",s,")") #------------------------------- print("verification") h = 123 #Bob knows public key -> y #Also, he knows public params -> p, q, g #Also, he knows h, (r, s) pair w = commons.modInverse(s, q) u1 = h * w % q u2 = r * w % q
y = pow(g, x, p) print("private key: ", x) print("public key: ", y) print("public params: p=", p, ", q=", q, ", g=", g, "") #------------------------------- print("signing") k = 10 #random key h = 123 r = pow(g, k, p) % q s = commons.modInverse(k, q) * (h + x * r) % q print("signature: (r=", r, ", s=", s, ")") #------------------------------- print("verification") h = 123 #Bob knows public key -> y #Also, he knows public params -> p, q, g #Also, he knows h, (r, s) pair w = commons.modInverse(s, q) u1 = h * w % q u2 = r * w % q
print("digital signature") print("-----------------------") print("signing") hash = 100 k = random.randint(1, p - 1) while commons.gcd(p - 1, k) != 1: k = random.randint(1, p - 1) #print("random key: ",k) r = pow(g, k, p) s = (hash - x * r) * commons.modInverse(k, p - 1) % (p - 1) print("signature: (r=", r, ", s=", s, ")") print("verification") hash = 100 checkpoint1 = pow(g, hash, p) checkpoint2 = (pow(y, r, p) * pow(r, s, p)) % p print("checkpoint1: ", checkpoint1) print("checkpoint2: ", checkpoint2) if checkpoint1 == checkpoint2: print("signature is valid")