def _process_jwk(self, jwk_dict): if not jwk_dict.get("kty") == "RSA": raise JWKError( "Incorrect key type. Expected: 'RSA', Received: %s" % jwk_dict.get("kty")) e = base64_to_long(jwk_dict.get("e")) n = base64_to_long(jwk_dict.get("n")) if "d" not in jwk_dict: return pyrsa.PublicKey(e=e, n=n) else: d = base64_to_long(jwk_dict.get("d")) extra_params = ["p", "q", "dp", "dq", "qi"] if any(k in jwk_dict for k in extra_params): # Precomputed private key parameters are available. if not all(k in jwk_dict for k in extra_params): # These values must be present when 'p' is according to # Section 6.3.2 of RFC7518, so if they are not we raise # an error. raise JWKError( "Precomputed private key parameters are incomplete.") p = base64_to_long(jwk_dict["p"]) q = base64_to_long(jwk_dict["q"]) return pyrsa.PrivateKey(e=e, n=n, d=d, p=p, q=q) else: p, q = _rsa_recover_prime_factors(n, e, d) return pyrsa.PrivateKey(n=n, e=e, d=d, p=p, q=q)
def _process_jwk(self, jwk_dict): if not jwk_dict.get('kty') == 'RSA': raise JWKError("Incorrect key type. Expected: 'RSA', Received: %s" % jwk_dict.get('kty')) e = base64_to_long(jwk_dict.get('e')) n = base64_to_long(jwk_dict.get('n')) if 'd' not in jwk_dict: return pyrsa.PublicKey(e=e, n=n) else: d = base64_to_long(jwk_dict.get('d')) extra_params = ['p', 'q', 'dp', 'dq', 'qi'] if any(k in jwk_dict for k in extra_params): # Precomputed private key parameters are available. if not all(k in jwk_dict for k in extra_params): # These values must be present when 'p' is according to # Section 6.3.2 of RFC7518, so if they are not we raise # an error. raise JWKError('Precomputed private key parameters are incomplete.') p = base64_to_long(jwk_dict['p']) q = base64_to_long(jwk_dict['q']) return pyrsa.PrivateKey(e=e, n=n, d=d, p=p, q=q) else: p, q = _rsa_recover_prime_factors(n, e, d) return pyrsa.PrivateKey(n=n, e=e, d=d, p=p, q=q)
def press(self): if not (self.login.get() or self.password.get()): messagebox.askretrycancel('Пустое поле', 'Не введен логин и пароль') elif not self.login.get(): messagebox.askretrycancel('Пустое поле', 'Не введен логин') elif not self.password.get(): messagebox.askretrycancel('Пустое поле', 'Не введен пароль') else: with open('privatekey', 'r') as private: priv_key = tuple(int(i) for i in private.readline().split(',')) self.cursor.execute("SELECT USERNAME FROM users") all_data = self.cursor.fetchall() if not self.proverka(all_data, self.login.get(), 'USERNAME'): messagebox.showerror('Ошибка', 'Неправильно введен логин или пароль') else: self.cursor.execute( "SELECT password FROM users WHERE ? = USERNAME", (self.login.get(), )) all_data = self.cursor.fetchone() if self.password.get() == rsa.decrypt( all_data['password'], rsa.PrivateKey(*priv_key)).decode('utf-8'): self.LOGIN.destroy() self.cursor.execute( "SELECT theme FROM Users WHERE ? = USERNAME", (self.login.get(), )) main_window.main_window(self.cursor.fetchone()['theme'], self.login.get()) else: messagebox.showerror( 'Ошибка', 'Неправильно введен логин или пароль')
def get_rsa_priv_from_str(pub): n = int(pub.split(",")[0].split("(")[1]) e = int(pub.split()[1][:-1:]) d = int(pub.split()[2][:-1:]) p = int(pub.split()[3][:-1:]) q = int(pub.split()[4][:-1:]) return rsa.PrivateKey(n, e, d, p, q)
def toDER(self): tbsCertificate = rfc2459.TBSCertificate() tbsCertificate.setComponentByName('version', self.getVersion()) tbsCertificate.setComponentByName('serialNumber', self.getSerialNumber()) tbsCertificate.setComponentByName('signature', self.getSignature()) tbsCertificate.setComponentByName('issuer', self.getIssuer()) tbsCertificate.setComponentByName('validity', self.getValidity()) tbsCertificate.setComponentByName('subject', self.getSubject()) tbsCertificate.setComponentByName('subjectPublicKeyInfo', self.getSubjectPublicKeyInfo()) if self.extensions: extensions = rfc2459.Extensions().subtype(explicitTag=tag.Tag( tag.tagClassContext, tag.tagFormatSimple, 3)) count = 0 for extension in self.extensions: extensions.setComponentByPosition(count, extension) count += 1 tbsCertificate.setComponentByName('extensions', extensions) tbsDER = encoder.encode(tbsCertificate) rsaPrivateKey = rsa.PrivateKey(self.sharedRSA_N, self.sharedRSA_E, self.sharedRSA_D, self.sharedRSA_P, self.sharedRSA_Q) signature = rsa.sign(tbsDER, rsaPrivateKey, 'SHA-256') certificate = rfc2459.Certificate() certificate.setComponentByName('tbsCertificate', tbsCertificate) certificate.setComponentByName('signatureAlgorithm', self.getSignatureAlgorithm()) certificate.setComponentByName( 'signatureValue', byteStringToHexifiedBitString(signature)) return encoder.encode(certificate)
def decrypt_key(self, encrypted_key): n = int(encrypted_key['n']) e = int(encrypted_key['e']) d = int(encrypted_key['d']) p = int(encrypted_key['p']) q = int(encrypted_key['q']) return rsa.PrivateKey(n, e, self.decrypt_message(d), self.decrypt_message(p), self.decrypt_message(q))
def rsa_decrypt(bytes_string, n, e, d, p, q): # 导入rsa库 import rsa.common pri_key = rsa.PrivateKey(n, e, d, p, q) key_length = rsa.common.byte_size(n) if len(bytes_string) % key_length != 0: # 如果数据长度不是key_length的整数倍, 则数据是无效的 return None count = len(bytes_string) // key_length d_cty_bytes = b'' # 分组解密 for i in range(count): start = key_length * i size = key_length content = bytes_string[start: start + size] # rsa 分组 解密 d_crypto = rsa.decrypt(content, pri_key) d_cty_bytes = d_cty_bytes + d_crypto return d_cty_bytes
def check_signature(): try: file = open(path + 'message.txt') message = file.read() file.close() file = open(path + 'signature', 'rb') signature = file.read() file.close() with open(path + "key", "r") as f: n = int(f.readline()) d = int(f.readline()) p = int(f.readline()) q = int(f.readline()) exp1 = int(f.readline()) exp2 = int(f.readline()) coef = int(f.readline()) file.close() hash = get_hash(message) temp_hash = rsa.decrypt( signature, rsa.PrivateKey(n, 65537, d, p, q, exp1, exp2, coef)).decode("utf8") if temp_hash == hash: return True else: return False except Exception as e: print('[Error] Package not exist or damaged!') return None
def decode_message(self, message=None, message_in='msg.encoded.txt', message_out='msg.decoded.txt'): with open(self.key_dir / 'key', 'r') as f: key = f.read()[11:-1].split(',') msg = message try: if msg is None: with open(message_in, 'rb') as f: msg = f.read() except FileNotFoundError: raise MessageNotFoundException() crypto = rsa.decrypt( msg, rsa.PrivateKey(int(key[0]), int(key[1]), int(key[2]), int(key[3]), int(key[4]))) with open(message_out, 'w') as f: f.write(crypto.decode('utf8')) print('[+] Message decoded to', message_in) print('[Decoded Text]', crypto.decode('utf8'))
def import_PrivateKey(self, key): """ Importar la clave privada """ priv_key = str(key) try: if not (priv_key.index('PrivateKey') == 0): raise invalidKeys('No corresponde con la especificación') except ValueError: raise invalidKeys('No se encontraron valores validos que argumenten la especificación') priv_key = priv_key.replace(' ','').replace('PrivateKey(','').replace(')','').split(',') if not (len(priv_key) == 5): raise invalidKeys('Hay demasiados o muy pocos argumentos para que la especificación de la clave privada sea correcta') self.priv_key = rsa.PrivateKey(int(priv_key[0]), int(priv_key[1]), int(priv_key[2]), int(priv_key[3]), int(priv_key[4])) return True
def __load_data(self, username, password): with open(r"user_data\{}.json".format(username), 'r') as f: data = json.load(f) self.password_ = "b7b2ec16d69ed532781d8d4d4cf022ee" self.username = username self.password = password self.password_encr = data['password_encrypted'] self.bankbalance = int( decrypt(data['bankbalance_encrypted'], key=self.password, return_hex=False, key_is_hex=False)) self.assets = [ Asset.decrypt(i, self) for i in data['assets_encrypted'] ] self.block = Block(self) self.blockchain = BlockChain(self) prv_key = tuple_( decrypt(data['private_key'], key=self.password, return_hex=False, key_is_hex=False)) pub_key = tuple_(data['public_key']) self.private_key = rsa.PrivateKey(prv_key[0], prv_key[1], prv_key[2], prv_key[3], prv_key[4]) self.public_key = rsa.PublicKey(pub_key[0], pub_key[1])
def check_sign(block, block_id): if block['index'] == 0: return block base_sign = block['sign'] del block['sign'] str_block = json.dumps(block, separators=(',', ':')) creator = block['creator'] with open(f'C:/Users/wegas/workspace/testTasks/3/Keys/{creator}.key', 'r') as f: denpq = f.read().split('\n') keys = {} for key in denpq: keys[key[0]] = int(key[3:]) priv = rsa.PrivateKey(keys['n'], keys['e'], keys['d'], keys['p'], keys['q']) sign = rsa.sign(str_block.encode(), priv, 'SHA-1').hex() if base_sign != sign: block['sign'] = sign print(block_id, 'sign', block['sign']) return block
def deserialize(data): return (PrivateKey( rsa.PrivateKey(int.from_bytes(data[1:129], byteorder='big'), int.from_bytes(data[129:137], byteorder='big'), int.from_bytes(data[137:265], byteorder='big'), int.from_bytes(data[265:361], byteorder='big'), int.from_bytes(data[361:457], byteorder='big'))), data[457:]) if data[0] else (None, data[1:])
def sign(self, data): """Returns a hexified bit string representing a signature by this key over the specified data. Intended for use with pyasn1.type.univ.BitString""" rsaPrivateKey = rsa.PrivateKey(self.RSA_N, self.RSA_E, self.RSA_D, self.RSA_P, self.RSA_Q) signature = rsa.sign(data, rsaPrivateKey, 'SHA-256') return byteStringToHexifiedBitString(signature)
def decrypto_file(self, file_path): """ :param file_path: file path :return: plain text """ self.d = int(self.d) privatekey = rsa.PrivateKey(self.N, self.e, self.d, self.p, self.q) with open(file_path, "rb") as fp: return rsa.decrypt(fp.read(), privatekey).decode()
def decrypt_text(text): private_key = rsa.PrivateKey( 112498960303803422979651245957017678176394995870040805103294101587080573593391639083204890633266176675619193431853787099141105414422882423667306631770369249723135465658112044512157221802265928432962881804577056072295101819125598383697077060226451710050415188411376031025142998028523529220279991750739514313573, 65537, 105447283710001075273768960860180340154382535076380313665414244875303607966010879308515696884369256557465423094211610047959762645567896675213375280193289259049092936107215782160567594079636645826370084812987772047467355184725660283080559902959834837970395201605225355306389304916421074345038498157674905654849, 54453017540102265780646638375551174180003890177362990355713586730600416440846304363001426226348768572416670612076076652749216088278275907163150413683821572899626257, 2065982114231830387299732653224934901379717480127255306258576080846591437822426986786972962852398835442014904792579660792165834204952404168743189 ) return str((rsa.decrypt(text, private_key)).decode('utf-8'))
def decrypt(self, data, encrypted_blowfish_key, priv_key): privkey = rsa.PrivateKey(1, 3, 5, 7, 9) privkey = privkey.load_pkcs1(priv_key) blowfish_key = rsa.decrypt(encrypted_blowfish_key, privkey) decryptor = Blowfish.new(blowfish_key) msg = self._unpad(decryptor.decrypt(data)) return msg.decode('utf8')
def test_rsa(self): import rsa privateKey = rsa.PrivateKey(68706731939835159529538476419799965655742346573230197443885147162104769051533, 65537, 19061382122008680143523026355567129629292323946827194069036011864529823625833, 57075922549895275552549577057264864809031, 1203777860616660755154882879116047243) message = b'\x80\xbc\xc9\xca?\xf9\xd7\x82YNC\x1a\xb0\xde\xee\xb9\x89\x94\xa7\xf5\xcc\xbb\xde\xd9gc\xfd\x83S\x11wX' self.assertEqual(self.decoder.rsa(privateKey, message), 'hello'.encode())
def __init__(self, rsa_dict): n = int(rsa_dict['n']) e = int(rsa_dict['e']) d = int(rsa_dict['d']) p = int(rsa_dict['p']) q = int(rsa_dict['q']) self.pub_key = rsa.PublicKey(n, e) self.priv_key = rsa.PrivateKey(n, e, d, p, q)
def get_priv_key(self, hash): f = open(hash+'.txt', 'r') keys = f.readline() f.close() keys = json.loads(keys) priv_key = json.loads(keys.get('ck')) priv_key = rsa.PrivateKey(n=priv_key.get('n'), e=priv_key.get('e'), d=priv_key.get('d'), p=priv_key.get('p'), q=priv_key.get('q')) f.close() return priv_key
def collecting_block(self, block_size): block = {} with open(self.hash + '.txt', 'r') as key_file: info = key_file.readline() info = json.loads(info) ok = json.loads(info.get('ok')) ck = json.loads(info.get('ck')) miner_hash = info.get('hash') ok = rsa.PublicKey(e=ok.get('e'), n=ok.get('n')) ck = rsa.PrivateKey(e=ck.get('e'), n=ck.get('n'), d=ck.get('d'), p=ck.get('p'), q=ck.get('q')) tx_for_block = [] tx = [] with open('tx_buffer.txt', 'r') as tx_buffer: header = tx_buffer.readline() for i in range(block_size): row = tx_buffer.readline() if not row: break else: tx.append(json.loads(row)) if not tx: return False else: print(tx) for current_tx in tx: hash_from = current_tx.get('from') ok_from = RSASign.RSASign().find_ok(hash_from) try: print('trans_for_block', current_tx) RSASign.RSASign().verif_sign_trans(current_tx, ok_from) except: print('MAINING: TRANS VERIF -- FAIL') else: tx_for_block.append(json.dumps(current_tx, sort_keys=True)) chain_len = len( os.listdir( 'C:\\Users\\USER\\PycharmProjects\\Blockchain-master\\chain')) block.update({'number': chain_len}) block.update({'tx': tx_for_block}) block.update({'miner_hash': miner_hash}) pre_hash = self.get_prehash() block.update({'pre_hash': pre_hash}) block.update({'nonce': '0'}) block = self.count_nonce(block) block.update({'time': time.time()}) # подписали блок block = RSASign.RSASign().get_sign(block, ck) block.update({'type': "block"}) print('MAINING BLOCK:', block) self.send_block(block) self.delete_proof_transacton(tx_for_block)
def phase_generate_key(): this_pub = 0 this_pri = 0 print("1 or 2") id = input() if(id == '1'): this_pub = rsa.PublicKey(202137387733458537301164105994247647661, 65537) this_pri = rsa.PrivateKey(202137387733458537301164105994247647661, 65537, 56430804674784585731965153685654373665, 181785849768822681379, 1111953367055339759) if(id == '2'): this_pub = rsa.PublicKey(228824876101654018166397806380867770343, 65537) this_pri = rsa.PrivateKey(228824876101654018166397806380867770343, 65537, 133415129479840421135250387360768543713, 213929244404772581873, 1069628777207746391) # (this_pub, this_pri) = rsa.newkeys(128) print("Public: ", this_pub) print("Private: ", this_pri) return (this_pub, this_pri)
def decrypt(self, ctext): """ Return the PKCS#1 RSA decryption of "ctext". "ctext" is an even-length hex string and the output is a plain string. """ ctext = bytearray([int(x, 16) for x in re.findall(r'\w\w', ctext)]) prikey = rsa.PrivateKey(self.n, self.e, self.d, self.p, self.q) return rsa.decrypt(ctext, prikey).decode("utf-8")
def decrypt(hashed: str) -> str: key = rsa.PrivateKey(*map(int, readFile(os.path.join("server", "key")).split())) try: message = str(rsa.decrypt(bytes.fromhex(hashed), key))[2:-1] except rsa.pkcs1.DecryptionError: raise SecurityError(ForgeCookieMessage) except ValueError: raise SecurityError(ForgeCookieMessage) return message
class SysConst(Enum): """Класс системных констант""" ENCODING = 'utf-8' PUBLICKEY = rsa.PublicKey(21398861240354752897359515597515368555906324350098607159605742192139763336816841534991594943674409937742947439898488100771707536253244593501487475151941309944866808440286441104426257559940643240785179943693486638873343326089853455397326780230048332618343922116099430613175805015460623055858358640655087822382203101617404330725227594286958375316603338394181379698613732417282925757803608125628591300696388888365958495657592112101446763219305227850570264571018723964337074244339922479825427958129030532723153087028647966872933110500652043487320817768343706784400594743366819730786404206933925058381702078550560479250891, 65537) PRIVATEKEY = rsa.PrivateKey( 21398861240354752897359515597515368555906324350098607159605742192139763336816841534991594943674409937742947439898488100771707536253244593501487475151941309944866808440286441104426257559940643240785179943693486638873343326089853455397326780230048332618343922116099430613175805015460623055858358640655087822382203101617404330725227594286958375316603338394181379698613732417282925757803608125628591300696388888365958495657592112101446763219305227850570264571018723964337074244339922479825427958129030532723153087028647966872933110500652043487320817768343706784400594743366819730786404206933925058381702078550560479250891, 65537, 755557393688769675213847431109915968664528961443584188585496550538038243456279221080771941035790234462016576528145955188454327157025924124730183217138291212787002681398642365620067442722472015184962790327703863197169788921859726502424800791191721343345710602814502989744553653749422185196892928209646476618837331621422755239997513016548884946907780237554065826576039015559213818266461010000595424743488929462688728697555098148543094475452745192864376218199840868794345382947712409718186746345470971173085254662852396459919199865628960272823739565549718943776516397471305876360938303487982725124288751934000442110721, 3228201555865204331752711611707221752136691332832851137857287809857601237190779134663403069149498619614545211722821985125351406891050623801512841526115710975782832801733040787757121709542611630635716161794060249130341693973897231882058688228579769954708606509788725313552122486198270447910729301978696968066747124704606885589899, 6628725273202326760228013631984132851704811269394768287188498058548097869835714737482104906702046916585268867888496259077568237668150325164648575314066166518663915936037250848434411706713783048901820027592943627664320200892090192420833907524222049052505676047741549057171057779148505238209)
def __init__(self, blockchain, private_key=None): if not private_key: self.public_key, self.__private_key = rsa.newkeys(512) else: self.public_key = rsa.PublicKey(private_key[0], private_key[1]) self.__private_key = rsa.PrivateKey(private_key[0], private_key[1], private_key[2], private_key[3], private_key[4]) self.address = hash_it(pub_to_json(self.public_key)) self.blockchain = blockchain
def dec(): file = input("Write the filename: ") file_key = input("Write the filename with key:") with open(file_key, "r") as k: pr_key = k.read().split() n, e, d, p, q = pr_key with open(file, "rb") as r: read = r.read() message = rsa.decrypt(read, rsa.PrivateKey(int(n), int(e), int(d), int(p), int(q))) print("\n[*] Decrypted text:\n\n[text] << " + str(message.decode("utf8")) + "\n")
def genRsaKeys(): p, q = getPrimes(1024) e = GLOBAL_E phi = (p - 1) * (q - 1) d = modularInverse(e, phi) public_key = rsa.PublicKey(p * q, e) private_key = rsa.PrivateKey(p * q, e, d, p, q) return public_key, private_key
def decode_key(encoded): "Decode environment variable to url and key." tmp_byte = encoded.encode('utf8') tmp_b64e = base64.b64decode(tmp_byte) tmp_zlib = zlib.decompress(tmp_b64e) tmp_utf8 = tmp_zlib.decode('utf8') tmp = json.loads(tmp_utf8) key = rsa.PrivateKey(tmp['n'], tmp['e'], tmp['d'], tmp['p'], tmp['q']) key_size = tmp['s'] digest = _hash_rsa_n(key, key_size) return tmp['u'], tmp['s'], digest, key
def decode_privkey(text, password): ''' Decode private key from text. ''' keystring = aes.decryptData(aes_key(password), b64decode(text)) k = keystring.split(":") if not k.pop(0) == "CHECK": print("Incorrect password to decode private key. Exiting.") exit() ks = map(long, k) return rsa.PrivateKey(ks[0], ks[1], ks[2], ks[3], ks[4])