Python cryptography.hazmat.primitives.asymmetric.utils.encode_dss_signature() Examples
The following are 12
code examples of cryptography.hazmat.primitives.asymmetric.utils.encode_dss_signature().
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.utils
, or try the search function
.
Example #1
Source File: ecdsalib.py From virtualchain with GNU General Public License v3.0 | 6 votes |
def verify_digest(hash_hex, pubkey_hex, sigb64, hashfunc=hashlib.sha256): """ Given a digest, public key (as hex), and a base64 signature, verify that the public key signed the digest. Return True if so Return False if not """ if not isinstance(hash_hex, (str, unicode)): raise ValueError("hash hex is not a string") hash_hex = str(hash_hex) pubk_uncompressed_hex = keylib.key_formatting.decompress(pubkey_hex) sig_r, sig_s = decode_signature(sigb64) pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pubk_uncompressed_hex.decode('hex')).public_key(default_backend()) signature = encode_dss_signature(sig_r, sig_s) try: pubk.verify(signature, hash_hex.decode('hex'), ec.ECDSA(utils.Prehashed(hashes.SHA256()))) return True except InvalidSignature: return False
Example #2
Source File: jwa.py From jwcrypto with GNU Lesser General Public License v3.0 | 5 votes |
def verify(self, key, payload, signature): pkey = key.get_op_key('verify', self._curve) r = signature[:len(signature) // 2] s = signature[len(signature) // 2:] enc_signature = ec_utils.encode_dss_signature( int(hexlify(r), 16), int(hexlify(s), 16)) pkey.verify(enc_signature, payload, ec.ECDSA(self.hashfn))
Example #3
Source File: elliptic_curve.py From aws-encryption-sdk-python with Apache License 2.0 | 5 votes |
def _ecc_static_length_signature(key, algorithm, digest): """Calculates an elliptic curve signature with a static length using pre-calculated hash. :param key: Elliptic curve private key :type key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey :param algorithm: Master algorithm to use :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param bytes digest: Pre-calculated hash digest :returns: Signature with required length :rtype: bytes """ pre_hashed_algorithm = ec.ECDSA(Prehashed(algorithm.signing_hash_type())) signature = b"" while len(signature) != algorithm.signature_len: _LOGGER.debug( "Signature length %d is not desired length %d. Recalculating.", len(signature), algorithm.signature_len ) signature = key.sign(digest, pre_hashed_algorithm) if len(signature) != algorithm.signature_len: # Most of the time, a signature of the wrong length can be fixed # by negating s in the signature relative to the group order. _LOGGER.debug( "Signature length %d is not desired length %d. Negating s.", len(signature), algorithm.signature_len ) r, s = decode_dss_signature(signature) s = _ECC_CURVE_PARAMETERS[algorithm.signing_algorithm_info.name].order - s signature = encode_dss_signature(r, s) return signature
Example #4
Source File: jwt.py From autopush with Mozilla Public License 2.0 | 5 votes |
def extract_signature(auth): # type: (str) -> Tuple[str, str] """Fix the JWT auth token. The JWA spec defines the signature to be a pair of 32octet encoded longs. The `ecdsa` library signs using a raw, 32octet pair of values (s, r). Cryptography, which uses OpenSSL, uses a DER sequence of (s, r). This function converts the raw ecdsa to DER. :param auth: A JWT authorization token. :type auth: str :return tuple containing the signature material and signature """ payload, asig = auth.encode('utf8').rsplit(".", 1) sig = base64.urlsafe_b64decode(repad(asig)) if len(sig) != 64: return payload, sig encoded = utils.encode_dss_signature( s=int(binascii.hexlify(sig[32:]), 16), r=int(binascii.hexlify(sig[:32]), 16) ) return payload, encoded
Example #5
Source File: m2crypto.py From py-ipv8 with GNU Lesser General Public License v3.0 | 5 votes |
def verify(self, signature, msg): """ Verify whether a given signature is correct for a message. :param signature: the given signature :param msg: the given message """ length = len(signature) // 2 r = signature[:length] # remove all "\x00" prefixes while r and r[0:1] == "\x00": r = r[1:] # prepend "\x00" when the most significant bit is set if ord(r[0:1]) & 128: r = "\x00" + r s = signature[length:] # remove all "\x00" prefixes while s and s[0:1] == "\x00": s = s[1:] # prepend "\x00" when the most significant bit is set if ord(s[0:1]) & 128: s = "\x00" + s # turn back into int r = int(hexlify(r), 16) s = int(hexlify(s), 16) # verify try: if NEW_CRYPTOGRAPHY_SIGN_VERSION: self.ec.verify(encode_dss_signature(r, s), msg, ec.ECDSA(hashes.SHA1())) else: self.ec.verifier(encode_dss_signature(r, s), ec.ECDSA(hashes.SHA1())) return True except InvalidSignature: return False
Example #6
Source File: es256.py From google-auth-library-python with Apache License 2.0 | 5 votes |
def verify(self, message, signature): # First convert (r||s) raw signature to ASN1 encoded signature. sig_bytes = _helpers.to_bytes(signature) if len(sig_bytes) != 64: return False r = utils.int_from_bytes(sig_bytes[:32], byteorder="big") s = utils.int_from_bytes(sig_bytes[32:], byteorder="big") asn1_sig = encode_dss_signature(r, s) message = _helpers.to_bytes(message) try: self._pubkey.verify(asn1_sig, message, ec.ECDSA(hashes.SHA256())) return True except (ValueError, cryptography.exceptions.InvalidSignature): return False
Example #7
Source File: ecdsalib.py From virtualchain with GNU General Public License v3.0 | 5 votes |
def __init__(self, pubkey_hex, sigb64): """ Instantiate the verifier with a hex-encoded public key and a base64-encoded signature """ sig_r, sig_s = decode_signature(sigb64) pubkey_hex_decompressed = keylib.key_formatting.decompress(pubkey_hex) pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pubkey_hex_decompressed.decode('hex')).public_key(default_backend()) signature = encode_dss_signature(sig_r, sig_s) self.verifier = pubk.verifier(signature, ec.ECDSA(hashes.SHA256()))
Example #8
Source File: __init__.py From signxml with Apache License 2.0 | 5 votes |
def _encode_dss_signature(self, raw_signature, key_size_bits): want_raw_signature_len = bits_to_bytes_unit(key_size_bits) * 2 if len(raw_signature) != want_raw_signature_len: raise InvalidSignature( "Expected %d byte SignatureValue, got %d" % (want_raw_signature_len, len(raw_signature)) ) int_len = len(raw_signature) // 2 r = bytes_to_long(raw_signature[:int_len]) s = bytes_to_long(raw_signature[int_len:]) return utils.encode_dss_signature(r, s)
Example #9
Source File: googleplay.py From googleplay-api with GNU General Public License v3.0 | 5 votes |
def encryptPassword(self, login, passwd): """Encrypt credentials using the google publickey, with the RSA algorithm""" # structure of the binary key: # # *-------------------------------------------------------* # | modulus_length | modulus | exponent_length | exponent | # *-------------------------------------------------------* # # modulus_length and exponent_length are uint32 binaryKey = b64decode(config.GOOGLE_PUBKEY) # modulus i = utils.readInt(binaryKey, 0) modulus = utils.toBigInt(binaryKey[4:][0:i]) # exponent j = utils.readInt(binaryKey, i + 4) exponent = utils.toBigInt(binaryKey[i + 8:][0:j]) # calculate SHA1 of the pub key digest = hashes.Hash(hashes.SHA1(), backend=default_backend()) digest.update(binaryKey) h = b'\x00' + digest.finalize()[0:4] # generate a public key der_data = encode_dss_signature(modulus, exponent) publicKey = load_der_public_key(der_data, backend=default_backend()) # encrypt email and password using pubkey to_be_encrypted = login.encode() + b'\x00' + passwd.encode() ciphertext = publicKey.encrypt( to_be_encrypted, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None ) ) return urlsafe_b64encode(h + ciphertext)
Example #10
Source File: cryptography_backend.py From python-jose with MIT License | 5 votes |
def _raw_to_der(self, raw_signature): """Convert signature from RAW encoding to DER encoding.""" component_length = self._sig_component_length() if len(raw_signature) != int(2 * component_length): raise ValueError("Invalid signature") r_bytes = raw_signature[:component_length] s_bytes = raw_signature[component_length:] r = int_from_bytes(r_bytes, "big") s = int_from_bytes(s_bytes, "big") return encode_dss_signature(r, s)
Example #11
Source File: signing.py From pyUmbral with GNU General Public License v3.0 | 5 votes |
def _der_encoded_bytes(self) -> bytes: return utils.encode_dss_signature(int(self.r), int(self.s))
Example #12
Source File: dsa.py From securesystemslib with MIT License | 4 votes |
def get_signature_params(data): """ <Purpose> Parse the signature parameters as multi-precision-integers. <Arguments> data: the RFC4880-encoded signature data buffer as described in the fourth paragraph of section 5.2.2 <Exceptions> securesystemslib.gpg.exceptions.PacketParsingError: if the public key parameters are malformed securesystemslib.exceptions.UnsupportedLibraryError: if the cryptography module is not available <Side Effects> None. <Returns> The decoded signature buffer """ if not CRYPTO: # pragma: no cover return securesystemslib.exceptions.UnsupportedLibraryError(NO_CRYPTO_MSG) ptr = 0 r_length = securesystemslib.gpg.util.get_mpi_length(data[ptr:ptr+2]) ptr += 2 r = data[ptr:ptr + r_length] if len(r) != r_length: # pragma: no cover raise securesystemslib.gpg.exceptions.PacketParsingError( "r-value truncated in signature") ptr += r_length s_length = securesystemslib.gpg.util.get_mpi_length(data[ptr: ptr+2]) ptr += 2 s = data[ptr: ptr + s_length] if len(s) != s_length: # pragma: no cover raise securesystemslib.gpg.exceptions.PacketParsingError( "s-value truncated in signature") s = int(binascii.hexlify(s), 16) r = int(binascii.hexlify(r), 16) signature = dsautils.encode_dss_signature(r, s) return signature