How to use the cryptography.hazmat.primitives.serialization.NoEncryption function in cryptography

To help you get started, we’ve selected a few cryptography examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pyca / cryptography / tests / hazmat / primitives / test_ec.py View on Github external
def test_private_bytes_rejects_invalid(self, encoding, fmt, backend):
        _skip_curve_unsupported(backend, ec.SECP256R1())
        key = ec.generate_private_key(ec.SECP256R1(), backend)
        with pytest.raises(ValueError):
            key.private_bytes(encoding, fmt, serialization.NoEncryption())
github AVSystem / Anjay / test / integration / suites / default / firmware_update.py View on Github external
key = rsa.generate_private_key(public_exponent=65537, key_size=2048,
                                           backend=default_backend())
            name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn or '127.0.0.1')])
            now = datetime.datetime.utcnow()
            cert = (x509.CertificateBuilder().
                    subject_name(name).
                    issuer_name(name).
                    public_key(key.public_key()).
                    serial_number(1000).
                    not_valid_before(now).
                    not_valid_after(now + datetime.timedelta(days=1)).
                    sign(key, hashes.SHA256(), default_backend()))
            cert_pem = cert.public_bytes(encoding=serialization.Encoding.PEM)
            key_pem = key.private_bytes(encoding=serialization.Encoding.PEM,
                                        format=serialization.PrivateFormat.TraditionalOpenSSL,
                                        encryption_algorithm=serialization.NoEncryption())
            return cert_pem, key_pem
github ProgVal / Limnoria / plugins / Fediverse / activitypub.py View on Github external
def _get_private_key():
    path = conf.supybot.directories.data.dirize("Fediverse/instance_key.pem")
    if not os.path.isfile(path):
        os.makedirs(os.path.dirname(path), exist_ok=True)
        key = _generate_private_key()
        pem = key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption(),
        )
        with open(path, "wb") as fd:
            fd.write(pem)

    with open(path, "rb") as fd:
        return serialization.load_pem_private_key(
            fd.read(), password=None, backend=default_backend()
        )
github google / rekall / rekall-agent / rekall_agent / crypto.py View on Github external
def to_primitive(self):
        if not self._value:
            raise RuntimeError("Key not initialized yet.")

        return self._value.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption())
github cmdmnt / commandment / commandment / threads / startup_thread.py View on Github external
if not os.path.exists(pem_key_path) or not os.path.exists(pem_certificate_path):
                app.logger.info('You provided a PKCS#12 push certificate, we will have to encode it as PEM to continue...')
                app.logger.info('.key and .crt files will be saved in the same location: %s, %s', pem_key_path, pem_certificate_path)
                with open(push_certificate_path, 'rb') as fd:
                    if 'PUSH_CERTIFICATE_PASSWORD' in app.config:
                        key, certificate, intermediates = parse_pkcs12(fd.read(), bytes(app.config['PUSH_CERTIFICATE_PASSWORD'], 'utf8'))
                    else:
                        key, certificate, intermediates = parse_pkcs12(fd.read())

                try:
                    crypto_key = serialization.load_der_private_key(key.dump(), None, default_backend())
                    with open(pem_key_path, 'wb') as fd:
                        fd.write(crypto_key.private_bytes(
                            encoding=serialization.Encoding.PEM,
                            format=serialization.PrivateFormat.PKCS8,
                            encryption_algorithm=serialization.NoEncryption()))

                    crypto_cert = x509.load_der_x509_certificate(certificate.dump(), default_backend())
                    with open(pem_certificate_path, 'wb') as fd:
                        fd.write(crypto_cert.public_bytes(serialization.Encoding.PEM))
                except PermissionError:
                    app.logger.error('Could not write out .key or .crt file. You will not be able to push APNS messages')
                    app.logger.error('This means your MDM is BROKEN until you fix permissions')
            else:
                app.logger.info('.p12 already split into PEM/KEY components')
github freenas / freenas / src / middlewared / middlewared / plugins / crypto.py View on Github external
key = ec.generate_private_key(
                getattr(ec, options.get('curve')),
                default_backend()
            )
        else:
            key = rsa.generate_private_key(
                public_exponent=65537,
                key_size=options.get('key_length'),
                backend=default_backend()
            )

        if options.get('serialize'):
            return key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption()
            ).decode()
        else:
            return key
