def test_get(self): JWT_PRIVATE_SIGNING_KEY = RSA.generate(2048).exportKey('PEM') JWT_EXPIRED_PRIVATE_SIGNING_KEYS = [RSA.generate(2048).exportKey('PEM'), RSA.generate(2048).exportKey('PEM')] secret_keys = [JWT_PRIVATE_SIGNING_KEY] + JWT_EXPIRED_PRIVATE_SIGNING_KEYS with override_settings(JWT_PRIVATE_SIGNING_KEY=JWT_PRIVATE_SIGNING_KEY, JWT_EXPIRED_PRIVATE_SIGNING_KEYS=JWT_EXPIRED_PRIVATE_SIGNING_KEYS): response = self.client.get(reverse('jwks')) self.assertEqual(response.status_code, 200) actual = json.loads(response.content) expected = { 'keys': [views.JwksView.serialize_rsa_key(key) for key in secret_keys], } self.assertEqual(actual, expected)
def ensure_rsakey(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, apps=global_apps, **kwargs): """Ensure an RSA key exists for token signing If no RSAKey objects exist, create one. This is registered as a post-migrate signal handler for the oidc_provider app so that it can be run immediately after the initial migration. """ try: RSAKey = apps.get_model('oidc_provider', 'RSAKey') except LookupError: return if not router.allow_migrate_model(using, RSAKey): return if RSAKey.objects.using(using).exists(): return if verbosity >= 1: print('Creating initial RSAKey') key = RSA.generate(2048).exportKey('PEM').decode('utf-8') try: RSAKey.objects.using(using).create(pk=1, key=key) except IntegrityError: pass
def _generate_lti_1p3_keys_if_missing(self): """ Generate LTI 1.3 RSA256 keys if missing. If either the public or private key are missing, regenerate them. The LMS provides a keyset endpoint, so key rotations don't cause any issues for LTI launches (as long as they have a different kid). """ # Generate new private key if not present if not self.lti_1p3_internal_private_key: # Private key private_key = RSA.generate(2048) self.lti_1p3_internal_private_key_id = str(uuid.uuid4()) self.lti_1p3_internal_private_key = private_key.export_key( 'PEM').decode('utf-8') # Clear public key if any to allow regeneration # in the code below self.lti_1p3_internal_public_jwk = '' if not self.lti_1p3_internal_public_jwk: # Public key key_handler = PlatformKeyHandler( key_pem=self.lti_1p3_internal_private_key, kid=self.lti_1p3_internal_private_key_id, ) self.lti_1p3_internal_public_jwk = json.dumps( key_handler.get_public_jwk()) # Doesn't do anything if model didn't change self.save()
def create_and_store_rsa_key_pair(name="pyoidc", path=".", size=2048): """ :param name: Name of the key file :param path: Path to where the key files are stored :param size: RSA key size :return: RSA key """ key = RSA.generate(size) if sys.version_info[0] > 2: os.makedirs(path, exist_ok=True) else: try: os.makedirs(path) except OSError: # assume this is because it already exists pass if name: with open(os.path.join(path, name), 'wb') as f: f.write(key.exportKey('PEM')) _pub_key = key.publickey() with open(os.path.join(path, '{}.pub'.format(name)), 'wb') as f: f.write(_pub_key.exportKey('PEM')) return key
def generate_jwks(self, mode): if "rotenc" in self.behavior_type: # Rollover encryption keys rsa_key = RSAKey(kid="rotated_rsa_{}".format(time.time()), use="enc").load_key(RSA.generate(2048)) ec_key = ECKey(kid="rotated_ec_{}".format(time.time()), use="enc").load_key(P256) keys = [rsa_key.serialize(private=True), ec_key.serialize(private=True)] new_keys = {"keys": keys} #self.do_key_rollover(new_keys, "%d") signing_keys = [k.to_dict() for k in self.keyjar.get_signing_key()] new_keys["keys"].extend(signing_keys) return json.dumps(new_keys) elif "nokid1jwk" in self.behavior_type: alg = mode["sign_alg"] if not alg: alg = "RS256" keys = [k.to_dict() for kb in self.keyjar[""] for k in list(kb.keys())] for key in keys: if key["use"] == "sig" and key["kty"].startswith(alg[:2]): key.pop("kid", None) jwk = dict(keys=[key]) return json.dumps(jwk) raise Exception( "Did not find sig {} key for nokid1jwk test ".format(alg)) else: # Return all keys keys = [k.to_dict() for kb in self.keyjar[""] for k in list(kb.keys())] jwks = dict(keys=keys) return json.dumps(jwks)
def __call__(self): keyjar = self.conv.entity.keyjar self.conv.entity.original_keyjar = keyjar.copy() # invalidate the old key old_kid = self.op_args["old_kid"] old_key = keyjar.get_key_by_kid(old_kid) old_key.inactive_since = time.time() # setup new key key_spec = self.op_args["new_key"] typ = key_spec["type"].upper() if typ == "RSA": kb = KeyBundle(keytype=typ, keyusage=key_spec["use"]) kb.append(RSAKey(use=key_spec["use"]).load_key( RSA.generate(key_spec["bits"]))) elif typ == "EC": kb = ec_init(key_spec) else: raise Exception('Wrong key type') # add new key to keyjar with list(kb.keys())[0].kid = self.op_args["new_kid"] keyjar.add_kb("", kb) # make jwks and update file keys = [] for kb in keyjar[""]: keys.extend( [k.to_dict() for k in list(kb.keys()) if not k.inactive_since]) jwks = dict(keys=keys) with open(self.op_args["jwks_path"], "w") as f: f.write(json.dumps(jwks))
def setUp(self): super().setUp() self.rsa_key_id = "1" # Generate RSA and save exports rsa_key = RSA.generate(2048) self.key = RSAKey(key=rsa_key, kid=self.rsa_key_id) self.public_key = rsa_key.publickey().export_key() self.xblock_attributes = { 'lti_version': 'lti_1p3', 'lti_1p3_launch_url': 'http://tool.example/launch', 'lti_1p3_oidc_url': 'http://tool.example/oidc', # We need to set the values below because they are not automatically # generated until the user selects `lti_version == 'lti_1p3'` on the # Studio configuration view. 'lti_1p3_tool_public_key': self.public_key, 'has_score': True, } self.xblock = make_xblock('lti_consumer', LtiConsumerXBlock, self.xblock_attributes) # Set dummy location so that UsageKey lookup is valid self.xblock.location = 'block-v1:course+test+2020+type@problem+block@test' # Creates an LTI configuration objects for testing self.lti_1p1_config = LtiConfiguration.objects.create( location=str(self.xblock.location), version=LtiConfiguration.LTI_1P1) self.lti_1p3_config = LtiConfiguration.objects.create( location=str(self.xblock.location), version=LtiConfiguration.LTI_1P3)
def generate_keys(key_type, key_scope, key_format='der'): """ generates private and public keys: - key_type designates the type of the key: 'rsa', 'dsa', 'ecc' - key_format designates the key representation 'der' or 'pem' - key_scope designates the scope of the key: 'sig', 'enc' -- this is mostly for naming convention output files are: key-<key_type>-<key_scope>-{pkcs8,asn1}.<key_format> """ pbl, prv = get_key_files(key_type, key_scope, key_format=key_format) if key_format == 'der': key_format = 'DER' if key_format == 'pem': key_format = 'PEM' if key_type == 'rsa': key = RSA.generate(2048) bytes_prv = key.exportKey(key_format, pkcs=8) bytes_pbl = key.publickey().exportKey(key_format) elif key_type == 'dsa': key = DSA.generate(2048) bytes_prv = key.exportKey(key_format, pkcs8=True) bytes_pbl = key.publickey().exportKey(key_format) elif key_type == 'ecc': key = ECC.generate(curve='P-256') bytes_prv = key.export_key(format=key_format, use_pkcs8=True) bytes_pbl = key.public_key().export_key(format=key_format) else: raise ImplementationError(key_type, "Unknown key type") with open(prv, 'wb') as f: f.write(bytes_prv) with open(pbl, 'wb') as f: f.write(bytes_pbl)
def generate_user_on_node(base_client, pool_id, node_id): generated_username = secure_utils.generate_random_string() ssh_key = RSA.generate(2048) ssh_pub_key = ssh_key.publickey().exportKey('OpenSSH').decode('utf-8') base_client.create_user_on_node(pool_id, node_id, generated_username, ssh_pub_key) return generated_username, ssh_key
def __init__(self, kodi_helper): """ The Constructor checks for already existing crypto Keys. If they exist it will load the existing keys """ self.kodi_helper = kodi_helper try: os.mkdir(self.kodi_helper.msl_data_path) except OSError: pass if self.file_exists(self.kodi_helper.msl_data_path, 'msl_data.json'): self.kodi_helper.log(msg='MSL Data exists. Use old Tokens.') self.__load_msl_data() self.handshake_performed = True elif self.file_exists(self.kodi_helper.msl_data_path, 'rsa_key.bin'): self.kodi_helper.log(msg='RSA Keys do already exist load old ones') self.__load_rsa_keys() if self.kodi_helper.get_esn(): self.__perform_key_handshake() else: self.kodi_helper.log(msg='Create new RSA Keys') # Create new Key Pair and save self.rsa_key = RSA.generate(2048) self.__save_rsa_keys() if self.kodi_helper.get_esn(): self.__perform_key_handshake()
def register(): print('Register') name = input('Enter your full name: ') email = input('Enter your email address: ') raw_password = getpass.getpass('Enter your password: '******'Re-enter your password: '******'Password Mismatch, Registration cancelled') # Generate RSA Public/Private Key key = RSA.generate(2048) private_key = key.export_key(passphrase=raw_password, pkcs=8, protection='scryptAndAES128-CBC') public_key = key.publickey().export_key() del raw_password print('Registration Successful') # Save credentials to config config = readConfig() config['Cred'] = { 'name': name, 'email': email, 'password': password, 'public_key': public_key, 'private_key': private_key} writeConfig(config)
def generate_keys(): """ Generate the public and the private key """ random_generator = Random.new().read key = RSA.generate(2048, random_generator) return (key.exportKey(), key.publickey().exportKey())
def generate_keys(self): private_key = RSA.generate(1024, Cryptodome.Random.new().read) public_key = private_key.publickey() return (binascii.hexlify( private_key.exportKey(format='DER')).decode('ascii'), binascii.hexlify( public_key.exportKey(format='DER')).decode('ascii'))
def __generate_user_on_node(self, pool_id, node_id): generated_username = secure_utils.generate_random_string() ssh_key = RSA.generate(2048) ssh_pub_key = ssh_key.publickey().exportKey('OpenSSH').decode('utf-8') self.__create_user_on_node(generated_username, pool_id, node_id, ssh_pub_key) return generated_username, ssh_key
def keys_check(app_log, keyfile): # key maintenance if os.path.isfile("privkey.der") is True: app_log.warning("privkey.der found") elif os.path.isfile("privkey_encrypted.der") is True: app_log.warning("privkey_encrypted.der found") os.rename("privkey_encrypted.der", "privkey.der") elif os.path.isfile(keyfile) is True: app_log.warning("{} found".format(keyfile)) else: # generate key pair and an address key = RSA.generate(4096) #public_key = key.publickey() private_key_readable = key.exportKey().decode("utf-8") public_key_readable = key.publickey().exportKey().decode("utf-8") address = hashlib.sha224(public_key_readable.encode( "utf-8")).hexdigest() # hashed public key # generate key pair and an address app_log.info("Your address: {}".format(address)) app_log.info("Your public key: {}".format(public_key_readable)) # export to single file keys_save(private_key_readable, public_key_readable, address, keyfile)
def generate_private_key(): key = RSA.generate(2018) encrypted_key = key.exportKey(passphrase=secret_code, pkcs=8, protection='scryptAndAES128-CBC') file_out = open(private_key, "wb") file_out.write(encrypted_key) file_out.close() print(key.publickey().exportKey())
def init_generate_rsa_keys(self): self.kodi_helper.log(msg='Create new RSA Keys') # Create new Key Pair and save self.rsa_key = RSA.generate(2048) self.__save_rsa_keys() if self.kodi_helper.get_esn(): self.__perform_key_handshake()
def generate_rsa_key(self): """ Generate 2048 bits RSA key pair. """ key = RSA.generate(WorkerEncrypt.RSA_KEY_SIZE) self.rsa_private_key = key.export_key() self.rsa_public_key = key.publickey().export_key()
def setUp(self): super().setUp() # Create custom LTI Block self.rsa_key_id = "1" rsa_key = RSA.generate(2048) self.key = RSAKey( key=rsa_key, kid=self.rsa_key_id ) self.public_key = rsa_key.publickey().export_key() self.xblock_attributes = { 'lti_version': 'lti_1p3', 'lti_1p3_launch_url': 'http://tool.example/launch', 'lti_1p3_oidc_url': 'http://tool.example/oidc', # Intentionally using the same key for tool key to # allow using signing methods and make testing easier. 'lti_1p3_tool_public_key': self.public_key, # LTI NRPS related attributes 'lti_1p3_enable_nrps': True } self.xblock = make_xblock('lti_consumer', LtiConsumerXBlock, self.xblock_attributes) # Set dummy location so that UsageKey lookup is valid self.xblock.location = 'block-v1:course+test+2020+type@problem+block@test' # Create configuration self.lti_config = LtiConfiguration.objects.create( location=str(self.xblock.location), version=LtiConfiguration.LTI_1P3, ) # Preload XBlock to avoid calls to modulestore self.lti_config.block = self.xblock # Patch internal method to avoid calls to modulestore patcher = patch( 'lti_consumer.models.LtiConfiguration.block', new_callable=PropertyMock, return_value=self.xblock ) self.addCleanup(patcher.stop) self._lti_block_patch = patcher.start() self.context_membership_endpoint = reverse( 'lti_consumer:lti-nrps-memberships-view-list', kwargs={ "lti_config_id": self.lti_config.id } ) batch_external_id_patcher = patch( 'lti_consumer.plugin.views.compat.batch_get_or_create_externalids', return_value=ExternalIDMapping() ) self._batch_external_id_patcher = batch_external_id_patcher.start()
def __init__(self, name): self.name = name print("[*] client generating RSA Key for " + name) #generate client rsa public/private key privkey = RSA.generate(2048) self.privatekey = privkey.export_key() #4096) #encrypted_key = key.export_key(passphrase=secret_code, pkcs=8, protection="scryptAndAES128-CBC") self.publickey = private_key.publickey().export_key()
def gen(self): key_pair = RSA.generate(1024) private_key = open("privatekey.pem", "wb") private_key.write(key_pair.exportKey()) private_key.close() public_key = open("public_key.pem", "wb") public_key.write(key_pair.publickey().exportKey()) public_key.close()
def create_rsa_key(self, private_key='server_private_rsa_key.bin', public_key='server_rsa_public.pem'): key = RSA.generate(1024) encrypted_key = key.exportKey(passphrase='179', pkcs=8, protection="scryptAndAES128-CBC") # print(public_key) with open(private_key, "wb") as f: f.write(encrypted_key) with open(public_key, "wb") as f: f.write(key.publickey().exportKey())
def create_rsa_key(): key = RSA.generate(2048) pri_key = key.export_key(pkcs=8) pub_key = key.publickey().exportKey() with open('./pri.key', 'wb') as f: f.write(pri_key) with open('./pub.pem', 'wb') as f: f.write(pub_key)
def generate_key(self, rsa_bit=1024): random_generator = Random.new().read rsa = RSA.generate(rsa_bit, random_generator) self.e = rsa.e self.d = rsa.d self.n = rsa.n self.p = rsa.p self.q = rsa.q
def __init__(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.private_key = RSA.generate(2048) self.public_key = self.private_key.publickey().exportKey() self.merchant_public_key = None self.pg_public_key = None self.session_id = None self.session_signature = None
def generateAsymKey(size, folder, createdTime): key = RSA.generate(int(size.split(' ')[0])) publicFile = open(folder + "/PulicKey_" + createdTime + '(' + size.split(' ')[0] + ").pubk", "wb") #+ "(" + number + ") privateFile = open(folder + "/PrivateKey_" + createdTime + '(' + size.split(' ')[0] + ").prvk", "wb") publicFile.write(key.publickey().exportKey()) privateFile.write(key.exportKey()) publicFile.close() privateFile.close()
def generate_keys(self): private_key = RSA.generate(1024, rand.new().read) return ( binascii.hexlify( private_key.exportKey(format='DER')).decode('ascii'), binascii.hexlify(private_key.publickey().exportKey( format='DER')).decode('ascii'), )
def generate_keypair() -> (bytes,bytes): """ Function used to generate the RSA keypair for jwt encryption """ keypair = RSA.generate(2048) priv = keypair.export_key() pub = keypair.publickey().export_key() return pub, priv
def generate_rsa(): key = RSA.generate(2048) private_key = key.export_key(**config) public_key = key.publickey().export_key(**config) public_key = base64.b64encode(public_key).decode("utf-8") private_key = base64.b64encode(private_key).decode("utf-8") return public_key, private_key
def generateKeyPair(self): # self.gen() # 1024 means the keysize will be 1024 bits key_pair = RSA.generate(self.key_size) # storing only the key value in the dictionary self.key_pair = [RSA.importKey(key_pair.exportKey()),RSA.importKey(key_pair.publickey().exportKey())] # self.key_pair = [key_pair.exportKey(),key_pair.publickey().exportKey()] return self.key_pair
def generate_keys(): keys = RSA.generate(2048) # Because 4096 bit keys took 3 mins to generate. This took 20 secs public_key = keys.publickey().export_key(format='PEM', pkcs=1) # Index of 1 available to public keys private_key = keys.export_key(format='PEM', pkcs=8) # Index of 8 available to private keys only with open('master_public_key','wb') as f: f.write(public_key) with open('master_private_key', 'wb') as f: f.write(private_key)
def handle(self, *args, **options): try: key = RSA.generate(1024) rsakey = RSAKey(key=key.exportKey('PEM').decode('utf8')) rsakey.save() self.stdout.write(u'RSA key successfully created with kid: {0}'.format(rsakey.kid)) except Exception as e: self.stdout.write('Something goes wrong: {0}'.format(e))
def handle(self, *args, **options): try: key = RSA.generate(2048) rsakey = RSAKey(key=key.exportKey('PEM').decode('utf8')) rsakey.save() self.stdout.write(u'RSA key successfully created with kid: {0}'.format(rsakey.kid)) except Exception as e: self.stdout.write('Something goes wrong: {0}'.format(e))
def generate_keys(): """Generate a new pair of private and public key.""" private_key = RSA.generate(1024, Cryptodome.Random.new().read) public_key = private_key.publickey() return (binascii.hexlify( private_key.exportKey(format="DER")).decode("ascii"), binascii.hexlify(public_key.publickey().exportKey( format="DER")).decode("ascii"))
def create_managed_rsa_key(self, length): """ Create an RSA key with a given length. Basically the same as oidc_provider.creatersakey but with configurable key length. """ key = RSA.generate(length) rsakey = RSAKey.objects.create(key=key.exportKey('PEM').decode('utf8')) ManagedRSAKey.objects.create(rsakey=rsakey, created_at=timezone.now()) self.stdout.write('Created new key of length {0} with id: {1}'.format(length, rsakey))
def runTest(self): key = RSA.generate(1024) hashed = SHA1.new(b("Test")) good_signature = PKCS1_PSS.new(key).sign(hashed) verifier = PKCS1_PSS.new(key.publickey()) self.assertEqual(verifier.verify(hashed, good_signature), True) # Flip a few bits in the signature bad_signature = strxor(good_signature, bchr(1) * len(good_signature)) self.assertEqual(verifier.verify(hashed, bad_signature), False)
def rsa_generate(rsa_key_len, id_rsa_pub_path, id_rsa_path): if not os.path.exists(os.path.dirname(id_rsa_path)): os.makedirs(os.path.dirname(id_rsa_path)) logger.info("Generating a %d bit RSA key pair...", rsa_key_len) keys = RSA.generate(rsa_key_len) logger.debug("Finished generating RSA key pair, writing to disk...") with open(id_rsa_pub_path, "wb") as id_rsa_pub: id_rsa_pub.write(keys.publickey().exportKey()) with open(id_rsa_path, "wb") as id_rsa: id_rsa.write(keys.exportKey()) del keys
def _generate_key_pair(self): """ Generates an asymmetric key pair and returns the JWK of its public keys and keypair. """ rsa_key = RSA.generate(2048) rsa_jwk = jwk.RSAKey(kid="key_id", key=rsa_key) public_keys = jwk.KEYS() public_keys.append(rsa_jwk) serialized_public_keys_json = public_keys.dump_jwks() serialized_keypair = rsa_jwk.serialize(private=True) serialized_keypair_json = json.dumps(serialized_keypair) return serialized_public_keys_json, serialized_keypair_json
def id_token_as_signed_jwt(self, session, loa="2", alg="", code=None, access_token=None, user_info=None, auth_time=0, exp=None, extra_claims=None, **kwargs): kwargs = {} if "rotsig" in self.behavior_type: # Rollover signing keys if alg == "RS256": key = RSAKey(kid="rotated_rsa_{}".format(time.time()), use="sig").load_key(RSA.generate(2048)) else: # alg == "ES256" key = ECKey(kid="rotated_ec_{}".format(time.time()), use="sig").load_key(P256) new_keys = {"keys": [key.serialize(private=True)]} self.events.store("New signing keys", new_keys) self.do_key_rollover(new_keys, "%d") self.events.store("Rotated signing keys", '') if "nokid1jwks" in self.behavior_type: kwargs['keys'] = self.no_kid_keys() # found_key = None # for kb in self.keyjar.key_summary[""]: # issuer_key = list(kb.keys())[0] # if issuer_key.use == "sig" and \ # issuer_key.kty.startswith( # alg[:2]): # issuer_key.kid = None # found_key = key # break # self.keyjar.key_summary[""] = [found_key] if "nokidmuljwks" in self.behavior_type: kwargs['keys'] = self.no_kid_keys() # for key in self.keyjar.key_summary[""]: # for inner_key in list(key.keys()): # inner_key.kid = None _jws = provider.Provider.id_token_as_signed_jwt( self, session, loa=loa, alg=alg, code=code, access_token=access_token, user_info=user_info, auth_time=auth_time, exp=exp, extra_claims=extra_claims, **kwargs) if "idts" in self.behavior_type: # mess with the signature # p = _jws.split(".") p[2] = sort_string(p[2]) _jws = ".".join(p) return _jws
def generateRSAKey1(passPhrase): print ('encrypting..... key') key = RSA.generate(2048) encrypted_key = key.exportKey(passphrase=passPhrase, pkcs=8, protection="scryptAndAES128-CBC") print ('creating....... PrivateKey') file = open(RSA_privKeyFile, "wb") file.write(encrypted_key) file.close() print ('creating....... PublicKey') file = open(RSA_pubKeyFile, "wb") file.write(key.publickey().exportKey()) file.close()
def generateRSAKey(): from Cryptodome.PublicKey import RSA secret_code = "Unguessable" key = RSA.generate(2048) encrypted_key = key.exportKey(passphrase=secret_code, pkcs=8, protection="scryptAndAES128-CBC") file = open("rsa_key.bin", "wb") file.write(encrypted_key) file.close() file = open("rsa_pub.bin", "wb") file.write(key.publickey().exportKey()) file.close()
def update(self, msg, state, key_size=0): """ Used to 'update' the AccessToken Request :param msg: :param state: Used to map access token response to this request :param key_size: :return: """ if not key_size: key_size = self.key_size key = RSAKey(key=RSA.generate(key_size)) self.state2key[state] = key msg['key'] = json.dumps(key.serialize()) return msg
def runTest(self): key = RSA.generate(1280) signer = pss.new(key) hash_names = ("MD2", "MD4", "MD5", "RIPEMD160", "SHA1", "SHA224", "SHA256", "SHA384", "SHA512", "SHA3_224", "SHA3_256", "SHA3_384", "SHA3_512") for name in hash_names: hashed = load_hash_by_name(name).new(b("Test")) signer.sign(hashed) from Cryptodome.Hash import BLAKE2b, BLAKE2s for hash_size in (20, 32, 48, 64): hashed_b = BLAKE2b.new(digest_bytes=hash_size, data=b("Test")) signer.sign(hashed_b) for hash_size in (16, 20, 28, 32): hashed_s = BLAKE2s.new(digest_bytes=hash_size, data=b("Test")) signer.sign(hashed_s)
def create_and_store_rsa_key_pair(name="pyoidc", path=".", size=2048): """ :param name: Name of the key file :param path: Path to where the key files are stored :param size: RSA key size :return: RSA key """ key = RSA.generate(size) if name: with open(os.path.join(path, name), 'wb') as f: f.write(key.exportKey('PEM')) _pub_key = key.publickey() with open(os.path.join(path, '{}.pub'.format(name)), 'wb') as f: f.write(_pub_key.exportKey('PEM')) return key
def create_and_store_rsa_key_pair(name="pyoidc", path=".", size=1024): key = RSA.generate(size) keyfile = os.path.join(path, name) f = open("%s.key" % keyfile, "w") f.write(key.exportKey("PEM")) f.close() f = open("%s.pub" % keyfile, "w") f.write(key.publickey().exportKey("PEM")) f.close() rsa_key = RSAKey(key=key) rsa_key.serialize() # This will create JWK from the public RSA key jwk_spec = json.dumps(rsa_key.to_dict(), "enc") f = open(keyfile + ".jwk", "w") f.write(str(jwk_spec)) f.close() return key
def generateRSAKey(passPhrase): print ('generating..... key') from Cryptodome.PublicKey import RSA from Cryptodome import Random random_generator = Random.new().read key = RSA.generate(2048, random_generator) print ('created.......', key) print ('encrypting..... key') encrypted_key = key.exportKey(passphrase=passPhrase, pkcs=8, protection="scryptAndAES128-CBC") print ('creating....... PrivateKey to file:', RSA_privKeyFile) file = open(RSA_privKeyFile, "wb") file.write(encrypted_key) file.close() print ('creating....... PublicKey to file:', RSA_pubKeyFile) file = open(RSA_pubKeyFile, "wb") file.write(key.publickey().exportKey()) file.close() print ('key.can_encrypt......: ', key.can_encrypt()) print ('key.can_sign.........: ', key.can_sign()) print ('key.has_private......: ', key.has_private())
def setUp(self): self.rng = Random.new().read self.key1024 = RSA.generate(1024, self.rng)
def __init_generate_rsa_keys(self): self.kodi_helper.log(msg='Create new RSA Keys') # Create new Key Pair and save self.rsa_key = RSA.generate(2048)
def signing_key(self): return RSAKey(key=RSA.generate(2048), alg="RS256")
def rsa_key(): key = RSA.generate(1024) rsakey = RSAKey(key=key.exportKey('PEM').decode('utf8')) rsakey.save() return rsakey
from Cryptodome.PublicKey import DSA as pycryptodomex_dsa from Cryptodome.PublicKey import RSA as pycryptodomex_rsa # Correct dsa.generate_private_key(key_size=2048, backend=backends.default_backend()) ec.generate_private_key(curve=ec.SECP384R1, backend=backends.default_backend()) rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=backends.default_backend()) pycrypto_dsa.generate(bits=2048) pycrypto_rsa.generate(bits=2048) pycryptodomex_dsa.generate(bits=2048) pycryptodomex_rsa.generate(bits=2048) # Also correct: without keyword args dsa.generate_private_key(4096, backends.default_backend()) ec.generate_private_key(ec.SECP256K1, backends.default_backend()) rsa.generate_private_key(3, 4096, backends.default_backend()) pycrypto_dsa.generate(4096) pycrypto_rsa.generate(4096) pycryptodomex_dsa.generate(4096) pycryptodomex_rsa.generate(4096) # Incorrect: weak key sizes
def generate_keys(self): private_key = RSA.generate(1024, Cryptodome.Random.new().read) public_key = private_key.publickey() return (binascii.hexlify(private_key.export_key(format='DER')).decode('ascii'), binascii.hexlify(public_key.export_key(format='DER')).decode('ascii'))
def authorization_endpoint(self, request="", cookie=None, **kwargs): _req = parse_qs(request) #self.events.store(EV_REQUEST, _req) try: _scope = _req["scope"] except KeyError: return self._error( error="incorrect_behavior", descr="No scope parameter" ) else: # verify that openid is among the scopes _scopes = _scope[0].split(" ") if "openid" not in _scopes: return self._error( error="incorrect_behavior", descr="Scope does not contain 'openid'" ) client_id = _req["client_id"][0] try: f = response_type_cmp(kwargs['test_cnf']['response_type'], _req['response_type']) except KeyError: pass else: if f is False: self.events.store( EV_FAULT, 'Wrong response type: {}'.format(_req['response_type'])) return self._error_response(error="incorrect_behavior", descr="Wrong response_type") _rtypes = [] for rt in _req['response_type']: _rtypes.extend(rt.split(' ')) if 'id_token' in _rtypes: try: self._update_client_keys(client_id) except TestError: return self._error(error="incorrect_behavior", descr="No change in client keys") _response = provider.Provider.authorization_endpoint(self, request, cookie, **kwargs) if "rotenc" in self.behavior_type: # Rollover encryption keys rsa_key = RSAKey(kid="rotated_rsa_{}".format(time.time()), use="enc").load_key(RSA.generate(2048)) ec_key = ECKey(kid="rotated_ec_{}".format(time.time()), use="enc").load_key(P256) keys = [rsa_key.serialize(private=True), ec_key.serialize(private=True)] new_keys = {"keys": keys} self.events.store("New encryption keys", new_keys) self.do_key_rollover(new_keys, "%d") self.events.store("Rotated encryption keys", '') logger.info( 'Rotated OP enc keys, new set: {}'.format( key_summary(self.keyjar, ''))) # This is just for logging purposes try: _resp = self.server.http_request(_req["request_uri"][0]) except KeyError: pass else: if _resp.status_code == 200: self.events.store(EV_REQUEST, "Request from request_uri: {}".format(_resp.text)) return _response
def test_can_sign(self): test_public_key = RSA.generate(1024).publickey() verifier = pss.new(test_public_key) self.assertEqual(verifier.can_sign(), False)
def _generate_key_pair(self, key_size, key_id): log.info('Generating new JWT signing keypair for key id %s.', key_id) rsa_key = RSA.generate(key_size) rsa_jwk = jwk.RSAKey(kid=key_id, key=rsa_key) return rsa_jwk
def test_can_sign(self): test_private_key = RSA.generate(1024) signer = pss.new(test_private_key) self.assertEqual(signer.can_sign(), True)
def generateKey(): return RSA.generate(2048)
def authorization_endpoint(self, request="", cookie=None, **kwargs): if isinstance(request, dict): _req = request else: _req = {} for key, val in parse_qs(request).items(): if len(val) == 1: _req[key] = val[0] else: _req[key] = val # self.events.store(EV_REQUEST, _req) try: _scope = _req["scope"] except KeyError: return error_response( error="incorrect_behavior", descr="No scope parameter" ) else: # verify that openid is among the scopes _scopes = _scope.split(" ") if "openid" not in _scopes: return error_response( error="incorrect_behavior", descr="Scope does not contain 'openid'" ) client_id = _req["client_id"] try: f = response_type_cmp(self.capabilities['response_types_supported'], _req['response_type']) except KeyError: pass else: if f is False: self.events.store( EV_FAULT, 'Wrong response type: {}'.format(_req['response_type'])) return error_response(error="incorrect_behavior", descr="Not supported response_type") _rtypes = _req['response_type'].split(' ') if 'id_token' in _rtypes: try: self._update_client_keys(client_id) except TestError: return error_response(error="incorrect_behavior", descr="No change in client keys") if isinstance(request, dict): request = urlencode(request) if "max_age" in _req and _req["max_age"] == "0" and "prompt" in _req and _req["prompt"] == "none": aresp = { "error": "login_required", } if "state" in _req: aresp['state'] = _req["state"] return self.response_mode(_req, False, aresp=aresp, redirect_uri=_req['redirect_uri'], headers={}) else: _response = provider.Provider.authorization_endpoint(self, request, cookie, **kwargs) if "rotenc" in self.behavior_type: # Rollover encryption keys rsa_key = RSAKey(kid="rotated_rsa_{}".format(time.time()), use="enc").load_key(RSA.generate(2048)) ec_key = ECKey(kid="rotated_ec_{}".format(time.time()), use="enc").load_key(P256) keys = [rsa_key.serialize(private=True), ec_key.serialize(private=True)] new_keys = {"keys": keys} self.events.store("New encryption keys", new_keys) self.do_key_rollover(new_keys, "%d") self.events.store("Rotated encryption keys", '') logger.info( 'Rotated OP enc keys, new set: {}'.format( key_summary(self.keyjar, ''))) # This is just for logging purposes try: _resp = self.server.http_request(_req["request_uri"]) except KeyError: pass except requests.ConnectionError as err: self.events.store(EV_EXCEPTION, err) err = unwrap_exception(err) return error_response(error="server_error", descr=err) else: if _resp.status_code == 200: self.events.store(EV_REQUEST, "Request from request_uri: {}".format( _resp.text)) return _response