Python cryptography.hazmat.primitives.serialization.load_pem_public_key() Examples
The following are 30
code examples of cryptography.hazmat.primitives.serialization.load_pem_public_key().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cryptography.hazmat.primitives.serialization
, or try the search function
.
Example #1
Source File: utils.py From wechatpy with MIT License | 7 votes |
def rsa_encrypt(data, pem, b64_encode=True): """ rsa 加密 :param data: 待加密字符串/binary :param pem: RSA public key 内容/binary :param b64_encode: 是否对输出进行 base64 encode :return: 如果 b64_encode=True 的话,返回加密并 base64 处理后的 string;否则返回加密后的 binary """ from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding encoded_data = to_binary(data) pem = to_binary(pem) public_key = serialization.load_pem_public_key(pem, backend=default_backend()) encrypted_data = public_key.encrypt( encoded_data, padding=padding.OAEP(mgf=padding.MGF1(hashes.SHA1()), algorithm=hashes.SHA1(), label=None,), ) if b64_encode: encrypted_data = base64.b64encode(encrypted_data).decode("utf-8") return encrypted_data
Example #2
Source File: key_utils.py From aws-ec2-instance-connect-cli with Apache License 2.0 | 7 votes |
def convert_pem_to_der(pem_key): """ Converts a given key from PEM to DER format. :param pem_key: PEM-encoded key bytes :type pem_key: bytearray :return: DER-encoded key bytes :rtype: bytearray """ first_line = pem_key.decode().split('\n', 1)[0] is_private = first_line == begin_key.format(private_str) if is_private: loaded_key = crypto_serialization.load_pem_private_key(pem_key, backend=crypto_default_backend()) return serialize_key(loaded_key, encoding='DER', return_private=is_private) else: loaded_key = crypto_serialization.load_pem_public_key(pem_key, backend=crypto_default_backend()) return loaded_key.public_bytes(encoding=crypto_serialization.Encoding.DER, format=crypto_serialization.PublicFormat.SubjectPublicKeyInfo)
Example #3
Source File: keys.py From fence with Apache License 2.0 | 6 votes |
def _rsa_public_numbers(public_key_data): """ Take the data for a public key (string of the key in PEM format) and return the public key modulus ``n`` and exponent ``e`` for that key. The values of n and e are needed for the return of the JWKS endpoint. Args: public_key_data (str): the public key Return: Tuple[int, int]: the public key modulus ``n`` and exponent ``e`` """ key = serialization.load_pem_public_key( bytes(public_key_data, "utf-8"), default_backend() ) numbers = key.public_numbers() return (numbers.n, numbers.e)
Example #4
Source File: _auth.py From addon with GNU General Public License v3.0 | 6 votes |
def sha2_rsa_encrypt(password, salt, public_key): """Encrypt password with salt and public_key. Used for sha256_password and caching_sha2_password. """ if not _have_cryptography: raise RuntimeError("cryptography is required for sha256_password or caching_sha2_password") message = _xor_password(password + b'\0', salt) rsa_key = serialization.load_pem_public_key(public_key, default_backend()) return rsa_key.encrypt( message, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None, ), )
Example #5
Source File: app_config.py From dash-masternode-tool with MIT License | 6 votes |
def set_rpc_encryption_pubkey(self, key: str): """ AES public key for additional RPC encryption, dedicated for calls transmitting sensitive information like protx. Accepted formats: PEM, DER. """ try: if key: # validate public key by deserializing it if re.fullmatch(r'^([0-9a-fA-F]{2})+$', key): serialization.load_der_public_key(bytes.fromhex(key), backend=default_backend()) else: pubkey = serialization.load_pem_public_key(key.encode('ascii'), backend=default_backend()) raw = pubkey.public_bytes(serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo) key = raw.hex() if self.__rpc_encryption_pubkey_object and (self.__rpc_encryption_pubkey_der != key or not key): self.__rpc_encryption_pubkey_der = None self.__rpc_encryption_pubkey_der = key except Exception as e: logging.exception('Exception occurred') raise
Example #6
Source File: models.py From asymmetric-jwt-auth with ISC License | 6 votes |
def validate_public_key(value): """ Check that the given value is a valid RSA Public key in either PEM or OpenSSH format. If it is invalid, raises ``django.core.exceptions.ValidationError``. """ is_valid = False exc = None for load in (load_pem_public_key, load_ssh_public_key): if not is_valid: try: load(value.encode('utf-8'), default_backend()) is_valid = True except Exception as e: exc = e if not is_valid: raise ValidationError('Public key is invalid: %s' % exc)
Example #7
Source File: _auth.py From teleport with Apache License 2.0 | 6 votes |
def sha2_rsa_encrypt(password, salt, public_key): """Encrypt password with salt and public_key. Used for sha256_password and caching_sha2_password. """ if not _have_cryptography: raise RuntimeError("cryptography is required for sha256_password or caching_sha2_password") message = _xor_password(password + b'\0', salt) rsa_key = serialization.load_pem_public_key(public_key, default_backend()) return rsa_key.encrypt( message, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None, ), )
Example #8
Source File: _auth.py From teleport with Apache License 2.0 | 6 votes |
def sha2_rsa_encrypt(password, salt, public_key): """Encrypt password with salt and public_key. Used for sha256_password and caching_sha2_password. """ if not _have_cryptography: raise RuntimeError("cryptography is required for sha256_password or caching_sha2_password") message = _xor_password(password + b'\0', salt) rsa_key = serialization.load_pem_public_key(public_key, default_backend()) return rsa_key.encrypt( message, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None, ), )
Example #9
Source File: engine.py From appkernel with Apache License 2.0 | 6 votes |
def __init_crypto(self): # https://stackoverflow.com/questions/29650495/how-to-verify-a-jwt-using-python-pyjwt-with-public-key with self.app.app_context(): with open('{}/keys/appkernel.pem'.format(self.cfg_dir), "rb") as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend() ) config.private_key = private_key with open('{}/keys/appkernel.pub'.format(self.cfg_dir), 'rb') as key_file: public_key = serialization.load_pem_public_key( key_file.read(), backend=default_backend() ) config.public_key = public_key
Example #10
Source File: _auth.py From scalyr-agent-2 with Apache License 2.0 | 6 votes |
def sha2_rsa_encrypt(password, salt, public_key): """Encrypt password with salt and public_key. Used for sha256_password and caching_sha2_password. """ if not _have_cryptography: raise RuntimeError("cryptography is required for sha256_password or caching_sha2_password") message = _xor_password(password + b'\0', salt) rsa_key = serialization.load_pem_public_key(public_key, default_backend()) return rsa_key.encrypt( message, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None, ), )
Example #11
Source File: wrapping_keys.py From aws-encryption-sdk-python with Apache License 2.0 | 6 votes |
def __init__(self, wrapping_algorithm, wrapping_key, wrapping_key_type, password=None): """Prepares initial values.""" self.wrapping_algorithm = wrapping_algorithm self.wrapping_key_type = wrapping_key_type if wrapping_key_type is EncryptionKeyType.PRIVATE: self._wrapping_key = serialization.load_pem_private_key( data=wrapping_key, password=password, backend=default_backend() ) elif wrapping_key_type is EncryptionKeyType.PUBLIC: self._wrapping_key = serialization.load_pem_public_key(data=wrapping_key, backend=default_backend()) elif wrapping_key_type is EncryptionKeyType.SYMMETRIC: self._wrapping_key = wrapping_key self._derived_wrapping_key = derive_data_encryption_key( source_key=self._wrapping_key, algorithm=self.wrapping_algorithm.algorithm, message_id=None ) else: raise InvalidDataKeyError("Invalid wrapping_key_type: {}".format(wrapping_key_type))
Example #12
Source File: Trust.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
def __init__(self, public_key_filename: str, pre_err_handler: Callable[[str], None] = None) -> None: """Initializes a Trust object. A Trust object represents a public key and related utility methods on that key. If the application only has a single public key, it's best to use 'getInstance' or 'getInstanceOrNone'. :param public_key_filename: Path to the file that holds the public key. :param pre_err_handler: An extra error handler which will be called before TrustBasics.defaultViolationHandler Receives a human readable error string as argument. :raise Exception: if public key file provided by the argument can't be found or parsed. """ self._public_key = None # type: Optional[RSAPublicKey] try: with open(public_key_filename, "rb") as file: self._public_key = load_pem_public_key(file.read(), backend = default_backend()) except: # Yes, we do really want this on _every_ exception that might occur. self._public_key = None raise Exception("e", "Couldn't load public-key '{0}'.".format(public_key_filename)) # NOTE: Handle _potential_ security violation outside of this initializer, in case it's just for validation. def violation_handler(message: str): if pre_err_handler is not None: pre_err_handler(message) TrustBasics.defaultViolationHandler(message=message) self._violation_handler = violation_handler # type: Callable[[str], None]
Example #13
Source File: travis_pypi_setup.py From pyseqlogo with MIT License | 5 votes |
def load_key(pubkey): """Load public RSA key. Work around keys with incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())
Example #14
Source File: webhook.py From zeus with Apache License 2.0 | 5 votes |
def get_travis_public_key(domain) -> str: cache_key = "travis:public-key:{}".format(domain) public_key = redis.get(cache_key) if public_key is None: resp = requests.get( "https://{}/config".format(domain), headers={"User-Agent": USER_AGENT} ) resp.raise_for_status() public_key = resp.json()["config"]["notifications"]["webhook"][ "public_key" ].encode("utf-8") redis.setex(cache_key, 300, public_key) return serialization.load_pem_public_key(public_key, backend=default_backend())
Example #15
Source File: travis_pypi_setup.py From devon with MIT License | 5 votes |
def load_key(pubkey): """Load public RSA key, with work-around for keys using incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())
Example #16
Source File: kmip_secret_store.py From sgx-kms with Apache License 2.0 | 5 votes |
def get_public_key_der_pkcs1(pem): """Converts PEM public key to DER PKCS1""" rsa_public = serialization.load_pem_public_key( pem, backend=default_backend()) pem_pkcs1 = rsa_public.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.PKCS1) return convert_pem_to_der(pem_pkcs1)
Example #17
Source File: travis_pypi_setup.py From statsnba-playbyplay with MIT License | 5 votes |
def load_key(pubkey): """Load public RSA key, with work-around for keys using incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())
Example #18
Source File: travis_pypi_setup.py From visualqc with Apache License 2.0 | 5 votes |
def load_key(pubkey): """Load public RSA key. Work around keys with incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())
Example #19
Source File: travis_pypi_setup.py From plumbery with Apache License 2.0 | 5 votes |
def load_key(pubkey): """Load public RSA key, with work-around for keys using incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())
Example #20
Source File: cryptography_backend.py From python-jose with MIT License | 5 votes |
def __init__(self, key, algorithm, cryptography_backend=default_backend): if algorithm not in ALGORITHMS.RSA: raise JWKError('hash_alg: %s is not a valid hash algorithm' % algorithm) self.hash_alg = { ALGORITHMS.RS256: self.SHA256, ALGORITHMS.RS384: self.SHA384, ALGORITHMS.RS512: self.SHA512 }.get(algorithm) self._algorithm = algorithm self.cryptography_backend = cryptography_backend # if it conforms to RSAPublicKey interface if hasattr(key, 'public_bytes') and hasattr(key, 'public_numbers'): self.prepared_key = key return if isinstance(key, dict): self.prepared_key = self._process_jwk(key) return if isinstance(key, six.string_types): key = key.encode('utf-8') if isinstance(key, six.binary_type): try: if key.startswith(b'-----BEGIN CERTIFICATE-----'): self._process_cert(key) return try: self.prepared_key = load_pem_public_key(key, self.cryptography_backend()) except ValueError: self.prepared_key = load_pem_private_key(key, password=None, backend=self.cryptography_backend()) except Exception as e: raise JWKError(e) return raise JWKError('Unable to parse an RSA_JWK from key: %s' % key)
Example #21
Source File: travis_pypi_setup.py From drf_openapi with MIT License | 5 votes |
def load_key(pubkey): """Load public RSA key. Work around keys with incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())
Example #22
Source File: _cryptography_rsa.py From alfred-gmail with MIT License | 5 votes |
def from_string(cls, public_key): """Construct an Verifier instance from a public key or public certificate string. Args: public_key (Union[str, bytes]): The public key in PEM format or the x509 public key certificate. Returns: Verifier: The constructed verifier. Raises: ValueError: If the public key can't be parsed. """ public_key_data = _helpers.to_bytes(public_key) if _CERTIFICATE_MARKER in public_key_data: cert = cryptography.x509.load_pem_x509_certificate( public_key_data, _BACKEND) pubkey = cert.public_key() else: pubkey = serialization.load_pem_public_key( public_key_data, _BACKEND) return cls(pubkey)
Example #23
Source File: travis_pypi_setup.py From kibitzr with MIT License | 5 votes |
def load_key(pubkey): """Load public RSA key, with work-around for keys using incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())
Example #24
Source File: travis_pypi_setup.py From underthesea with GNU General Public License v3.0 | 5 votes |
def load_key(pubkey): """Load public RSA key, with work-around for keys using incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())
Example #25
Source File: travis_pypi_setup.py From swagger-aggregator with MIT License | 5 votes |
def load_key(pubkey): """Load public RSA key, with work-around for keys using incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())
Example #26
Source File: travis_pypi_setup.py From logzero with MIT License | 5 votes |
def load_key(pubkey): """Load public RSA key. Work around keys with incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())
Example #27
Source File: travis_pypi_setup.py From hydrofunctions with MIT License | 5 votes |
def load_key(pubkey): """Load public RSA key, with work-around for keys using incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace("BEGIN RSA", "BEGIN").replace("END RSA", "END") return load_pem_public_key(pubkey.encode(), default_backend())
Example #28
Source File: travis_pypi_setup.py From pyucwa with Apache License 2.0 | 5 votes |
def load_key(pubkey): """Load public RSA key, with work-around for keys using incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())
Example #29
Source File: travis_pypi_setup.py From pydrill with MIT License | 5 votes |
def load_key(pubkey): """Load public RSA key, with work-around for keys using incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())
Example #30
Source File: travis_pypi_setup.py From ny-power with Apache License 2.0 | 5 votes |
def load_key(pubkey): """Load public RSA key. Work around keys with incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend())