Python cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicNumbers() Examples

The following are 22 code examples of cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicNumbers(). 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.asymmetric.dsa , or try the search function .
Example #1
Source File: dsskey.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
def write_private_key(self, file_obj, password=None):
        key = dsa.DSAPrivateNumbers(
            x=self.x,
            public_numbers=dsa.DSAPublicNumbers(
                y=self.y,
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=self.p,
                    q=self.q,
                    g=self.g
                )
            )
        ).private_key(backend=default_backend())

        self._write_private_key(
            file_obj,
            key,
            serialization.PrivateFormat.TraditionalOpenSSL,
            password=password
        ) 
Example #2
Source File: dsskey.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
def write_private_key_file(self, filename, password=None):
        key = dsa.DSAPrivateNumbers(
            x=self.x,
            public_numbers=dsa.DSAPublicNumbers(
                y=self.y,
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=self.p,
                    q=self.q,
                    g=self.g
                )
            )
        ).private_key(backend=default_backend())

        self._write_private_key_file(
            filename,
            key,
            serialization.PrivateFormat.TraditionalOpenSSL,
            password=password
        ) 
Example #3
Source File: ssh.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _load_ssh_dss_public_key(key_type, decoded_data, backend):
    p, rest = _ssh_read_next_mpint(decoded_data)
    q, rest = _ssh_read_next_mpint(rest)
    g, rest = _ssh_read_next_mpint(rest)
    y, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    parameter_numbers = dsa.DSAParameterNumbers(p, q, g)
    public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers)

    return public_numbers.public_key(backend) 
Example #4
Source File: ssh.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _load_ssh_dss_public_key(key_type, decoded_data, backend):
    p, rest = _ssh_read_next_mpint(decoded_data)
    q, rest = _ssh_read_next_mpint(rest)
    g, rest = _ssh_read_next_mpint(rest)
    y, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    parameter_numbers = dsa.DSAParameterNumbers(p, q, g)
    public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers)

    return public_numbers.public_key(backend) 
Example #5
Source File: ssh.py    From quickstart-redhat-openshift with Apache License 2.0 5 votes vote down vote up
def _load_ssh_dss_public_key(key_type, decoded_data, backend):
    p, rest = _ssh_read_next_mpint(decoded_data)
    q, rest = _ssh_read_next_mpint(rest)
    g, rest = _ssh_read_next_mpint(rest)
    y, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    parameter_numbers = dsa.DSAParameterNumbers(p, q, g)
    public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers)

    return public_numbers.public_key(backend) 
Example #6
Source File: serialization.py    From quickstart-git2s3 with Apache License 2.0 5 votes vote down vote up
def _load_ssh_dss_public_key(key_type, decoded_data, backend):
    p, rest = _ssh_read_next_mpint(decoded_data)
    q, rest = _ssh_read_next_mpint(rest)
    g, rest = _ssh_read_next_mpint(rest)
    y, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    parameter_numbers = dsa.DSAParameterNumbers(p, q, g)
    public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers)

    return public_numbers.public_key(backend) 
Example #7
Source File: dsskey.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def verify_ssh_sig(self, data, msg):
        if len(msg.asbytes()) == 40:
            # spies.com bug: signature has no header
            sig = msg.asbytes()
        else:
            kind = msg.get_text()
            if kind != 'ssh-dss':
                return 0
            sig = msg.get_binary()

        # pull out (r, s) which are NOT encoded as mpints
        sigR = util.inflate_long(sig[:20], 1)
        sigS = util.inflate_long(sig[20:], 1)

        signature = encode_dss_signature(sigR, sigS)

        key = dsa.DSAPublicNumbers(
            y=self.y,
            parameter_numbers=dsa.DSAParameterNumbers(
                p=self.p,
                q=self.q,
                g=self.g
            )
        ).public_key(backend=default_backend())
        verifier = key.verifier(signature, hashes.SHA1())
        verifier.update(data)
        try:
            verifier.verify()
        except InvalidSignature:
            return False
        else:
            return True 
Example #8
Source File: dsskey.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def sign_ssh_data(self, data):
        key = dsa.DSAPrivateNumbers(
            x=self.x,
            public_numbers=dsa.DSAPublicNumbers(
                y=self.y,
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=self.p,
                    q=self.q,
                    g=self.g
                )
            )
        ).private_key(backend=default_backend())
        signer = key.signer(hashes.SHA1())
        signer.update(data)
        r, s = decode_dss_signature(signer.finalize())

        m = Message()
        m.add_string('ssh-dss')
        # apparently, in rare cases, r or s may be shorter than 20 bytes!
        rstr = util.deflate_long(r, 0)
        sstr = util.deflate_long(s, 0)
        if len(rstr) < 20:
            rstr = zero_byte * (20 - len(rstr)) + rstr
        if len(sstr) < 20:
            sstr = zero_byte * (20 - len(sstr)) + sstr
        m.add_string(rstr + sstr)
        return m 
