def check_signature(public_key, z, signature, curve: Curve=curve_P256): u1 = (inverse_of(signature[1], curve.n) * z) % curve.n u2 = (inverse_of(signature[1], curve.n) * signature[0]) % curve.n u1G = multiply(curve.g, u1) u2Q = multiply(public_key, u2) P = points_sum(u1G, u2Q) _r = P.x % curve.n if signature[0] == _r: return 1 else: return 0
def decrypt(private_key, s, T: Point, c_text, curve: Curve =curve_P256): l = 128 U = multiply(T, private_key) bytes_u_x_ = bytes(str(U.x)[:8], 'utf-8') kdf_T_U = int.from_bytes(PBKDF2(str(T.x), bytes_u_x_).read(int(l / 8)), 'big') r = s ^ kdf_T_U keylen = 256 _t_len = keylen + 128 len_ = (keylen + _t_len) / 8 pre_key = PBKDF2(str(r), 'salt').read(int(len_)) t_ = int.from_bytes(pre_key, 'big') >> keylen K = int(bin(int.from_bytes(pre_key, 'big') << _t_len)[2:keylen + 2], 2) t = t_ % curve.n T_ = multiply(curve.g, t, curve.a) if T_.x == T.x and T_.y == T.y: obj = AES.new(str(K)[:32], AES.MODE_CBC, "ABCDEFGHABCDEFGH") return obj.decrypt(c_text) else: return 'incorrect'
def encrypt(public_key: Point, msg, curve: Curve =curve_P256): l = 128 r = int(bin(get_random_k())[2:l+2], 2) keylen = 256 _t_len = keylen + l len_ = (keylen + _t_len) / 8 pre_key = PBKDF2(str(r), 'salt').read(int(len_)) t_ = int.from_bytes(pre_key, 'big') >> keylen K = int(bin(int.from_bytes(pre_key, 'big') << _t_len)[2:keylen + 2], 2) t = t_ % curve.n T = multiply(curve.g, t, curve.a) U = multiply(public_key, t, curve.a) bytes_u_x_ = bytes(str(U.x)[:8], 'utf-8') kdf_T_U = int.from_bytes(PBKDF2(str(T.x), bytes_u_x_).read(int(l / 8)), 'big') s = r ^ kdf_T_U obj = AES.new(str(K)[:32], AES.MODE_CBC, "ABCDEFGHABCDEFGH") _n = 16 - msg.__len__() % 16 rand_str = ''.join(' ' for i in range(_n)) c_text = obj.encrypt(msg+rand_str) return s, T, c_text
def get_signature(z, private_key, curve: Curve=curve_P256): s = r = k = 0 _r = lambda __k: multiply(curve.g, k).x % curve.n while s == 0: k = get_random_k() while r == 0: r = _r(k) _k_ = inverse_of(k, curve.n) what = (z + r * private_key) s = (_k_ * what) % curve.n return r, s
def get_public_key(private_key, curve: Curve=curve_P256): return multiply(curve.g, private_key, curve.a)
def get_secret(private_key, public_key: Point, curve: Curve=curve_P256): return multiply(public_key, private_key, curve.a)