def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0): if not d: self.rsa = RSA.construct((compatLong(n), compatLong(e))) else: self.rsa = RSA.construct((compatLong(n), compatLong(e), compatLong(d), compatLong(p), compatLong(q)))
def construct(self, mod, exp, d=None, p=None, q=None, u=None): if d and p and q and u: self.obj = RSA.construct((mod, exp, d, p, q, u)) else: self.obj = RSA.construct((mod, exp)) self.mod = self.obj.n self.exp = self.obj.e
def __setstate__(self,state): if state["priv_exponent"] is not None: state["_key"] = _RSA.construct((state["modulus"], state["pub_exponent"], state["priv_exponent"])) else: state["_key"] = _RSA.construct((state["modulus"], state["pub_exponent"])), super(RSAKey,self).__setstate__(state)
def search(K, Kp, Kq, check_level, break_step): max_step = 0 cands = [0] for step in range(1, break_step + 1): #print " ", step, "( max =", max_step, ")" max_step = max(step, max_step) mod = 1 << (4 * step) mask = mod - 1 cands_next = [] for p, new_digit in product(cands, p_ranges[-step]): pval = (new_digit << ((step - 1) * 4)) | p if check_level >= 1: qval = solve_linear(pval, N & mask, mod) if qval is None or not check_val(qval, mask, qmask_msk, qmask_val): continue if check_level >= 2: val = solve_linear(E, 1 + K * (N - pval - qval + 1), mod) if val is None or not check_val(val, mask, dmask_msk, dmask_val): continue if check_level >= 3: val = solve_linear(E, 1 + Kp * (pval - 1), mod) if val is None or not check_val(val, mask, dpmask_msk, dpmask_val): continue if check_level >= 4: val = solve_linear(E, 1 + Kq * (qval - 1), mod) if val is None or not check_val(val, mask, dqmask_msk, dqmask_val): continue if pval * qval == N: print "Kq =", Kq print "pwned" print "p =", pval print "q =", qval p = pval q = qval d = invmod(E, (p - 1) * (q - 1)) coef = invmod(p, q) from Crypto.PublicKey import RSA print RSA.construct(map(long, (N, E, d, p, q, coef))).exportKey() quit() cands_next.append(pval) if not cands_next: return False cands = cands_next return True
def set_RSAobj(n,e,d=None,p=None,q=None): if n != None and e != None and d == None and p == None and q == None: key = RSA.construct((n, e)) elif n != None and e != None and d != None and p == None and q == None: p, q = RecoverPrimeFactors(n, e, d) key = RSA.construct((n, e, d, p, q)) elif n != None and e != None and d != None and p != None and q == None: key = RSA.construct((n, e, d, p, n//p)) elif n != None and e != None and d != None and p != None and q != None: key = RSA.construct((n, e, d, p, q)) return key
def set_RSAobj(n,e,d=None,p=None,q=None): if n != None and e != None and d == None and p == None and q == None: key = RSA.construct((n, e)) elif n != None and e != None and d != None and p == None and q == None: key = RSA.construct((n, e, d)) elif n != None and e != None and d != None and p != None and q == None: key = RSA.construct((n, e, d, p)) elif n != None and e != None and d != None and p != None and q != None: key = RSA.construct((n, e, d, p, q)) return key
def genkey(N = 1024): p = getTwinPrime(N) q = getTwinPrime(N) n1 = p*q n2 = (p+2)*(q+2) e = long(65537) d1 = inverse(e, (p-1)*(q-1)) d2 = inverse(e, (p+1)*(q+1)) key1 = RSA.construct((n1, e, d1)) key2 = RSA.construct((n2, e, d2)) if n1 < n2: return (key1, key2) else: return (key2, key1)
def setUp(self): self.keys = {} for key, cert in KEY_FILE_PAIRS: with open(key, "r") as f: data = f.read() dict = rsa_pem.parse(data) t = rsa_pem.dict_to_tuple(dict) self.keys[key] = RSA.construct(t) with open(cert, "r") as f: data = f.read() dict = x509_pem.parse(data) t = x509_pem.dict_to_tuple(dict) self.keys[cert] = RSA.construct(t)
def keyObject(self): """ A C{Crypto.PublicKey} object similar to this key. As PyCrypto is no longer used for the underlying operations, this property should be avoided. """ # Lazy import to have PyCrypto as a soft dependency. from Crypto.PublicKey import DSA, RSA keyObject = None keyType = self.type() keyData = self.data() isPublic = self.isPublic() if keyType == 'RSA': if isPublic: keyObject = RSA.construct(( keyData['n'], long(keyData['e']), )) else: keyObject = RSA.construct(( keyData['n'], long(keyData['e']), keyData['d'], keyData['p'], keyData['q'], keyData['u'], )) elif keyType == 'DSA': if isPublic: keyObject = DSA.construct(( keyData['y'], keyData['g'], keyData['p'], keyData['q'], )) else: keyObject = DSA.construct(( keyData['y'], keyData['g'], keyData['p'], keyData['q'], keyData['x'], )) else: raise BadKeyError('Unsupported key type.') return keyObject
def Read(key): """ Reads a RSA private key from a JSON string representation of it. @param key: a JSON representation of a RSA private key @type key: string @return: a RSA private key @rtype: L{RsaPrivateKey} """ rsa = json.loads(key) pub = RsaPublicKey.Read(json.dumps(rsa['publicKey'])) params = {'privateExponent': util.Base64WSDecode(rsa['privateExponent']), 'primeP': util.Base64WSDecode(rsa['primeP']), 'primeQ': util.Base64WSDecode(rsa['primeQ']), 'primeExponentP': util.Base64WSDecode(rsa['primeExponentP']), 'primeExponentQ': util.Base64WSDecode(rsa['primeExponentQ']), 'crtCoefficient': util.Base64WSDecode(rsa['crtCoefficient']) } key = RSA.construct((util.BytesToLong(pub.params['modulus']), util.BytesToLong(pub.params['publicExponent']), util.BytesToLong(params['privateExponent']), util.BytesToLong(params['primeQ']), util.BytesToLong(params['primeP']), util.BytesToLong(params['crtCoefficient']))) return RsaPrivateKey(params, pub, key, rsa['size'])
def get_encrypted_password(password, rsa_mod, pub_exp): """ Encrypts a Steam password for web login using RSA with PKCS1_v1_5. Returns the base64 encoded ciphertext since that's what Steam's login endpoint wants. """ public_key = RSA.construct((rsa_mod, pub_exp)) cipher = PKCS1_v1_5.new(public_key) ciphertext = cipher.encrypt(bytes(password, 'utf_8')) return base64.b64encode(ciphertext)
def __generate(self, keydata): ''' Generate the pycrypto rsa object ''' if keydata: if 'components' not in keydata: raise ValueError('Invalid keydata, no components') key = RSA.construct(keydata['components']) if key.has_private(): self.priv = key self.pub = key.publickey() self.sign_key = PKCS1_PSS.new(self.priv) self.verify_key = PKCS1_PSS.new(self.pub) self.decrypter = PKCS1_OAEP.new(self.priv) else: self.pub = key self.verify_key = PKCS1_PSS.new(self.pub) self.keydata = keydata else: self.priv = self._gen_key() self.pub = self.priv.publickey() self.sign_key = PKCS1_PSS.new(self.priv) self.verify_key = PKCS1_PSS.new(self.pub) self.keydata = self._gen_keydata(self.priv) self.decrypter = PKCS1_OAEP.new(self.priv) self.encrypter = PKCS1_OAEP.new(self.pub) self.max_msg_size = self.get_max_msg_size() self.enc_chunk_size = self.get_enc_chunk_size()
def deserialize(self): if self.n and self.e: e = base64_to_long(str(self.e)) n = base64_to_long(str(self.n)) if self.d: d = base64_to_long(str(self.d)) self.key = RSA.construct((n, e, d)) else: self.key = RSA.construct((n, e)) elif self.x5c: if self.x5t: # verify the cert pass cert = "\n".join([PREFIX, str(self.x5c[0]), POSTFIX]) self.key = import_rsa_key(cert) if len(self.x5c) > 1: # verify chain pass
def _fromString_PRIVATE_LSH(Class, data): """ Return a private key corresponding to this LSH private key string. The LSH private key string format is:: <s-expression: ('private-key', (<key type>, (<name>, <value>)+))> The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e, d, p, q. The names for a DSA (key type 'dsa') key are: y, g, p, q, x. @type data: C{str} @return: a {Crypto.PublicKey.pubkey.pubkey} object @raises BadKeyError: if the key type is unknown """ sexp = sexpy.parse(data) assert sexp[0] == 'private-key' kd = {} for name, data in sexp[1][1:]: kd[name] = common.getMP(common.NS(data))[0] if sexp[1][0] == 'dsa': assert len(kd) == 5, len(kd) return Class(DSA.construct((kd['y'], kd['g'], kd['p'], kd['q'], kd['x']))) elif sexp[1][0] == 'rsa-pkcs1': assert len(kd) == 8, len(kd) if kd['p'] > kd['q']: # make p smaller than q kd['p'], kd['q'] = kd['q'], kd['p'] return Class(RSA.construct((kd['n'], kd['e'], kd['d'], kd['p'], kd['q']))) else: raise BadKeyError('unknown lsh key type %s' % sexp[1][0])
def _fromString_BLOB(Class, blob): """ Return a public key object corresponding to this public key blob. The format of a RSA public key blob is:: string 'ssh-rsa' integer e integer n The format of a DSA public key blob is:: string 'ssh-dss' integer p integer q integer g integer y @type blob: C{str} @return: a C{Crypto.PublicKey.pubkey.pubkey} object @raises BadKeyError: if the key type (the first string) is unknown. """ keyType, rest = common.getNS(blob) if keyType == 'ssh-rsa': e, n, rest = common.getMP(rest, 2) return Class(RSA.construct((n, e))) elif keyType == 'ssh-dss': p, q, g, y, rest = common.getMP(rest, 4) return Class(DSA.construct((y, g, p, q))) else: raise BadKeyError('unknown blob type: %s' % keyType)
def add_fips_tests(cls): files = ("SigGen15_186-2.txt", "SigGen15_186-3.txt") for file_name in files: file_tv = open_fips_test_file("PKCS1-v1.5", file_name) sections = load_test_vector(file_tv, ('SHAAlg', )) modulus = None private_key = None for mod_size, test_vectors in sections.iteritems(): for test_vector in test_vectors: # The modulus for all subsequent test vectors appears # in a single line if len(test_vector) == 1: modulus = test_vector['n'] continue # Exponents appear in two lines if len(test_vector) == 2: test_vector['n'] = modulus triplet = [bytes_to_long(test_vector[x]) for x in ('n', 'e', 'd')] private_key = RSA.construct(triplet, consistency_check=False) continue hashmod = load_hash_by_name(test_vector['SHAAlg']) cls.add_test(hashmod, test_vector['Msg'], private_key, test_vector['S'])
def _Dynamic_SignForApp(self, request, response): """Implementation of AppIdentityService::SignForApp.""" bytes_to_sign = request.bytes_to_sign() if RSA_LIB_INSTALLED: signature_bytes = rsa.pkcs1.sign( bytes_to_sign, rsa.key.PrivateKey(N, E, D, 3, 5), 'SHA-256') elif CRYPTO_LIB_INSTALLED: rsa_obj = RSA.construct((N, E, D)) hash_obj = SHA256.new() hash_obj.update(bytes_to_sign) padding_length = MODULUS_BYTES - LEN_OF_PREFIX - LENGTH_OF_SHA256_HASH - 3 emsa = (HEADER1 + (PADDING * padding_length) + HEADER2 + PREFIX + hash_obj.hexdigest()) sig = rsa_obj.sign(binascii.a2b_hex(emsa), '') signature_bytes = number.long_to_bytes(sig[0]) else: raise NotImplementedError("""Unable to import the pycrypto module, SignForApp is disabled.""") response.set_signature_bytes(signature_bytes) response.set_key_name(SIGNING_KEY_NAME)
def fermat_factor_attack(ciphertexts): options = dict(feathermodules.current_options) options = prepare_options(options, ciphertexts) if options == False: print '[*] Could not process options.' return False answers = [] for ciphertext in ciphertexts: try: key = RSA.importKey(ciphertext) if key.has_private(): continue else: modulus = key.n exponent = key.e except: continue factors = ca.fermat_factor(modulus, minutes=options['minutes_to_wait'], verbose=True) if factors[0] != 1: answers.append( (modulus, exponent, ca.derive_d_from_pqe(factors[0],factors[1],exponent)) ) for answer in answers: key = RSA.construct(answer) print "Found private key:\n%s" % key.exportKey() return ''
def login(self): password_aes = prepare_key(str_to_a32(self.password)) del self.password uh = stringhash(self.email.lower(), password_aes) res = self.api_req({'a': 'us', 'user': self.email, 'uh': uh}) enc_master_key = base64_to_a32(res['k']) self.master_key = decrypt_key(enc_master_key, password_aes) if 'tsid' in res: tsid = base64urldecode(res['tsid']) if a32_to_str(encrypt_key(str_to_a32(tsid[:16]), self.master_key)) == tsid[-16:]: self.sid = res['tsid'] elif 'csid' in res: enc_rsa_priv_key = base64_to_a32(res['privk']) rsa_priv_key = decrypt_key(enc_rsa_priv_key, self.master_key) privk = a32_to_str(rsa_priv_key) self.rsa_priv_key = [0, 0, 0, 0] for i in xrange(4): l = ((ord(privk[0]) * 256 + ord(privk[1]) + 7) / 8) + 2 self.rsa_priv_key[i] = mpi2int(privk[:l]) privk = privk[l:] enc_sid = mpi2int(base64urldecode(res['csid'])) decrypter = RSA.construct((self.rsa_priv_key[0] * self.rsa_priv_key[1], 0L, self.rsa_priv_key[2], self.rsa_priv_key[0], self.rsa_priv_key[1])) sid = '%x' % decrypter.key._decrypt(enc_sid) sid = binascii.unhexlify('0' + sid if len(sid) % 2 else sid) self.sid = base64urlencode(sid[:43])
def _login_process(self, resp, password): encrypted_master_key = base64_to_a32(resp['k']) self.master_key = decrypt_key(encrypted_master_key, password) if 'tsid' in resp: tsid = base64_url_decode(resp['tsid']) key_encrypted = a32_to_str( encrypt_key(str_to_a32(tsid[:16]), self.master_key)) if key_encrypted == tsid[-16:]: self.sid = resp['tsid'] elif 'csid' in resp: encrypted_rsa_private_key = base64_to_a32(resp['privk']) rsa_private_key = decrypt_key(encrypted_rsa_private_key, self.master_key) private_key = a32_to_str(rsa_private_key) self.rsa_private_key = [0, 0, 0, 0] for i in range(4): l = ((ord(private_key[0]) * 256 + ord(private_key[1]) + 7) / 8) + 2 self.rsa_private_key[i] = mpi_to_int(private_key[:l]) private_key = private_key[l:] encrypted_sid = mpi_to_int(base64_url_decode(resp['csid'])) rsa_decrypter = RSA.construct( (self.rsa_private_key[0] * self.rsa_private_key[1], 0L, self.rsa_private_key[2], self.rsa_private_key[0], self.rsa_private_key[1])) sid = '%x' % rsa_decrypter.key._decrypt(encrypted_sid) sid = binascii.unhexlify('0' + sid if len(sid) % 2 else sid) self.sid = base64_url_encode(sid[:43])
def _login_common(self, res, password): if res in (-2, -9): raise MegaIncorrectPasswordExcetion("Incorrect e-mail and/or password.") enc_master_key = base64_to_a32(res['k']) self.master_key = decrypt_key(enc_master_key, password) if 'tsid' in res: tsid = base64urldecode(res['tsid']) key_encrypted = a32_to_str( encrypt_key(str_to_a32(tsid[:16]), self.master_key)) if key_encrypted == tsid[-16:]: self.sid = res['tsid'] elif 'csid' in res: enc_rsa_priv_key = base64_to_a32(res['privk']) rsa_priv_key = decrypt_key(enc_rsa_priv_key, self.master_key) privk = a32_to_str(rsa_priv_key) self.rsa_priv_key = [0, 0, 0, 0] for i in xrange(4): l = ((ord(privk[0]) * 256 + ord(privk[1]) + 7) / 8) + 2 self.rsa_priv_key[i] = mpi2int(privk[:l]) privk = privk[l:] enc_sid = mpi2int(base64urldecode(res['csid'])) decrypter = RSA.construct( (self.rsa_priv_key[0] * self.rsa_priv_key[1], 0L, self.rsa_priv_key[2], self.rsa_priv_key[0], self.rsa_priv_key[1])) sid = '%x' % decrypter.key._decrypt(enc_sid) sid = binascii.unhexlify('0' + sid if len(sid) % 2 else sid) self.sid = base64urlencode(sid[:43])
def _private_key(self): key = self.__private_key if not key: self.__private_key = key = RSA.construct((int(self.n), int(self.e), int(self.d))) return key
def _public_key(self): key = self.__public_key if not key: self.__public_key = key = RSA.construct((int(self.n), int(self.e))) return key
def import_publickeyblob(cls, data): rsapubkey = RSAPUBKEY._make(RSAPUBKEY_s.unpack_from(data)) assert rsapubkey.magic == RSAPUBKEY_MAGIC bitlen8 = rsapubkey.bitlen // 8 modulus = bytes_to_long(data[12:12 + bitlen8][::-1]) r = RSA.construct((modulus, long(rsapubkey.pubexp))) return cls(r)
def strtoprivkey(data, password): kind = data[0][11: 14] if data[1].startswith('Proc-Type: 4,ENCRYPTED'): # encrypted key if not password: raise BadKeyPassword("password required") enc_type, salt = data[2].split(": ")[1].split(",") salt = unhexlify(salt.strip()) b64Data = base64.decodestring(''.join(data[4:-1])) if enc_type == "DES-EDE3-CBC": key = get_key_data(salt, password, 24) keyData = DES3.new(key, DES3.MODE_CBC, salt).decrypt(b64Data) elif enc_type == "AES-128-CBC": key = get_key_data(salt, password, 16) keyData = AES.new(key, AES.MODE_CBC, salt).decrypt(b64Data) else: raise BadKeyError("unknown encryption") removeLen = ord(keyData[-1]) keyData = keyData[:-removeLen] else: keyData = base64.decodestring(''.join(data[1:-1])) decodedKey = asn1parse(keyData) if isinstance(decodedKey[0], list): decodedKey = decodedKey[0] # this happens with encrypted keys if kind == 'RSA': n, e, d, p, q = decodedKey[1:6] return RSA.construct((n, e, d, p, q)) elif kind == 'DSA': p, q, g, y, x = decodedKey[1: 6] return DSA.construct((y, g, p, q, x))
def strtoprivkey(data, passphrase): kind = data[0][11:14] if data[1].startswith("Proc-Type: 4,ENCRYPTED"): # encrypted key ivdata = data[2].split(",")[1][:-1] iv = "".join([chr(int(ivdata[i : i + 2], 16)) for i in range(0, len(ivdata), 2)]) if not passphrase: raise BadKeyError, "encrypted key with no passphrase" ba = md5(passphrase + iv).digest() bb = md5(ba + passphrase + iv).digest() decKey = (ba + bb)[:24] b64Data = base64.decodestring("".join(data[4:-1])) keyData = DES3.new(decKey, DES3.MODE_CBC, iv).decrypt(b64Data) removeLen = ord(keyData[-1]) keyData = keyData[:-removeLen] else: keyData = base64.decodestring("".join(data[1:-1])) decodedKey = asn1parse(keyData) if type(decodedKey[0]) == type([]): decodedKey = decodedKey[0] # this happens with encrypted keys if kind == "RSA": n, e, d, p, q = decodedKey[1:6] return RSA.construct((n, e, d, p, q)) elif kind == "DSA": p, q, g, y, x = decodedKey[1:6] return DSA.construct((y, g, p, q, x))
def check(ip): checkflag=genflag() key=RSA.construct((n,e,d,p,q,u),) flag_md5=MD5.new(checkflag).digest() signature=key.sign(flag_md5,'')[0] try: opener = urllib2.build_opener() opener.addheaders = [('User-agent', USERAGENT)] f=opener.open('http://%s:3255/add.py?text=%s&sig=%s'%(ip,checkflag,signature), timeout=10) if f.getcode()!=200: return MUMBLE checkflag=checkflag[:-1]+"%%%02x" % ord(checkflag[-1]) try: f=opener.open('http://%s:3255/del.py?text=%s'%(ip,checkflag), timeout=5) if f.getcode()!=200: return MUMBLE except: pass # ignore f=opener.open('http://%s:3255/?c=%s'%(ip,genflag()), timeout=5) if f.getcode()!=200: return MUMBLE except Exception as E: print("%s"%E) return NOCONNECT return OK;
def import_key(self, public_file, private_file): """Inputs RSA keys from files and constructs and returns one Crypto key object.""" public_fields = self.input_file(public_file) if ("Description" not in public_fields or "Method" not in public_fields or "Modulus" not in public_fields or "Public exponent" not in public_fields or "Key length" not in public_fields or public_fields["Method"] != "RSA" or public_fields["Description"] != "Public key"): raise Exception("Error reading RSA public key file.") private_fields = self.input_file(private_file) if ("Description" not in private_fields or "Method" not in private_fields or "Modulus" not in private_fields or "Private exponent" not in private_fields or "Key length" not in private_fields or private_fields["Method"] != "RSA" or private_fields["Description"] != "Private key"): raise Exception("Error reading RSA private key file.") n = long(public_fields["Modulus"], 16) if n != long(private_fields["Modulus"], 16): raise Exception("RSA public and private keys don't match.") e = long(public_fields["Public exponent"], 16) d = long(private_fields["Private exponent"], 16) key = RSA.construct((n, e, d)) return key
def save_key(self, json_key): """ Callback to save public key from the master only save the key if its new. It is safe to update the key if the master is authenticated but that process is complicated. it requires logic to ensure that all Nodes receive the new key for now we're avoiding that. """ if not self.master_key: import os import simplejson from Crypto.PublicKey import RSA key = simplejson.loads(json_key) key = [long(x) for x in key] rsa_key = RSA.construct(key) self.master_key = rsa_key self.server.master_pub_key = rsa_key key_file = None try: key_path = '%s/node.master.key' % \ pydra_settings.RUNTIME_FILES_DIR key_file = file(key_path, 'w') logger.info('saving new master key') key_file = key_file.write(json_key) os.chmod(key_path, 0400) finally: if key_file: key_file.close()
def testExportKey4(self): key = RSA.construct([self.n, self.e]) pemKey = key.export_key("PEM") self.assertEqual(pemKey, b(self.rsaPublicKeyPEM))
def testExportKey3(self): key = RSA.construct( [self.n, self.e, self.d, self.p, self.q, self.pInv]) pemKey = key.export_key("PEM") self.assertEqual(pemKey, b(self.rsaKeyPEM))
from Crypto.PublicKey import RSA n = 85161183100445121230463008656121855194098040675901982832345153586114585729131 e = 65537 p = 280651103481631199181053614640888768819 q = 303441468941236417171803802700358403049 m = n - (p + q - 1) def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m d = modinv(e, m) key = RSA.construct((n, long(e), d, p, q)) print(key.exportKey())
def testExportKey1(self): key = RSA.construct( [self.n, self.e, self.d, self.p, self.q, self.pInv]) derKey = key.export_key("DER") self.assertEqual(derKey, self.rsaKeyDER)
import sys import binascii encrypt = False decrypt = False if len(sys.argv) == 4: encrypt = True elif len(sys.argv) == 6: decrypt = True else: print("FAIL") sys.exit(1) if encrypt: pk = RSA.construct((int(sys.argv[1], 16), int(sys.argv[2], 16))) message = binascii.unhexlify(sys.argv[3]) cipher = PKCS1_OAEP.new(pk) ciphertext = cipher.encrypt(message) print(ciphertext.hex()) if decrypt: ciphertext = binascii.unhexlify(sys.argv[5]) pky = RSA.construct( (int(sys.argv[1], 16) * int(sys.argv[2], 16), int(sys.argv[3], 16), int(sys.argv[4], 16), int(sys.argv[1], 16), int(sys.argv[2], 16))) cipher = PKCS1_OAEP.new(pky) recovered = cipher.decrypt(ciphertext) print(recovered.hex())
cipher = open(args.uncipherfile, 'rb').read().strip() args.uncipher = cipher # If we already have all informations if args.p is not None and args.q is not None and args.e is not None: try: priv_key = PrivateKey(args.p, args.q, args.e, args.n) except ValueError: if args.verbose: print("[!] No invmod for e and t, maybe an error in your args ?") sys.exit(0) if args.private: print(priv_key) if args.createpub: print(RSA.construct((args.n, args.e)).publickey().exportKey()) if args.uncipher is not None: unciphered = priv_key.decrypt(args.uncipher) print("[+] Clear text : %s" % unciphered) quit() # if createpub mode generate public key then quit if args.createpub: if (args.n is None and (args.p is None or args.q is None)) or args.e is None: raise Exception("Specify both a modulus and exponent on the command line. See --help for info.") print(RSA.construct((args.n, args.e)).publickey().exportKey().decode("utf-8")) quit()
n = p * q e = 65537 key = RSA.construct((n, e)) cipher = PKCS1_OAEP.new(key) enc = cipher.encrypt(flag) return key, enc def collide(): log = [] while True: key, enc = query() for n in log: p = GCD(key.n, n) if p != 1: q = key.n // p return p, q, enc log.append(key.n) p, q, enc = collide() n = p * q phi = (p - 1) * (q - 1) e = 65537 d = inverse(e, phi) key = RSA.construct((n, e, d)) cipher = PKCS1_OAEP.new(key) flag = cipher.decrypt(enc).decode() print(flag)
def _verify_signed_jwt_with_certs(jwt, time_now, cache, cert_uri=_DEFAULT_CERT_URI): """Verify a JWT against public certs. See http://self-issued.info/docs/draft-jones-json-web-token.html. The PyCrypto library included with Google App Engine is severely limited and so you have to use it very carefully to verify JWT signatures. The first issue is that the library can't read X.509 files, so we make a call to a special URI that has the public cert in modulus/exponent form in JSON. The second issue is that the RSA.verify method doesn't work, at least for how the JWT tokens are signed, so we have to manually verify the signature of the JWT, which means hashing the signed part of the JWT and comparing that to the signature that's been encrypted with the public key. Args: jwt: string, A JWT. time_now: The current time, as a long (eg. long(time.time())). cache: Cache to use (eg. the memcache module). cert_uri: string, URI to get cert modulus and exponent in JSON format. Returns: dict, The deserialized JSON payload in the JWT. Raises: _AppIdentityError: if any checks are failed. """ segments = jwt.split('.') if len(segments) != 3: raise _AppIdentityError('Token is not an id_token (Wrong number of ' 'segments)') signed = '%s.%s' % (segments[0], segments[1]) signature = _urlsafe_b64decode(segments[2]) lsignature = long(signature.encode('hex'), 16) header_body = _urlsafe_b64decode(segments[0]) try: header = json.loads(header_body) except: raise _AppIdentityError("Can't parse header") if header.get('alg') != 'RS256': raise _AppIdentityError('Unexpected encryption algorithm: %r' % header.get('alg')) json_body = _urlsafe_b64decode(segments[1]) try: parsed = json.loads(json_body) except: raise _AppIdentityError("Can't parse token body") certs = _get_cached_certs(cert_uri, cache) if certs is None: raise _AppIdentityError( 'Unable to retrieve certs needed to verify the signed JWT') if not _CRYPTO_LOADED: raise _AppIdentityError( 'Unable to load pycrypto library. Can\'t verify ' 'id_token signature. See http://www.pycrypto.org ' 'for more information on pycrypto.') local_hash = SHA256.new(signed).hexdigest() verified = False for keyvalue in certs['keyvalues']: try: modulus = _b64_to_long(keyvalue['modulus']) exponent = _b64_to_long(keyvalue['exponent']) key = RSA.construct((modulus, exponent)) hexsig = '%064x' % key.encrypt(lsignature, '')[0] hexsig = hexsig[-64:] verified = (hexsig == local_hash) if verified: break except Exception, e: logging.debug( "Signature verification error: %s; continue with the next cert.", e) continue
signer = RSAsign.new(key) signature = signer.sign(h) print "Welcome to admin's music portal.\nTo verify that you are the owner of this service\nsend the public key which will verify the following signature :\n" print "Message ->", message print print "Signature ->", signature.encode("hex") sys.stdout.flush() while True: try: n = long(raw_input("Enter n:")) e = long(raw_input("Enter e:")) sys.stdout.flush() if e >= 3 and n >= int(signature.encode("hex"), 16) and n.bit_length() <= 1025: break except ValueError: print "Invalid input" else: print "Invalid PublicKey" sys.stdout.flush() input_key = RSA.construct((n, e)) verifier = RSAsign.new(input_key) if verifier.verify(h, signature): print flag else: print "Music is only for admin's eyes." sys.stdout.flush() import libnum
class Key(object): """ An object representing a key. A key can be either a public or private key. A public key can verify a signature; a private key can create or verify a signature. To generate a string that can be stored on disk, use the toString method. If you have a private key, but want the string representation of the public key, use Key.public().toString(). @ivar keyObject: The C{Crypto.PublicKey.pubkey.pubkey} object that operations are performed with. """ def fromFile(Class, filename, type=None, passphrase=None): """ Return a Key object corresponding to the data in filename. type and passphrase function as they do in fromString. """ return Class.fromString(file(filename, 'rb').read(), type, passphrase) fromFile = classmethod(fromFile) def fromString(Class, data, type=None, passphrase=None): """ Return a Key object corresponding to the string data. type is optionally the type of string, matching a _fromString_* method. Otherwise, the _guessStringType() classmethod will be used to guess a type. If the key is encrypted, passphrase is used as the decryption key. @type data: C{str} @type type: C{None}/C{str} @type passphrase: C{None}/C{str} @rtype: C{Key} """ if type is None: type = Class._guessStringType(data) if type is None: raise BadKeyError('cannot guess the type of %r' % data) method = getattr(Class, '_fromString_%s' % type.upper(), None) if method is None: raise BadKeyError('no _fromString method for %s' % type) if method.func_code.co_argcount == 2: # no passphrase if passphrase: raise BadKeyError('key not encrypted') return method(data) else: return method(data, passphrase) fromString = classmethod(fromString) def _fromString_BLOB(Class, blob): """ Return a public key object corresponding to this public key blob. The format of a RSA public key blob is:: string 'ssh-rsa' integer e integer n The format of a DSA public key blob is:: string 'ssh-dss' integer p integer q integer g integer y @type blob: C{str} @return: a C{Crypto.PublicKey.pubkey.pubkey} object @raises BadKeyError: if the key type (the first string) is unknown. """ keyType, rest = common.getNS(blob) if keyType == 'ssh-rsa': e, n, rest = common.getMP(rest, 2) return Class(RSA.construct((n, e))) elif keyType == 'ssh-dss': p, q, g, y, rest = common.getMP(rest, 4) return Class(DSA.construct((y, g, p, q))) else: raise BadKeyError('unknown blob type: %s' % keyType) _fromString_BLOB = classmethod(_fromString_BLOB) def _fromString_PUBLIC_OPENSSH(Class, data): """ Return a public key object corresponding to this OpenSSH public key string. The format of an OpenSSH public key string is:: <key type> <base64-encoded public key blob> @type data: C{str} @return: A {Crypto.PublicKey.pubkey.pubkey} object @raises BadKeyError: if the blob type is unknown. """ blob = base64.decodestring(data.split()[1]) return Class._fromString_BLOB(blob) _fromString_PUBLIC_OPENSSH = classmethod(_fromString_PUBLIC_OPENSSH) def _fromString_PRIVATE_OPENSSH(Class, data, passphrase): """ Return a private key object corresponding to this OpenSSH private key string. If the key is encrypted, passphrase MUST be provided. Providing a passphrase for an unencrypted key is an error. The format of an OpenSSH private key string is:: -----BEGIN <key type> PRIVATE KEY----- [Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,<initialization value>] <base64-encoded ASN.1 structure> ------END <key type> PRIVATE KEY------ The ASN.1 structure of a RSA key is:: (0, n, e, d, p, q) The ASN.1 structure of a DSA key is:: (0, p, q, g, y, x) @type data: C{str} @type passphrase: C{str} @return: a C{Crypto.PublicKey.pubkey.pubkey} object @raises BadKeyError: if * a passphrase is provided for an unencrypted key * a passphrase is not provided for an encrypted key * the ASN.1 encoding is incorrect """ lines = [x + '\n' for x in data.split('\n')] kind = lines[0][11:14] if lines[1].startswith('Proc-Type: 4,ENCRYPTED'): # encrypted key ivdata = lines[2].split(',')[1][:-1] iv = ''.join([ chr(int(ivdata[i:i + 2], 16)) for i in range(0, len(ivdata), 2) ]) if not passphrase: raise EncryptedKeyError('encrypted key with no passphrase') ba = md5.new(passphrase + iv).digest() bb = md5.new(ba + passphrase + iv).digest() decKey = (ba + bb)[:24] b64Data = base64.decodestring(''.join(lines[3:-1])) keyData = DES3.new(decKey, DES3.MODE_CBC, iv).decrypt(b64Data) removeLen = ord(keyData[-1]) keyData = keyData[:-removeLen] else: keyData = base64.decodestring(''.join(lines[1:-1])) try: decodedKey = asn1.parse(keyData) except Exception, e: raise BadKeyError, 'something wrong with decode' if kind == 'RSA': if len(decodedKey) == 2: # alternate RSA key decodedKey = decodedKey[0] n, e, d, p, q = decodedKey[1:6] if p > q: # make p smaller than q p, q = q, p return Class(RSA.construct((n, e, d, p, q))) elif kind == 'DSA': p, q, g, y, x = decodedKey[1:6] return Class(DSA.construct((y, g, p, q, x)))
'shaalg': lambda x: x, 'result': lambda x: x }) or [] for count, tv in enumerate(test_vectors_verify): if isinstance(tv, str): continue if hasattr(tv, "n"): modulus = tv.n continue if hasattr(tv, "p"): continue hash_module = load_hash_by_name(tv.shaalg.upper()) hash_obj = hash_module.new(tv.msg) public_key = RSA.construct([bytes_to_long(x) for x in (modulus, tv.e)]) # type: ignore if tv.saltval != b("\x00"): prng = PRNG(tv.saltval) verifier = pss.new(public_key, salt_bytes=len(tv.saltval), rand_func=prng) else: verifier = pss.new(public_key, salt_bytes=0) def positive_test(self, hash_obj=hash_obj, verifier=verifier, signature=tv.s): verifier.verify(hash_obj, signature) def negative_test(self,
fnoqzEujTvkaXhhfgwIDAQAB -----END PUBLIC KEY-----""") n = public_key.n e = public_key.e q = int(n // p) assert p * q == n # Phi ϕ = (p - 1) * (q - 1) d = _modinv(e, ϕ) assert (e * d) % ϕ == 1 print(f'RSA modulus: {n}') print(f'RSA public exponent: {e}') print(f'First factor of the RSA modulus: {p}') print(f'Second factor of the RSA modulus: {q}') print(f'RSA private exponent: {d}') # I suck at reading files in python, so I base64'd it raw_cipher = b64decode( 'U0JUONM2neF4/SksiQsBjybSLlJ/HbHrtM9iesDJWFlN/9y1N1OqouihxVqWpliUdAc8608bkxNXAz9DCdMG6myABK9H6Fd1+diVKktMWw+FbhV95MouJdvXRXR0VBOxc5RefLUL/ntTXoTZ3uR2oDthD8f+nB4Ky00y3DHOFuE=' ) private_key = RSA.construct((n, e, d, p, q)) cipher = PKCS1_OAEP.new(private_key) message = cipher.decrypt(raw_cipher) print(message) # [Good job! Next chall: /rsa2ez4me.zip]'
dP = int(target_key_set[2][0], 16) dQ = int(target_key_set[2][1], 16) qInv = int(target_key_set[3], 16) print "p: %d" % p print "q: %d" % q print "d mod (p - 1): %d" % dP print "d mod (q - 1): %d" % dQ print "(inverse of q) mod p: %d" % qInv n = p * q r = (p - 1) * (q - 1) e = 1 while e < r: print e if fractions.gcd(e, r) == 1: d = gmpy.invert(e, r) if d % (p - 1) == dP and d % (q - 1) == dQ: print 'n: %d' % n print 'e: %d' % e print 'd: %d' % d print 'p: %d' % p print 'q: %d' % q break e += 1 private_key = RSA.construct((n, long(e), long(d), p, q)) print private_key.exportKey() dsmg = private_key.decrypt(open('flag.enc').read()) print dsmg
exit(0) # Create pubkey if requested if args.createpub: pub_key, priv_key = generate_keys_from_p_q_e_n(args.p, args.q, args.e, args.n) print(pub_key.decode("utf-8")) exit(0) # Load keys tmpfile = None if args.publickey is None and args.e is not None and args.n is not None: tmpfile = tempfile.NamedTemporaryFile() with open(tmpfile.name, "wb") as tmpfd: tmpfd.write( RSA.construct((args.n, args.e)).publickey().exportKey()) args.publickey = [tmpfile.name] elif args.publickey is not None: if "*" in args.publickey or "?" in args.publickey: pubkeyfilelist = glob(args.publickey) args.publickey = pubkeyfilelist elif "," in args.publickey: args.publickey = args.publickey.split(",") else: args.publickey = [args.publickey] # If we already have all informations if (args.p is not None and args.q is not None and args.e is not None and args.n is not None): try:
def make_key(self, _, key): return RSA.construct((key['n'], long(key['e']), key['d']))
c[pos] = "1" if (c[pos] == "0") else "0" candidate_binrep = "".join(c) candidate = int(candidate_binrep, 2) facstatus = isFactored(candidate) if (facstatus[0] > 4): if ((len(facstatus[1]) == 2) and not (False in [isprime(x) for x in facstatus[1]])): print "[+]Found candidate! [%d] [%s]" % (candidate, facstatus[1]) print "[+]Corresponding private exponent (d = %d)" % d else: continue p = facstatus[1][0] q = facstatus[1][1] d = modInv(pubKey.e, (p - 1) * (q - 1)) privKey = RSA.construct(( candidate, pubKey.e, d, p, q, )) p = privKey.decrypt(ciphertext) # If flag prefix is in plaintext we have our private key if ("TMCTF" in p): print "[+]Plaintext: [%s]" % p exit()
group.add_argument('--createpub', help='Take n and e from cli and just print a public key then exit', action='store_true') group.add_argument('--dumpkey', help='Just dump the RSA variables from a key - n,e,d,p,q', action='store_true') parser.add_argument('--uncipher', help='uncipher a file', default=None) parser.add_argument('--verbose', help='verbose mode (display n, e, p and q)', action='store_true') parser.add_argument('--private', help='Display private key if recovered', action='store_true') parser.add_argument('--n', type=long, help='Specify the modulus in --createpub mode.') parser.add_argument('--e', type=long, help='Specify the public exponent in --createpub mode.') parser.add_argument('--key', help='Specify the input key file in --dumpkey mode.') args = parser.parse_args() # if createpub mode generate public key then quit if args.createpub: if args.n is None or args.e is None: raise Exception("Specify both a modulus and exponent on the command line. See --help for info.") print RSA.construct((args.n, args.e)).publickey().exportKey() quit() # if dumpkey mode dump the key components then quit if args.dumpkey: if args.key is None: raise Exception("Specify a key file to dump with --key. See --help for info.") #print RSA.construct((args.n, args.e)).publickey().exportKey() key_data = open(args.key,'rb').read() key = RSA.importKey(key_data) print "[*] n: " + str(key.n) print "[*] e: " + str(key.e) if key.has_private(): print "[*] d: " + str(key.d) print "[*] p: " + str(key.p) print "[*] q: " + str(key.q)
def enc_message(self): for i in PublicInfo.get_all(): key = RSA.construct((i.enc_n, i.enc_e)) self._message = RSAChunker.encrypt(key, self._message) for i in PublicInfo.get_all(): self._message = self._message + i.id.encode('utf-8')
def rsa(src): rsakey = RSA.construct((int(define.__LOGIN_RSA_VER158_KEY_N__, 16), define.__LOGIN_RSA_VER158_KEY_E__)) cipher = Cipher_pkcs1_v1_5.new(rsakey) encrypt_buf = cipher.encrypt(src) return encrypt_buf
from Crypto.PublicKey import RSA import gmpy2 public_key = RSA.importKey("""-----BEGIN PUBLIC KEY----- MEEwDQYJKoZIhvcNAQEBBQADMAAwLQImDlsTjeFVTgo4BAs9/Ex5xUU6iWNoBDY8 J7tuuv7INMmMOgYoIFUCAwEAAQ== -----END PUBLIC KEY-----""") n = int(public_key.n) e = int(public_key.e) p = 1332830227949273521465367319234277279439624789 q = 1371293089587387292180481293784036793076837889 d = int(gmpy2.invert(e, (p - 1) * (q - 1))) private_key = RSA.construct((n, e, d)) private_key_file = open('private.pem', 'wb') private_key_file.write(private_key.exportKey()) private_key_file.close() ##Utilizado apenas para propósito de testes!!! cipher = open('key.cipher', 'rb') encrypted_message = cipher.read() cipher.close() decrypted_message = private_key.decrypt(encrypted_message) print(decrypted_message) signature = private_key.sign(decrypted_message, '') public_key.verify(decrypted_message, signature) secret = public_key.encrypt(decrypted_message, '') print(secret) print(private_key.decrypt(secret))
def testExportKey9(self): key = RSA.construct( [self.n, self.e, self.d, self.p, self.q, self.pInv]) self.assertRaises(ValueError, key.exportKey, "invalid-format")
def testExportKey15(self): # Verify that that error an condition is detected when trying to # use a password with DER encoding and PKCS#1. key = RSA.construct( [self.n, self.e, self.d, self.p, self.q, self.pInv]) self.assertRaises(ValueError, key.exportKey, 'DER', 'test', 1)
help='use Known High Bits Factor Attack, this specify the High Bits of factor', default=None) group4.add_argument('--pbits', type=int, help='customize the bits lenth of factor, default is half of n`s bits lenth', default=None) parser.add_argument( '-v', '--verbose', help='print details', action='store_true') args = parser.parse_args() # if createpub mode generate public key then quit if args.createpub: if args.N is None or args.e is None: raise Exception( "Specify both a modulus and exponent on the command line. See --help for info.") if args.output: with open(args.output, 'w') as file: file.write(RSA.construct( (args.N, args.e)).publickey().exportKey()) print('saved in %s' % args.output) else: print(RSA.construct((args.N, args.e)).publickey().exportKey()) quit() # if dumpkey mode dump the key components then quit if args.dumpkey: if args.key is None: raise Exception( "Specify a key file to dump with --key. See --help for info.") key_data = open(args.key, 'rb').read() key = RSA.importKey(key_data) print("[*] n: " + str(key.n)) print("[*] e: " + str(key.e))
def testExportKey5(self): key = RSA.construct([self.n, self.e]) openssh_1 = key.exportKey("OpenSSH").split() openssh_2 = self.rsaPublicKeyOpenSSH.split() self.assertEqual(openssh_1[0], openssh_2[0]) self.assertEqual(openssh_1[1], openssh_2[1])
0, -36, -126, 74, 72, -26, 63, 107, -123, -9, 118, 37, -95, 61, 5, 55, -20, 8, -21, 54, 86, -78, -41, 44, -103, -126, -30, -36, 29, 111, 122, 11, 18, 114, 102, 94, -126, 117, 7, 106, -117, -58, 25, 126, 29, 113, 28, 107, 27, 78, 57, 70, 5, 25, 93, 8, 24, 87, 101, 4, 121, -30, -62, -100, -114, -21, -102, -76, 47, 124, 124, 65, -127, -65, 50, 28, -63, -56, 48, 127, 48, -36, -121, -109, 6, -114, 72, -96, -100, -3, 72, -62, -55, -52, 24, 6, -24, 1, -113, 50, 116, 68, 74, 71, -70, -8, 14, -96, 121, 10, -98, 92, -4, -119, -55, 112, 102, 54, 73, 1, -20, 71, -113, -28, -123, -8, -99, 9 ] # create key object n = [ctypes.c_ubyte(i).value for i in n] d = [ctypes.c_ubyte(i).value for i in d] n = int(''.join(format(x, '02x') for x in n), 16) d = int(''.join(format(x, '02x') for x in d), 16) priKey = RSA.construct((n, e, d)).exportKey() pubKey = RSA.construct((n, e)).exportKey() private_key = RSA.import_key(priKey) public_key = RSA.import_key(pubKey) cipher_rsa_pri = PKCS1_v1_5.new(private_key) ######################### MONGODB ACCESS db_client = MongoClient('localhost', 27017) db_db = db_client.xtldb db_xtlcard = db_db.xtlcard def verify_transactions_first_stage(cipherTxs): dsize = SHA.digest_size sentinel = Random.new().read(15 + dsize)
sys.path[0:0] = ['.', '..'] from elftools.elf.elffile import ELFFile from elftools.elf.sections import SymbolTableSection PAGE_SIZE = 4096 h = SHA256.new() n = 0xA1D46FBA2318F8DCEF16C280948B1CF27966B9B47225ED2989F8D74B45BD36049C0AAB5AD0FF003553BA843C8E12782FC5873BB89A3DC84B883D25666CD22BF3ACD5B675969F8BEBFBCAC93FDD927C7442B178B10D1DFF9398E52316AAE0AF74E594650BDC3C670241D418684593CDA1A7B9DC4F20D2FDC6F66344074003E211 e = 0x010001 d = 0x589552BB4F2F023ADDDD5586D0C8FD857512D82080436678D07F984A29D892D31F1F7000FC5A39A0F73E27D885E47249A4148C8A5653EF69F91F8F736BA9F84841C2D99CD8C24DE8B72B5C9BE0EDBE23F93D731749FEA9CFB4A48DD2B7F35A2703E74AA2D4DB7DE9CEEA7D763AF0ADA7AC176C4E9A22C4CDA65CEC0C65964401 p = 0xCD083568D2D46C44C40C1FA0101AF2155E59C70B08423112AF0C1202514BBA5210765E29FF13036F56C7495894D80CF8C3BAEE2839BACBB0B86F6A2965F60DB1 q = 0xCA0EEEA5E710E8E9811A6B846399420E3AE4A4C16647E426DDF8BBBCB11CD3F35CE2E4B6BCAD07AE2C0EC2ECBFCC601B207CDD77B5673E16382B1130BF465261 rsaCertikos = RSA.construct((n, e), consistency_check=True) rsaDevice = RSA.generate(bits=2048, e=65537) def ROUND_DOWN(num, divisor): return num - (num%divisor) def ROUND_UP(num, divisor): return num + (divisor - num%divisor) def process_file(filename): print('Processing file:', filename) with open(filename, 'rb') as f: section_info_lowlevel(f) f.seek(0) section_info_highlevel(f)
#xの値より、tp,tqに追加すべき候補は2通りに絞られる if binx[-(bits + 1)] == "1": p = recur("1" + tp, "0" + tq) if p: return p p = recur("0" + tp, "1" + tq) if p: return p else: p = recur("1" + tp, "1" + tq) if p: return p p = recur("0" + tp, "0" + tq) if p: return p return False p = recur("11", "01") q = n // p e = 65537 phi = (p - 1) * (q - 1) d = inverse(e, phi) f = open("./dist/flag.enc", "rb") a = f.readlines() key = RSA.construct((n, e, d, p, q)) cipher = PKCS1_OAEP.new(key) ciphertext = a[0] + a[1][:-1] #最後の改行が入ると悪さをするのでそれを抜く flag = cipher.decrypt(ciphertext) print(flag)
def testExportKey2(self): key = RSA.construct([self.n, self.e]) derKey = key.export_key("DER") self.assertEqual(derKey, self.rsaPublicKeyDER)
modulo_file = sys.argv[3] output_file = sys.argv[4] with open(key_file) as f: key_str = f.read().strip() e = int(key_str, 16) with open(ciphertext_file) as f: ciphertext = f.read().strip() with open(modulo_file) as f: modulo = f.read().strip() N = int(modulo, 16) expansion = cf_expansion(e, N) conv = convergents(expansion) prikey = find_key(N, e, conv) RSAkey = RSA.construct((N, e, prikey)) ciphertext = int(ciphertext, 16) plaintext = RSAkey.decrypt(ciphertext) print plaintext #plaintext = hex(plaintext)[2] with open(output_file, 'w') as f: f.write(hex(plaintext)[2:])
if isPrime(p): return p key = None flag = open("flag.txt", "rb").read() print("Welcome to my Prime Obsession. Tell me what do you want.\n") while True: print("[1] Generate key") print("[2] Get Encrypted flag") print("[3] Exit") opt = int(input(">>> ")) if opt == 1: p = generate_prime(1024) q = generate_prime(1024) e = 65537 n = p * q key = RSA.construct((n, e)) print(key.exportKey('PEM').decode()) if opt == 2: if not key: print("No key generated :/") else: cipher = PKCS1_OAEP.new(key) print(binascii.hexlify(cipher.encrypt(flag)).decode()) if opt == 3: print("You are not obsessed enough :/") break print("\n")
def __init__( self, **kw ): """ Constructor, kw is dict of CRT paramters and RSA key. Required RSA priv. key params (as long) n, d, e - modulus and private exponent or p, q, e - primes p, q, and public exponent e If also dp, dq, qinv present, they are checked to be consistent. Default value for e is 0x10001 """ # super( RSAtoken, self ).__init__( **kw ) Token.__init__( self, **kw ) # check RSA parameters for par in ( 'n', 'd', 'e', 'p', 'q', 'dp', 'dq', 'dqinv' ): if par in kw: assert isinstance( long( kw[par] ), long ), \ "RSA parameter %s must be long" % par e = long( kw.get( 'e', 0x10001L )) if 'n' in kw and 'd' in kw: self.key = RSA.construct(( n, e, d )) elif 'p' in kw and 'q' in kw: p = kw['p'] q = kw['q'] n = p*q d = number.inverse( e, (p-1)*(q-1)) if 'd' in kw: assert d == kw['d'], "Inconsinstent private exponent" if 'dp' in kw: assert d % (p-1) == kw['dp'], "Inconsistent d mod (p-1)" if 'dq' in kw: assert d % (q-1) == kw['dq'], "Inconsistent d mod (q-1)" u = number.inverse( q, p ) if 'qinv' in kw: assert u == kw['qinv'], "Inconsistent q inv" self.key = RSA.construct(( n, e, d, q, p, u ))