Example #9
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __privkey__(self):
        params = dsa.DSAParameterNumbers(self.p, self.q, self.g)
        pn = dsa.DSAPublicNumbers(self.y, params)
        return dsa.DSAPrivateNumbers(self.x, pn).private_key(default_backend()) 
Example #10
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __pubkey__(self):
        params = dsa.DSAParameterNumbers(self.p, self.q, self.g)
        return dsa.DSAPublicNumbers(self.y, params).public_key(default_backend()) 
Example #11
Source File: serialization.py    From oss-ftp with MIT License 5 votes vote down vote up
def _load_ssh_dss_public_key(key_type, decoded_data, backend):
    p, rest = _read_next_mpint(decoded_data)
    q, rest = _read_next_mpint(rest)
    g, rest = _read_next_mpint(rest)
    y, rest = _read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    parameter_numbers = dsa.DSAParameterNumbers(p, q, g)
    public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers)

    return public_numbers.public_key(backend) 
Example #12
Source File: keys.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _fromDSAComponents(cls, y, p, q, g, x=None):
        """
        Build a key from DSA numerical components.

        @type y: L{int}
        @param y: The 'y' DSA variable.

        @type p: L{int}
        @param p: The 'p' DSA variable.

        @type q: L{int}
        @param q: The 'q' DSA variable.

        @type g: L{int}
        @param g: The 'g' DSA variable.

        @type x: L{int} or L{None}
        @param x: The 'x' DSA variable (optional for a public key)

        @rtype: L{Key}
        @return: A DSA key constructed from the values as given.
        """
        publicNumbers = dsa.DSAPublicNumbers(
            y=y, parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g))
        if x is None:
            # We have public components.
            keyObject = publicNumbers.public_key(default_backend())
        else:
            privateNumbers = dsa.DSAPrivateNumbers(
                x=x, public_numbers=publicNumbers)
            keyObject = privateNumbers.private_key(default_backend())

        return cls(keyObject) 
Example #13
Source File: keys.py    From python-sshpubkeys with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _process_ssh_dss(self, data):
        """Parses ssh-dsa public keys."""
        data_fields = {}
        current_position = 0
        for item in ("p", "q", "g", "y"):
            current_position, value = self._unpack_by_int(data, current_position)
            data_fields[item] = self._parse_long(value)

        q_bits = self._bits_in_number(data_fields["q"])
        p_bits = self._bits_in_number(data_fields["p"])
        if q_bits != self.DSA_N_LENGTH:
            raise InvalidKeyError("Incorrect DSA key parameters: bits(p)=%s, q=%s" % (self.bits, q_bits))
        if self.strict_mode:
            min_length = self.DSA_MIN_LENGTH_STRICT
            max_length = self.DSA_MAX_LENGTH_STRICT
        else:
            min_length = self.DSA_MIN_LENGTH_LOOSE
            max_length = self.DSA_MAX_LENGTH_LOOSE
        if p_bits < min_length:
            raise TooShortKeyError("%s key can not be shorter than %s bits (was %s)" % (self.key_type.decode(), min_length, p_bits))
        if p_bits > max_length:
            raise TooLongKeyError(
                "%s key data can not be longer than %s bits (was %s)" % (self.key_type.decode(), max_length, p_bits)
            )

        dsa_parameters = DSAParameterNumbers(data_fields["p"], data_fields["q"], data_fields["g"])
        self.dsa = DSAPublicNumbers(data_fields["y"], dsa_parameters).public_key(default_backend())
        self.bits = self.dsa.key_size

        return current_position 