github MatteoGuadrini / Butterfly-Backup / bb.py View on Github external
from cryptography.hazmat.backends import default_backend

    if not dry_run('Generate private/public key pair'):
        # Generate private/public key pair
        print_verbose(args.verbose, 'Generate private/public key pair')
        private_key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537,
                                               key_size=2048)
        # Get public key in OpenSSH format
        print_verbose(args.verbose, 'Get public key in OpenSSH format')
        public_key = private_key.public_key().public_bytes(serialization.Encoding.OpenSSH,
                                                           serialization.PublicFormat.OpenSSH)
        # Get private key in PEM container format
        print_verbose(args.verbose, 'Get private key in PEM container format')
        pem = private_key.private_bytes(encoding=serialization.Encoding.PEM,
                                        format=serialization.PrivateFormat.TraditionalOpenSSL,
                                        encryption_algorithm=serialization.NoEncryption())
        # Decode to printable strings
        private_key_str = pem.decode('utf-8')
        public_key_str = public_key.decode('utf-8')
        # Create home path
        home = os.path.expanduser('~')
        # Create folder .ssh
        ssh_folder = os.path.join(home, '.ssh')
        print_verbose(args.verbose, 'Create folder {0}'.format(ssh_folder))
        if not os.path.exists(ssh_folder):
            os.mkdir(ssh_folder, mode=0o755)
        # Create private key file
        id_rsa_file = os.path.join(ssh_folder, 'id_rsa')
        print_verbose(args.verbose, 'Create private key file {0}'.format(id_rsa_file))
        if not os.path.exists(id_rsa_file):
            with open(id_rsa_file, 'w') as id_rsa:
                os.chmod(id_rsa_file, mode=0o600)
github apache / airflow / airflow / contrib / hooks / snowflake_hook.py View on Github external
private_key_file = conn.extra_dejson.get('private_key_file', None)
        if private_key_file:
            with open(private_key_file, "rb") as key:
                passphrase = None
                if conn.password:
                    passphrase = conn.password.strip().encode()

                p_key = serialization.load_pem_private_key(
                    key.read(),
                    password=passphrase,
                    backend=default_backend()
                )

            pkb = p_key.private_bytes(encoding=serialization.Encoding.DER,
                                      format=serialization.PrivateFormat.PKCS8,
                                      encryption_algorithm=serialization.NoEncryption())

            conn_config['private_key'] = pkb
            conn_config.pop('password', None)

        return conn_config
github IntelAI / nauta / applications / cli / git_repo_manager / client.py View on Github external
def _generate_ssh_key(self, key_bits=4096) -> Tuple[str, str]:
        key = rsa.generate_private_key(public_exponent=65537, key_size=key_bits, backend=default_backend())
        private_key = key.private_bytes(encoding=serialization.Encoding.PEM,
                                        format=serialization.PrivateFormat.TraditionalOpenSSL,
                                        encryption_algorithm=serialization.NoEncryption()).decode(_encoding)
        public_key = key.public_key().public_bytes(encoding=serialization.Encoding.OpenSSH,
                                                   format=serialization.PublicFormat.OpenSSH).decode(_encoding)
        return private_key, public_key
github aws / aws-ec2-instance-connect-cli / ec2instanceconnectcli / key_utils.py View on Github external
if encoding == 'OpenSSH':
        assert(not return_private)
        enc = crypto_serialization.Encoding.OpenSSH
    elif encoding == 'PEM':
        enc = crypto_serialization.Encoding.PEM
    elif encoding == 'DER':
        enc = crypto_serialization.Encoding.DER
    else:
        raise AssertionError('Unrecognized encoding {0}'.format(encoding))

    if return_private:
        if password:
            enc_alg = crypto_serialization.BestAvailableEncryption(password)
        else:
            enc_alg = crypto_serialization.NoEncryption()

        return key.private_bytes(
            encoding=enc,
            format=crypto_serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=enc_alg
        )

    else:
        if encoding == 'OpenSSH':
            format = crypto_serialization.PublicFormat.OpenSSH
        else:
            format = crypto_serialization.PublicFormat.SubjectPublicKeyInfo

        return key.public_key().public_bytes(
            encoding=enc,
            format=format