def pack_license_key(data, privkey_args): """ Pack a dictionary of license key data to a string. You typically call this function on a server, when a user purchases a license. Eg.: lk_contents = pack_license_key({'email': '*****@*****.**'}, ...) The parameter `privkey_args` is a dictionary containing values for the RSA fields "n", "e", "d", "p" and "q". You can generate it with fbs's command `init_licensing`. The resulting string is signed to prevent the end user from changing it. Use the function `unpack_license_key` below to reconstruct `data` from it. This also verifies that the string was not tampered with. This function has two non-obvious caveats: 1) It does not obfuscate the data. If `data` contains "key": "value", then "key": "value" is also visible in the resulting string. 2) Calling this function twice with the same arguments will result in the same string. This may be undesirable when you generate multiple license keys for the same user. A simple workaround for this is to add a unique parameter to `data`, such as the current timestamp. """ data_bytes = _dumpb(data) signature = rsa.sign(data_bytes, PrivateKey(**privkey_args), 'SHA-1') result = dict(data) if 'key' in data: raise ValueError('Data must not contain an element called "key"') result['key'] = b64encode(signature).decode('ascii') return json.dumps(result)
def get_client_pri_key(): return PrivateKey( 9659409811222239424053139659514350094343427389834135540932282496665611583618159590834922783558917852795055561382877564364710885749628173307757081925597489, 65537, 1350522179840843795758104867481422553892744940614464866587767284388162395131790899554868688522906461439000088568816762804091645889133667242002096698398417, 5559425529932599305598725281545023902835884959815769154010890312251665313855301237, 1737483443067065782717045867372208780049132259225788701387959997763307597 )
def from_key_str_get_obj(s_key): # 先把 \n 去掉再获取 args = [ int(x) for x in s_key.split("\n")[1].split(RsaCrypto.SPLIT_CODE) ] if len(args) == 2: return PublicKey(*args) if len(args) == 5: return PrivateKey(*args) raise EOFError('长度异常')
def requester(self, encrypted_hash_val): private_key = open('private_key_rsa.txt', 'r').read().split(',') private_key = PrivateKey(int(private_key[0]), int(private_key[1]), int(private_key[2]), int(private_key[3]), int(private_key[4])) try: hash_val = decrypt(encrypted_hash_val, private_key) except: print('Not an Authentic User') """If an error is raised here then the connection should be disconnected""" # code for disconnecting service and prompting user of failure """ 'hash' to be sent to verifier through server and verifier checks data""" """ if data is same as sent data then authentication is sucessfull"""
def getPrivateKeyFromPS(path) -> PrivateKey: from source.util.ToolsFuc import StrToInt from source.core.const.Const import NUM_DICT_M file = open(path, 'rb') byte = file.read() file.close() pks = byte.decode('utf-8') pko = json.loads(pks) return PrivateKey(StrToInt(pko[0], NUM_DICT_M), StrToInt(pko[1], NUM_DICT_M), StrToInt(pko[2], NUM_DICT_M), StrToInt(pko[3], NUM_DICT_M), StrToInt(pko[4], NUM_DICT_M))
def miner_Side(self): file_obj = open('miner_private_key.txt', 'r') arr = file_obj.read().split(',') file_obj.close() p_key = PrivateKey(int(arr[0]), int(arr[1]), int(arr[2]), int(arr[3]), int(arr[4])) try: self.block_address = int(decrypt(self.block_address, p_key)) except: print('Error raised disconnecting the service') """If an error is raised here then the connection should be disconnected""" #code for disconnecting service and prompting user of failure self.req_pu_key = BlockChain.obj.blockchain[ self.block_address]['auth_public_key'].split(',') self.verifier()
def __set_privkey(self, priv_key): """ 设置私钥 :param priv_key: :return: """ if self._key_is_hex: b_str = a2b_hex(priv_key) priv_key = b64encode(b_str) pkl = self._convert_key(priv_key, is_pubkey=False) n = int(pkl[0], 16) e = int(pkl[1], 16) d = int(pkl[2], 16) p = int(pkl[3], 16) q = int(pkl[4], 16) self.__priv_key = PrivateKey(n, e, d, p, q)
def loads_privatekey_from_file(file_path): n, e, d, p, q = RsaCrypto.loads_strs_from_file(file_path).split( "\n")[1].split(RsaCrypto.SPLIT_CODE) return PrivateKey(*[int(x) for x in [n, e, d, p, q]])
import pickle, os from rsa import PrivateKey, sign, verify if __name__ == "__main__": master_tup = pickle.load(open("masterKey.pickle", "rb")) master_key = PrivateKey(*master_tup) if os.path.exists("to_sign"): for key in os.listdir("." + os.sep + "to_sign"): tup = pickle.load(open("to_sign" + os.sep + key, "rb")) signed = sign(str(tup), master_key, "SHA-256") print("Key " + str(key) + " signed.") print("Sig valid? " + str(verify(str(tup), signed, master_key))) if not os.path.exists("signed"): os.mkdir("signed") pickle.dump(signed, open("signed" + os.sep + key, "wb"), 0) def exportProof(priv): tup = (priv.n, priv.e) proof = rsa.sign(str(tup), priv, "SHA-256") print("Post this proof somewhere associated with your") print("organization, to verify your identity.") print("Send that link to [email protected]") return (tup, proof)
def pythonify_private_key(self, key): try: return PrivateKey(key[0], key[1], key[2], key[3], key[4]) except: return key
def __init__(self): self.blocked_peers = [] self.synchronizing = False self.write_new_peer("http://Eggcoin.generationxcode.repl.co") self.escape = False self.mine_stat = False self.difficulty = 4 self.read_personal_data() self.current_transactions = [] self.nonce = 0 my_key = 140388580907465133105915434450383793485035986871045024199643410432339156186579924298083425595522266259072335465721683558239322246445355757776569418174479148327499466879142197016031265888167897049284395859778857155905614260161061241649905878412678823961156997654382749170224692738793588409591092859914764702383 keys = self.read_keys() self.public_key = PublicKey(keys["public_key"][0], keys["public_key"][1]) self.private_key = PrivateKey(keys["private_key"][0], keys["private_key"][1], keys["private_key"][2], keys["private_key"][3], keys["private_key"][4]) if (Block_chain.objects.all().count() > 0) or ( (int(keys['public_key'][0]) == my_key) and (self.personal_data['username'] != "generationxcode")): keys = self.read_keys() self.public_key = PublicKey(keys["public_key"][0], keys["public_key"][1]) self.private_key = PrivateKey(keys["private_key"][0], keys["private_key"][1], keys["private_key"][2], keys["private_key"][3], keys["private_key"][4]) self.current_transactions = self.read_from_blockchain_latest( )["transactions"] self.unspent_coins = self.read_unspent_coins() self.blockchain_checking() else: self.chain = [] print("hey") self.chain.append({ "index": 1, "prev_hash": self.hash_txt("egg"), "nonce": None, "timestamp": time.time(), "transactions": [], "message": "hi guys, this is an academic project, just to learn about blockchains. Have fun with it!" }) self.unspent_coins = [] (self.public_key, self.private_key) = rsa.newkeys(1024) print("keys synthesized") self.current_transactions = self.first_transaction_in_block( self.chain[-1]) print("transaction made") self.write_keys({ "public_key": [self.public_key.n, self.public_key.e], "private_key": [ self.private_key.n, self.private_key.e, self.private_key.d, self.private_key.p, self.private_key.q ] }) print("keys written") self.chain[-1]['transactions'] = self.current_transactions self.log_transactions({ "index": 1, "prev_hash": self.hash_txt("egg"), "nonce": None, "transactions": self.current_transactions, "message": "hi guys, this is an academic project, just to learn about blockchains. Have fun with it!" }) print("transactions logged") self.write_to_blockchain(self.chain[-1]) print("blockchain logged") self.peers = [] self.personal_data = {} self.read_peers() self.read_peers() self.ping_all_peers() self.blockchain_checking()
import re from random import choice from string import ascii_letters import rsa as rsa from rsa import PublicKey, PrivateKey # Публичный ключ для RSA Public_Rsa_key = PublicKey( 8528460616836763783897561956462105596914954006532265911712311683380482486102630624564799783376409979607899614788126661049746076325444875429188307035856253, 65537) Private_Key = PrivateKey( 8528460616836763783897561956462105596914954006532265911712311683380482486102630624564799783376409979607899614788126661049746076325444875429188307035856253, 65537, 4717284852225959185899364037440702624291119256859402159079165944772304041129781901475469050294402307285587354096391573497657995816080121983368308792273473, 4902009478631967923449653186935907234780556621710806720657636519983995645904895561, 1739788683398639716463012009651288258585394195066471998081771727246292373) # Функция создания пути и его шифрования def Get_Path(): Patch = '' Patch += (''.join(choice(ascii_letters) for i in range(35))) Patch_as_bytes = str.encode(Patch) print(Patch) crypto = rsa.encrypt(Patch_as_bytes, Public_Rsa_key) return Patch, crypto
def from_strp(a): a = a.split("_") return PrivateKey(int(a[0]), int(a[1]), int(a[2]), int(a[3]), int(a[4]))