Example #14
Source File: dsa.py    From securesystemslib with MIT License 5 votes vote down vote up
def create_pubkey(pubkey_info):
  """
  <Purpose>
    Create and return a DSAPublicKey object from the passed pubkey_info
    using pyca/cryptography.

  <Arguments>
    pubkey_info:
            The DSA pubkey info dictionary as specified by
            securesystemslib.formats.GPG_DSA_PUBKEY_SCHEMA

  <Exceptions>
    securesystemslib.exceptions.FormatError if
      pubkey_info does not match securesystemslib.formats.GPG_DSA_PUBKEY_SCHEMA

    securesystemslib.exceptions.UnsupportedLibraryError if
      the cryptography module is not available

  <Returns>
    A cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicKey based on the
    passed pubkey_info.

  """
  if not CRYPTO: # pragma: no cover
    raise securesystemslib.exceptions.UnsupportedLibraryError(NO_CRYPTO_MSG)

  securesystemslib.formats.GPG_DSA_PUBKEY_SCHEMA.check_match(pubkey_info)

  y = int(pubkey_info['keyval']['public']['y'], 16)
  g = int(pubkey_info['keyval']['public']['g'], 16)
  p = int(pubkey_info['keyval']['public']['p'], 16)
  q = int(pubkey_info['keyval']['public']['q'], 16)
  parameter_numbers = dsa.DSAParameterNumbers(p, q, g)
  pubkey = dsa.DSAPublicNumbers(y, parameter_numbers).public_key(
      backends.default_backend())

  return pubkey 
Example #15
Source File: ssh.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _load_ssh_dss_public_key(key_type, decoded_data, backend):
    p, rest = _ssh_read_next_mpint(decoded_data)
    q, rest = _ssh_read_next_mpint(rest)
    g, rest = _ssh_read_next_mpint(rest)
    y, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    parameter_numbers = dsa.DSAParameterNumbers(p, q, g)
    public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers)

    return public_numbers.public_key(backend) 
Example #16
Source File: ssh.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _load_ssh_dss_public_key(key_type, decoded_data, backend):
    p, rest = _ssh_read_next_mpint(decoded_data)
    q, rest = _ssh_read_next_mpint(rest)
    g, rest = _ssh_read_next_mpint(rest)
    y, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    parameter_numbers = dsa.DSAParameterNumbers(p, q, g)
    public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers)

    return public_numbers.public_key(backend) 
Example #17
Source File: serialization.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _load_ssh_dss_public_key(key_type, decoded_data, backend):
    p, rest = _ssh_read_next_mpint(decoded_data)
    q, rest = _ssh_read_next_mpint(rest)
    g, rest = _ssh_read_next_mpint(rest)
    y, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    parameter_numbers = dsa.DSAParameterNumbers(p, q, g)
    public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers)

    return public_numbers.public_key(backend) 
Example #18
Source File: serialization.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _load_ssh_dss_public_key(key_type, decoded_data, backend):
    p, rest = _ssh_read_next_mpint(decoded_data)
    q, rest = _ssh_read_next_mpint(rest)
    g, rest = _ssh_read_next_mpint(rest)
    y, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    parameter_numbers = dsa.DSAParameterNumbers(p, q, g)
    public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers)

    return public_numbers.public_key(backend) 
Example #19
Source File: keys.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _fromDSAComponents(cls, y, p, q, g, x=None):
        """
        Build a key from DSA numerical components.

        @type y: L{int}
        @param y: The 'y' DSA variable.

        @type p: L{int}
        @param p: The 'p' DSA variable.

        @type q: L{int}
        @param q: The 'q' DSA variable.

        @type g: L{int}
        @param g: The 'g' DSA variable.

        @type x: L{int} or L{None}
        @param x: The 'x' DSA variable (optional for a public key)

        @rtype: L{Key}
        @return: A DSA key constructed from the values as given.
        """
        publicNumbers = dsa.DSAPublicNumbers(
            y=y, parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g))
        if x is None:
            # We have public components.
            keyObject = publicNumbers.public_key(default_backend())
        else:
            privateNumbers = dsa.DSAPrivateNumbers(
                x=x, public_numbers=publicNumbers)
            keyObject = privateNumbers.private_key(default_backend())

        return cls(keyObject) 
