def main(): if len(sys.argv) != 2: print("\nUsage: $ python ecpractice.py (params | check | generate)\n") return basefield = SubGroup(p=23, g=(16, 13), n=31, h=1) curve = Curve(a=20, b=8, field=basefield, name='Test Curve') option = sys.argv[1] if option == "params": # print curve params print_curve_params(curve) elif option == "check": # check points check_on_curve(curve, 5, 5) check_on_curve(curve, 13, 2) elif option == "generate": # generate EC group by a generator print_generated_group_elements_with_tangent(curve) else: print("\nUsage: $ python ecpractice.py (params | check | generate)\n")
class class_RC: P = (15, 13) #defining elliptical curve, selecting a base point field = SubGroup(p=17, g=(15, 13), n=18, h=1) curve = Curve(a=0, b=7, field=field, name='elliptic_curve') #setting fixed ASK and USK ASK = 'J1BI6av3' USK = '6VWxi48Q' #hash function : SHA256 def hash_sha(self, s): h = hashlib.sha256(s.encode()) return h.hexdigest() #to create a server with SID def on_AS(self, SIDa): SID_concat = SIDa + self.ASK Ks = self.hash_sha(SID_concat) h_ask = self.hash_sha(self.ASK) #insert into database conn = sqlite3.connect('database.sqlite') cursor=conn.cursor() cursor.execute("insert into TS values (?,?)", (SIDa, Ks)) conn.commit() conn.close() return (Ks,h_ask, self.P) #to create a new user def new_user(self, PIDu, PWDu): conn = sqlite3.connect('database.sqlite') cursor=conn.cursor() cursor.execute('Select * from TS') ts = cursor.fetchall() conn.commit() length = len(ts) cursor1=conn.cursor() cursor1.execute('Select * from TU') tu = cursor1.fetchall() SmartCard = 0 Ws = '' if len(tu)==0: SmartCard = 100001 else: z = int(tu[len(tu)-1][1])+1 SmartCard = int(z)+1 for i in range(length): Qs = self.hash_sha(PIDu + ts[i][1]) Rs = int(Qs, 16) ^ int(PWDu, 16) #table to be inserted into smartcard conn.execute('insert into tu values (?,?,?)', (ts[i][0],str(SmartCard), str(Rs))) conn.commit() Ws = self.hash_sha(PIDu + self.USK) h_ask = self.hash_sha(self.ASK) conn.close() return SmartCard, Ws
def secp256k1(): name = 'secp256k1' p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 a = 0x0000000000000000000000000000000000000000000000000000000000000000 b = 0x0000000000000000000000000000000000000000000000000000000000000007 g = (0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798, 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8) h = 1 curve = Curve(a, b, SubGroup(p, g, n, h), name) return curve
def __init__(self): self.field = SubGroup(p=65629, g=(4, 46171), n=65538, h=1) self.curve = Curve(a=-8, b=31, field=self.field, name="p65629") self.encode_map = {} self.decode_map = {} if os.path.exists("../data/encode_map.pickle") and os.path.exists( "../data/decode_map.pickle"): self.encode_map = pickle.load(open("data/encode_map.pickle", "rb")) self.decode_map = pickle.load(open("data/decode_map.pickle", "rb")) else: for k in range(1, self.curve.field.n): p = k * self.curve.g if p.x is None: break self.encode_map[k] = p self.decode_map['' + str(p.x) + ',' + str(p.y)] = k pickle.dump(self.encode_map, open("data/encode_map.pickle", "wb")) pickle.dump(self.decode_map, open("data/decode_map.pickle", "wb")) self.random_k = randint(1, self.curve.field.n) self.random_index = randint(1, self.curve.field.n)
from tinyec.ec import SubGroup, Curve # Domain parameters for the `secp256k1` curve # (as defined in http://www.secg.org/sec2-v2.pdf) name = 'secp256k1' p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 a = 0x0000000000000000000000000000000000000000000000000000000000000000 b = 0x0000000000000000000000000000000000000000000000000000000000000007 g = (0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798, 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8) h = 1 curve = Curve(a, b, SubGroup(p, g, n, h), name) print('curve:', curve) privKey = int( '0x51897b64e85c3f714bba707e867914295a1377a7463a9dae8ea6a8b914246319', 16) print('privKey:', hex(privKey)[2:]) pubKey = curve.g * privKey pubKeyCompressed = '0' + str(2 + pubKey.y % 2) + str(hex(pubKey.x)[2:]) print('pubKey:', pubKeyCompressed)
from tinyec.ec import Curve, Point, SubGroup G = (5083, 5692) Q = (8568, 4147) mod = 9739 a = 497 b = 1768 field = SubGroup(p=mod, g=G, n=mod + 1, h=1) curve = Curve(a=a, b=b, field=field, name="Y^2 = X^3 + 497 X + 1768 mod 9739") point_g = Point(curve, G[0], G[1]) point_q = Point(curve, Q[0], Q[1]) for i in range(1000): if point_g * i == point_q: print(i) break
from tinyec.ec import SubGroup, Curve g = (15, 13) g = (5, 9) field = SubGroup(p=17, g=g, n=18, h=1) curve = Curve(a=0, b=7, field=field, name='p1707') print('curve:', curve) for k in range(0, 25): p = k * curve.g print(f"{k} * G = ({p.x}, {p.y})")
def EccMultiply(GenPoint, ScalarHex): if ScalarHex == 0 or ScalarHex >= n: raise Exception("Invalid Scalar/Private Key") ScalarBin = str(bin(ScalarHex))[2:] Q = GenPoint print(Q) for i in range(1, len(ScalarBin)): # This is invented EC multiplication. Q = ECdouble(Q) # print "DUB", Q[0]; print if ScalarBin[i] == "1": Q = ECadd(Q, GenPoint) # print "ADD", Q[0]; print return (Q) curve = Curve(Acurve, b, SubGroup(Pcurve, g, n, h), name) print('curve:', curve) # privKey = int('0x51897b64e85c3f714bba707e867914295a1377a7463a9dae8ea6a8b914246319', 16) privKey = 72759466100064397073952777052424474334519735946222029294952053344302920927294 print('privKey:', hex(privKey)[2:]) # PublicKey=EccMultiply(g,0x51897b64e85c3f714bba707e867914295a1377a7463a9dae8ea6a8b914246319) # print(hex(PublicKey[0])) pubKey = curve.g * privKey print(pubKey) pubKeyCompressed = '0' + str(2 + pubKey.y % 2) + str(hex(pubKey.x)[2:]) print('pubKey:', pubKeyCompressed)
### Key and address generation # Defining the elliptic curve p = int("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16) n = int("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16) h = 1 x = int("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16) y = int("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 16) g = (x, y) # We can check that the point is really on the curve using # print(y**2 % p == (x**3 + 7) % p) field = SubGroup(p, g, n, h) curve = Curve(a=0, b=7, field=field, name='secp256k1') # print('curve:', curve) # Generating the private and the public keys # Note that tinyec already posses a key generator but it is based on standard python random # which is not secure #private_key = randint(1, n) #private_key = int("f8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315", 16) # yields 0x001d3F1ef827552Ae1114027BD3ECF1f086bA0F9 private_key = int( "208065a247edbe5df4d86fbdc0171303f23a76961be9f6013850dd2bdc759bbb", 16) # yields 0x0BED7ABd61247635c1973eB38474A2516eD1D884 # see https://kobl.one/blog/create-full-ethereum-keypair-and-address/
from tinyec.ec import SubGroup, Curve # Elliptic curve: y² = x³ + ax + b mod p # Parameters: a = 33 b = 51 p = 71 n = 67 # Points in curve. G = (57, 18) # Base point generator. field = SubGroup(p=p, g=G, n=n, h=1) curve = Curve(a=a, b=b, field=field, name='ECDH') print(f'curve: {curve}') G_subgroup = [(lambda p: (p.x, p.y))(k * curve.g) for k in range(n)] # Alice vars. d_a = 12 Q_a = G_subgroup[d_a] print(f'1. Alice generates a random secret number {d_a} and calculate Q_a = \ d_a * G = {d_a} * {G} = {Q_a}') # Bob vars. d_b = 62 Q_b = G_subgroup[d_b] print(f'2. Bob generates a random secret number {d_b} and calculate Q_b = \ d_b * G = {d_b} * {G} = {Q_b}')
def generate_wallet(wallet_password): # __________________________________________________________________________________________________________________ # SECP256K1 PARAMETERS FOR EC CRYPTOGRAPHY p = int("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16) n = int("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16) h = 1 # __________________________________________________________________________________________________________________ # ELLIPTIC CURVE DEFINITION x = int("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16) # See "Recommended Eliptic Curve Domain Parameters" Paper y = int("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 16) g = (x, y) field = SubGroup(p, g, n, h) curve = Curve(a=0, b=7, field=field, name='secp2561k') # Object creation for the elliptic curve # __________________________________________________________________________________________________________________ # PRIVATE/PUBLIC KEY GENERATION THROUGH 'ELLIPTIC CURVE POINT MULTIPLICATION' private_key = randint(1, n) #private_key = int("f8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315", 16) #example public_key = private_key * curve.g # The public key is generated as an added point to the elliptic curve g. To obtain this new point, the eliptic curve # is multiplied by an initial point, known as the private key. Even given the elliptic curve and new point, # it is not (easily) possible to find the initial point (i.e. the private key). # __________________________________________________________________________________________________________________ # DERIVING THE ETHEREUM ADDRESS FROM PUBLIC KEY public_key_hex = Web3.toHex(public_key.x)[2:] + Web3.toHex( public_key.y)[2:] # Removing the 0x start using [2:] address = Web3.keccak(hexstr=public_key_hex).hex() address = Web3.toChecksumAddress('0x' + address[-40:]) # 0x is added to the last 40 characters of the sha-256 encrypted public key to generate the Ethereum address. A # Checksum is applied to the result by capitalizing certain characters (purely for readability). # __________________________________________________________________________________________________________________ # PASSWORD PROTECTION password = str(wallet_password).encode('utf-8') password = bytes(password) # Choose a password salt = get_random_bytes(16) # Generate a random salt key = scrypt(password, salt, 32, N=2**20, r=8, p=1) # Generate a 32-byte encryption key from the password # and salt, with CPU cost parameter 2**20 private_key = Web3.toHex(private_key)[ 2:] # Convert existing private key to Hex format data = str(private_key).encode( 'utf-8') # Convert Hex key to string and encode into bytes cipher = AES.new(key, AES.MODE_CBC) # Call required AES encryption method ct_bytes = cipher.encrypt(pad( data, AES.block_size)) # Encrypt private key 'data' using AES-256 salt = salt.hex() # Convert salt to hex iv = cipher.iv.hex() # Convert initialization vector to hex ct = ct_bytes.hex() # Convert encrypted private key to hex output = { 'salt': salt, "initialization vector": iv, "encrypted private key": ct } with open(address + '.txt', 'w') as json_file: json.dump(output, json_file) print('Generated wallet:') print(' address: ', address) print() #print('Private key: ', private_key) Only print for testing return 0
0 15 13 ---start--- 1 . 2 10 = 2 . 12 1 = 3 . 1 12 = 4 . 2 7 = 5 . 12 16 = 6 . 1 5 = while True: time.sleep(1) """ print("-" * 50) print("--- tiny-ec ---") field = SubGroup(p=p, g=(dx0, dy0), n=18, h=1) curve = Curve(a=a, b=b, field=field, name='p1707') print('curve:', curve) for k in range(0, 10): p = k * curve.g print(f"{k} * G' = ({p.x}, {p.y})") print("=" * 50) time.sleep(60) """ y^2 = x^3 + 2x + 2 (mod 17) (5,1) -> 6,3 """
from tinyec.ec import SubGroup, Curve import pickle import os from algorithm.utilities import utilities import time field = SubGroup(p=65629, g=(4, 46171), n=65538, h=1) curve = Curve(a=-8, b=31, field=field, name="p65629") encode_map = {} decode_map = {} if os.path.exists("data/encode_map.pickle") and os.path.exists( "data/decode_map.pickle"): encode_map = pickle.load(open("data/encode_map.pickle", "rb")) decode_map = pickle.load(open("data/decode_map.pickle", "rb")) else: for k in range(1, curve.field.n): p = k * curve.g if p.x is None: break encode_map[k] = p decode_map['' + str(p.x) + ',' + str(p.y)] = k pickle.dump(encode_map, open("data/encode_map.pickle", "wb")) pickle.dump(decode_map, open("data/decode_map.pickle", "wb")) # random_k = randint(1, curve.field.n) random_k = 5443 # random_index = randint(1, curve.field.n) random_index = 37347
# antes de executar o código abaixo, é necessário importar # o pacote tinyec no python. para isso, basta # executar o comando abaixo. # # pip install tinyec # importando biblioteca from tinyec.ec import SubGroup, Curve # definir os grupos da ecc field = SubGroup(p=17, g=(15, 13), n=18, h=1) curve = Curve(a=0, b=7, field=field, name='p1707') # exibir a equacao que esta sendo utilizada # curve: "p1707" => y^2 = x^3 + 0x + 7 (mod 17) print('curve:', curve) # loop for k in range(0, 25): p = k * curve.g print(f"{k} * G = ({p.x}, {p.y})")
# pip install tinyec # https://cryptobook.nakov.com/asymmetric-key-ciphers/elliptic-curve-cryptography-ecc from tinyec.ec import SubGroup, Curve from tinyec import registry import secrets field = SubGroup(p=17, g=(15, 13), n=18, h=1) curve = Curve(a=0, b=7, field=field, name='p1707') print('curve:', curve) for k in range(0, 25): p = k * curve.g print(f"{k} * G = ({p.x}, {p.y})") print("-" * 50) field = SubGroup(p=17, g=(5, 9), n=18, h=1) curve = Curve(a=0, b=7, field=field, name='p1707') print('curve:', curve) for k in range(0, 25): p = k * curve.g print(f"{k} * G' = ({p.x}, {p.y})") print("=" * 50) curve = registry.get_curve('secp192r1') print('curve:', curve)