Example #20
Source File: __init__.py    From signxml with Apache License 2.0 4 votes vote down vote up
def _verify_signature_with_pubkey(self, signed_info_c14n, raw_signature, key_value, der_encoded_key_value,
                                      signature_alg):
        if der_encoded_key_value is not None:
            key = load_der_public_key(b64decode(der_encoded_key_value.text), backend=default_backend())
        if "ecdsa-" in signature_alg:
            if key_value is not None:
                ec_key_value = self._find(key_value, "ECKeyValue", namespace="dsig11")
                named_curve = self._find(ec_key_value, "NamedCurve", namespace="dsig11")
                public_key = self._find(ec_key_value, "PublicKey", namespace="dsig11")
                key_data = b64decode(public_key.text)[1:]
                x = bytes_to_long(key_data[:len(key_data)//2])
                y = bytes_to_long(key_data[len(key_data)//2:])
                curve_class = self.known_ecdsa_curves[named_curve.get("URI")]
                key = ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve_class()).public_key(backend=default_backend())
            elif not isinstance(key, ec.EllipticCurvePublicKey):
                raise InvalidInput("DER encoded key value does not match specified signature algorithm")
            dss_signature = self._encode_dss_signature(raw_signature, key.key_size)
            key.verify(
                dss_signature,
                data=signed_info_c14n,
                signature_algorithm=ec.ECDSA(
                    self._get_signature_digest_method(signature_alg)
                ),
            )
        elif "dsa-" in signature_alg:
            if key_value is not None:
                dsa_key_value = self._find(key_value, "DSAKeyValue")
                p = self._get_long(dsa_key_value, "P")
                q = self._get_long(dsa_key_value, "Q")
                g = self._get_long(dsa_key_value, "G", require=False)
                y = self._get_long(dsa_key_value, "Y")
                pn = dsa.DSAPublicNumbers(y=y, parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g))
                key = pn.public_key(backend=default_backend())
            elif not isinstance(key, dsa.DSAPublicKey):
                raise InvalidInput("DER encoded key value does not match specified signature algorithm")
            # TODO: supply meaningful key_size_bits for signature length assertion
            dss_signature = self._encode_dss_signature(raw_signature, len(raw_signature) * 8 / 2)
            key.verify(dss_signature,
                       data=signed_info_c14n,
                       algorithm=self._get_signature_digest_method(signature_alg))
        elif "rsa-" in signature_alg:
            if key_value is not None:
                rsa_key_value = self._find(key_value, "RSAKeyValue")
                modulus = self._get_long(rsa_key_value, "Modulus")
                exponent = self._get_long(rsa_key_value, "Exponent")
                key = rsa.RSAPublicNumbers(e=exponent, n=modulus).public_key(backend=default_backend())
            elif not isinstance(key, rsa.RSAPublicKey):
                raise InvalidInput("DER encoded key value does not match specified signature algorithm")
            key.verify(raw_signature,
                       data=signed_info_c14n,
                       padding=PKCS1v15(),
                       algorithm=self._get_signature_digest_method(signature_alg))
        else:
            raise NotImplementedError() 
Example #21
Source File: keys.py    From learn_python3_spider with MIT License 4 votes vote down vote up
def _fromString_BLOB(cls, 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

        The format of ECDSA-SHA2-* public key blob is::
            string 'ecdsa-sha2-[identifier]'
            integer x
            integer y

            identifier is the standard NIST curve name.

        @type blob: L{bytes}
        @param blob: The key data.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if the key type (the first string) is unknown.
        """
        keyType, rest = common.getNS(blob)
        if keyType == b'ssh-rsa':
            e, n, rest = common.getMP(rest, 2)
            return cls(
                rsa.RSAPublicNumbers(e, n).public_key(default_backend()))
        elif keyType == b'ssh-dss':
            p, q, g, y, rest = common.getMP(rest, 4)
            return cls(
                dsa.DSAPublicNumbers(
                    y=y,
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=p,
                        q=q,
                        g=g
                    )
                ).public_key(default_backend())
            )
        elif keyType in _curveTable:
            return cls(
                ec.EllipticCurvePublicKey.from_encoded_point(
                    _curveTable[keyType], common.getNS(rest, 2)[1]
                )
            )
        else:
            raise BadKeyError('unknown blob type: %s' % (keyType,)) 
Example #22
Source File: keys.py    From Safejumper-for-Desktop with GNU General Public License v2.0 4 votes vote down vote up
def _fromString_BLOB(cls, 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

        The format of ECDSA-SHA2-* public key blob is::
            string 'ecdsa-sha2-[identifier]'
            integer x
            integer y

            identifier is the standard NIST curve name.

        @type blob: L{bytes}
        @param blob: The key data.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if the key type (the first string) is unknown.
        """
        keyType, rest = common.getNS(blob)
        if keyType == b'ssh-rsa':
            e, n, rest = common.getMP(rest, 2)
            return cls(
                rsa.RSAPublicNumbers(e, n).public_key(default_backend()))
        elif keyType == b'ssh-dss':
            p, q, g, y, rest = common.getMP(rest, 4)
            return cls(
                dsa.DSAPublicNumbers(
                    y=y,
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=p,
                        q=q,
                        g=g
                    )
                ).public_key(default_backend())
            )
        elif keyType in _curveTable:
            # First we have to make an EllipticCuvePublicNumbers from the
            # provided curve and points,
            # then turn it into a public key object.
            return cls(
                ec.EllipticCurvePublicNumbers.from_encoded_point(
                      _curveTable[keyType],
                       common.getNS(rest, 2)[1]).public_key(default_backend()))
        else:
            raise BadKeyError('unknown blob type: %s' % (keyType,))