signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def main(): | parser = argparse.ArgumentParser(description='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>',<EOL>dest='<STR_LIT>',<EOL>metavar='<STR_LIT:type>',<EOL>help='<STR_LIT>',<EOL>required=True)<EOL>parser.add_argument('<STR_LIT>',<EOL>dest='<STR_LIT>',<EOL>type=int,<EOL>metavar='<STR_LIT:size>',<EOL>help='<STR_LIT>')<EOL>par... | Main function | f13633:m0 |
def encrypt(self, key, iv="<STR_LIT>", cek="<STR_LIT>", **kwargs): | _msg = as_bytes(self.msg)<EOL>_args = self._dict<EOL>try:<EOL><INDENT>_args["<STR_LIT>"] = kwargs["<STR_LIT>"]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>jwe = JWEnc(**_args)<EOL>iv = self._generate_iv(self["<STR_LIT>"], iv)<EOL>cek = self._generate_key(self["<STR_LIT>"], cek)<EOL>if isinstance(key, SYMK... | Produces a JWE as defined in RFC7516 using symmetric keys
:param key: Shared symmetric key
:param iv: Initialization vector
:param cek: Content master key
:param kwargs: Extra keyword arguments, just ignore for now.
:return: | f13635:c0:m0 |
def ecdh_derive_key(key, epk, apu, apv, alg, dk_len): | <EOL>shared_key = key.exchange(ec.ECDH(), epk)<EOL>otherInfo = bytes(alg) +struct.pack("<STR_LIT>", len(apu)) + apu +struct.pack("<STR_LIT>", len(apv)) + apv +struct.pack("<STR_LIT>", dk_len)<EOL>return concat_sha256(shared_key, dk_len, otherInfo)<EOL> | ECDH key derivation, as defined by JWA
:param key : Elliptic curve private key
:param epk : Elliptic curve public key
:param apu : PartyUInfo
:param apv : PartyVInfo
:param alg : Algorithm identifier
:param dk_len: Length of key to be derived, in bits
:return: The derived key | f13636:m0 |
def enc_setup(self, msg, key=None, auth_data=b'<STR_LIT>', **kwargs): | encrypted_key = "<STR_LIT>"<EOL>self.msg = msg<EOL>self.auth_data = auth_data<EOL>try:<EOL><INDENT>apu = b64d(kwargs["<STR_LIT>"])<EOL><DEDENT>except KeyError:<EOL><INDENT>apu = get_random_bytes(<NUM_LIT:16>)<EOL><DEDENT>try:<EOL><INDENT>apv = b64d(kwargs["<STR_LIT>"])<EOL><DEDENT>except KeyError:<EOL><INDENT>apv = get... | :param msg: Message to be encrypted
:param auth_data:
:param key: An EC key
:param kwargs:
:return: | f13636:c0:m1 |
def dec_setup(self, token, key=None, **kwargs): | self.headers = token.headers<EOL>self.iv = token.initialization_vector()<EOL>self.ctxt = token.ciphertext()<EOL>self.tag = token.authentication_tag()<EOL>if "<STR_LIT>" not in self.headers or "<STR_LIT>" not in self.headers["<STR_LIT>"]:<EOL><INDENT>raise Exception(<EOL>"<STR_LIT>")<EOL><DEDENT>epubkey = ECKey(**self.h... | :param token: signed JSON Web token
:param key: Private Elliptic Curve Key
:param kwargs:
:return: | f13636:c0:m2 |
def encrypt(self, key=None, iv="<STR_LIT>", cek="<STR_LIT>", **kwargs): | _msg = as_bytes(self.msg)<EOL>_args = self._dict<EOL>try:<EOL><INDENT>_args["<STR_LIT>"] = kwargs["<STR_LIT>"]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>if '<STR_LIT>' in kwargs:<EOL><INDENT>if '<STR_LIT>' in kwargs['<STR_LIT>']:<EOL><INDENT>_args['<STR_LIT>'] = kwargs['<STR_LIT>']['<STR_LIT>']<EOL><DED... | Produces a JWE as defined in RFC7516 using an Elliptic curve key
:param key: *Not used>, only there to present the same API as
JWE_RSA and JWE_SYM
:param iv: Initialization vector
:param cek: Content master key
:param kwargs: Extra keyword arguments
:return: An encrypted JWT | f13636:c0:m3 |
def encrypt(self, msg, iv='<STR_LIT>', auth_data=None): | if not iv:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return self.key.encrypt(iv, msg, auth_data)<EOL> | Encrypts and authenticates the data provided as well as authenticating
the associated_data.
:param msg: The message to be encrypted
:param iv: MUST be present, at least 96-bit long
:param auth_data: Associated data
:return: The cipher text bytes with the 16 byte tag appended. | f13637:c1:m1 |
def decrypt(self, cipher_text, iv='<STR_LIT>', auth_data=None, tag=b'<STR_LIT>'): | if not iv:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return self.key.decrypt(iv, cipher_text+tag, auth_data)<EOL> | Decrypts the data and authenticates the associated_data (if provided).
:param cipher_text: The data to decrypt including tag
:param iv: Initialization Vector
:param auth_data: Associated data
:param tag: Authentication tag
:return: The original plaintext | f13637:c1:m2 |
def encrypt(self, msg, key, **kwargs): | raise NotImplementedError<EOL> | Encrypt ``msg`` with ``key`` and return the encrypted message. | f13639:c0:m1 |
def decrypt(self, msg, key, **kwargs): | raise NotImplementedError<EOL> | Return decrypted message. | f13639:c0:m2 |
def enc_setup(self, enc_alg, msg, auth_data=b'<STR_LIT>', key=None, iv="<STR_LIT>"): | iv = self._generate_iv(enc_alg, iv)<EOL>if enc_alg in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>aes = AES_GCMEncrypter(key=key)<EOL>ctx, tag = split_ctx_and_tag(aes.encrypt(msg, iv, auth_data))<EOL><DEDENT>elif enc_alg in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>aes = AES_CBCEncrypter(key=key)<EO... | Encrypt JWE content.
:param enc_alg: The JWE "enc" value specifying the encryption algorithm
:param msg: The plain text message
:param auth_data: Additional authenticated data
:param key: Key (CEK)
:return: Tuple (ciphertext, tag), both as bytes | f13640:c0:m3 |
@staticmethod<EOL><INDENT>def _decrypt(enc, key, ctxt, iv, tag, auth_data=b'<STR_LIT>'):<DEDENT> | if enc in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>aes = AES_GCMEncrypter(key=key)<EOL><DEDENT>elif enc in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>aes = AES_CBCEncrypter(key=key)<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" % enc)<EOL><DEDENT>try:<EOL><INDENT>return aes.decrypt(ctx... | Decrypt JWE content.
:param enc: The JWE "enc" value specifying the encryption algorithm
:param key: Key (CEK)
:param iv : Initialization vector
:param auth_data: Additional authenticated data (AAD)
:param ctxt : Ciphertext
:param tag: Authentication tag
:return:... | f13640:c0:m4 |
def concat_sha256(secret, dk_len, other_info): | dkm = b'<STR_LIT>'<EOL>dk_bytes = int(ceil(dk_len / <NUM_LIT>))<EOL>counter = <NUM_LIT:0><EOL>while len(dkm) < dk_bytes:<EOL><INDENT>counter += <NUM_LIT:1><EOL>counter_bytes = struct.pack("<STR_LIT>", counter)<EOL>digest = hashes.Hash(hashes.SHA256(), backend=default_backend())<EOL>digest.update(counter_bytes)<EOL>dige... | The Concat KDF, using SHA256 as the hash function.
Note: Does not validate that otherInfo meets the requirements of
SP800-56A.
:param secret: The shared secret value
:param dk_len: Length of key to be derived, in bits
:param other_info: Other info to be incorporated (see SP800-56A)
:return: The derived key | f13641:m5 |
def encrypt(self, keys=None, cek="<STR_LIT>", iv="<STR_LIT>", **kwargs): | _alg = self["<STR_LIT>"]<EOL>if keys:<EOL><INDENT>keys = self.pick_keys(keys, use="<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>keys = self.pick_keys(self._get_keys(), use="<STR_LIT>")<EOL><DEDENT>if not keys:<EOL><INDENT>logger.error(KEY_ERR.format(_alg))<EOL>raise NoSuitableEncryptionKey(_alg)<EOL><DEDENT>if _alg in ["<... | Encrypt a payload
:param keys: A set of possibly usable keys
:param cek: Content master key
:param iv: Initialization vector
:param kwargs: Extra key word arguments
:return: Encrypted message | f13643:c0:m0 |
def encrypt(self, key, iv="<STR_LIT>", cek="<STR_LIT>", **kwargs): | _msg = as_bytes(self.msg)<EOL>if "<STR_LIT>" in self:<EOL><INDENT>if self["<STR_LIT>"] == "<STR_LIT>":<EOL><INDENT>_msg = zlib.compress(_msg)<EOL><DEDENT>else:<EOL><INDENT>raise ParameterError("<STR_LIT>" % self["<STR_LIT>"])<EOL><DEDENT><DEDENT>kwarg_cek = cek or None<EOL>_enc = self["<STR_LIT>"]<EOL>iv = self._genera... | Produces a JWE as defined in RFC7516 using RSA algorithms
:param key: RSA key
:param iv: Initialization vector
:param cek: Content master key
:param kwargs: Extra keyword arguments
:return: A signed payload | f13644:c0:m0 |
def decrypt(self, token, key, cek=None): | if not isinstance(token, JWEnc):<EOL><INDENT>jwe = JWEnc().unpack(token)<EOL><DEDENT>else:<EOL><INDENT>jwe = token<EOL><DEDENT>self.jwt = jwe.encrypted_key()<EOL>jek = jwe.encrypted_key()<EOL>_decrypt = RSAEncrypter(self.with_digest).decrypt<EOL>_alg = jwe.headers["<STR_LIT>"]<EOL>if cek:<EOL><INDENT>pass<EOL><DEDENT>e... | Decrypts a JWT
:param token: The JWT
:param key: A key to use for decrypting
:param cek: Ephemeral cipher key
:return: The decrypted message | f13644:c0:m1 |
def generate_and_store_rsa_key(key_size=<NUM_LIT>, filename='<STR_LIT>',<EOL>passphrase='<STR_LIT>'): | private_key = rsa.generate_private_key(public_exponent=<NUM_LIT>,<EOL>key_size=key_size,<EOL>backend=default_backend())<EOL>with open(filename, "<STR_LIT:wb>") as keyfile:<EOL><INDENT>if passphrase:<EOL><INDENT>pem = private_key.private_bytes(<EOL>encoding=serialization.Encoding.PEM,<EOL>format=serialization.PrivateFor... | Generate a private RSA key and store a PEM representation of it in a
file.
:param key_size: The size of the key, default 2048 bytes.
:param filename: The name of the file to which the key should be written
:param passphrase: If the PEM representation should be protected with a
pass phrase.
:return: A
cryptogra... | f13645:m0 |
def import_private_rsa_key_from_file(filename, passphrase=None): | with open(filename, "<STR_LIT:rb>") as key_file:<EOL><INDENT>private_key = serialization.load_pem_private_key(<EOL>key_file.read(),<EOL>password=passphrase,<EOL>backend=default_backend())<EOL><DEDENT>return private_key<EOL> | Read a private RSA key from a PEM file.
:param filename: The name of the file
:param passphrase: A pass phrase to use to unpack the PEM file.
:return: A
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey instance | f13645:m1 |
def import_public_rsa_key_from_file(filename): | with open(filename, "<STR_LIT:rb>") as key_file:<EOL><INDENT>public_key = serialization.load_pem_public_key(<EOL>key_file.read(),<EOL>backend=default_backend())<EOL><DEDENT>return public_key<EOL> | Read a public RSA key from a PEM file.
:param filename: The name of the file
:param passphrase: A pass phrase to use to unpack the PEM file.
:return: A
cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey instance | f13645:m2 |
def import_rsa_key(pem_data): | if not pem_data.startswith(PREFIX):<EOL><INDENT>pem_data = bytes('<STR_LIT>'.format(PREFIX, pem_data, POSTFIX),<EOL>'<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>pem_data = bytes(pem_data, '<STR_LIT:utf-8>')<EOL><DEDENT>cert = x509.load_pem_x509_certificate(pem_data, default_backend())<EOL>return cert.public_key()<E... | Extract an RSA key from a PEM-encoded X.509 certificate
:param pem_data: RSA key encoded in standard form
:return: rsa.RSAPublicKey instance | f13645:m3 |
def rsa_eq(key1, key2): | pn1 = key1.public_numbers()<EOL>pn2 = key2.public_numbers()<EOL>if pn1 == pn2:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT> | Only works for RSAPublic Keys
:param key1:
:param key2:
:return: | f13645:m5 |
def x509_rsa_load(txt): | pub_key = import_rsa_key(txt)<EOL>if isinstance(pub_key, rsa.RSAPublicKey):<EOL><INDENT>return [("<STR_LIT>", pub_key)]<EOL><DEDENT> | So I get the same output format as loads produces
:param txt:
:return: | f13645:m6 |
def der_cert(der_data): | if isinstance(der_data, str):<EOL><INDENT>der_data = bytes(der_data, '<STR_LIT:utf-8>')<EOL><DEDENT>return x509.load_der_x509_certificate(der_data, default_backend())<EOL> | Load a DER encoded certificate
:param der_data: DER-encoded certificate
:return: A cryptography.x509.certificate instance | f13645:m9 |
def load_x509_cert(url, httpc, spec2key, **get_args): | try:<EOL><INDENT>r = httpc('<STR_LIT:GET>', url, allow_redirects=True, **get_args)<EOL>if r.status_code == <NUM_LIT:200>:<EOL><INDENT>cert = str(r.text)<EOL>try:<EOL><INDENT>public_key = spec2key[cert] <EOL><DEDENT>except KeyError:<EOL><INDENT>public_key = import_rsa_key(cert)<EOL>spec2key[cert] = public_key<EOL><DEDE... | Get and transform a X509 cert into a key.
:param url: Where the X509 cert can be found
:param httpc: HTTP client to use for fetching
:param spec2key: A dictionary over keys already seen
:param get_args: Extra key word arguments to the HTTP GET request
:return: List of 2-tuples (keytype, key) | f13645:m10 |
def cmp_public_numbers(pn1, pn2): | if pn1.n == pn2.n:<EOL><INDENT>if pn1.e == pn2.e:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL> | Compare 2 sets of public numbers. These is a way to compare
2 public RSA keys. If the sets are the same then the keys are the same.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True is the sets are the same otherwise False. | f13645:m11 |
def cmp_private_numbers(pn1, pn2): | if not cmp_public_numbers(pn1.public_numbers, pn2.public_numbers):<EOL><INDENT>return False<EOL><DEDENT>for param in ['<STR_LIT:d>', '<STR_LIT:p>', '<STR_LIT:q>']:<EOL><INDENT>if getattr(pn1, param) != getattr(pn2, param):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL> | Compare 2 sets of private numbers. This is for comparing 2
private RSA keys.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True is the sets are the same otherwise False. | f13645:m12 |
def x5t_calculation(cert): | if isinstance(cert, str):<EOL><INDENT>der_cert = base64.b64decode(cert.encode('<STR_LIT:ascii>'))<EOL><DEDENT>else:<EOL><INDENT>der_cert = base64.b64decode(cert)<EOL><DEDENT>return b64e(hashlib.sha1(der_cert).digest())<EOL> | base64url-encoded SHA-1 thumbprint (a.k.a. digest) of the DER
encoding of an X.509 certificate.
:param cert: DER encoded X.509 certificate
:return: x5t value | f13645:m13 |
def new_rsa_key(key_size=<NUM_LIT>, kid='<STR_LIT>', use='<STR_LIT>', public_exponent=<NUM_LIT>): | _key = rsa.generate_private_key(public_exponent=public_exponent,<EOL>key_size=key_size,<EOL>backend=default_backend())<EOL>_rk = RSAKey(priv_key=_key, use=use, kid=kid)<EOL>if not kid:<EOL><INDENT>_rk.add_kid()<EOL><DEDENT>return _rk<EOL> | Creates a new RSA key pair and wraps it in a
:py:class:`cryptojwt.jwk.rsa.RSAKey` instance
:param key_size: The size of the key
:param kid: The key ID
:param use: What the is supposed to be used for. 2 choices 'sig'/'enc'
:param public_exponent: The value of the public exponent.
:return: A :py:class:`cryptojwt.jwk.rsa... | f13645:m14 |
def deserialize(self): | <EOL>if self.n and self.e:<EOL><INDENT>try:<EOL><INDENT>numbers = {}<EOL>for param in self.longs:<EOL><INDENT>item = getattr(self, param)<EOL>if not item:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>val = int(deser(item))<EOL><DEDENT>except Exception:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><IND... | Based on a text based representation of an RSA key this method
instantiates a
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or
RSAPublicKey instance | f13645:c0:m1 |
def serialize(self, private=False): | if not self.priv_key and not self.pub_key:<EOL><INDENT>raise SerializationNotPossible()<EOL><DEDENT>res = self.common()<EOL>public_longs = list(set(self.public_members) & set(self.longs))<EOL>for param in public_longs:<EOL><INDENT>item = getattr(self, param)<EOL>if item:<EOL><INDENT>res[param] = item<EOL><DEDENT><DEDEN... | Given a cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or
RSAPublicKey instance construct the JWK representation.
:param private: Should I do the private part or not
:return: A JWK as a dictionary | f13645:c0:m2 |
def load_key(self, key): | self._serialize(key)<EOL>if isinstance(key, rsa.RSAPrivateKey):<EOL><INDENT>self.priv_key = key<EOL>self.pub_key = key.public_key()<EOL><DEDENT>else:<EOL><INDENT>self.pub_key = key<EOL><DEDENT>return self<EOL> | Load a RSA key. Try to serialize the key before binding it to this
instance.
:param key: An RSA key instance | f13645:c0:m4 |
def load(self, filename): | return self.load_key(import_private_rsa_key_from_file(filename))<EOL> | Load a RSA key from a file. Once we have the key do a serialization.
:param filename: File name | f13645:c0:m5 |
def __eq__(self, other): | if not isinstance(other, RSAKey):<EOL><INDENT>return False<EOL><DEDENT>if not self.pub_key:<EOL><INDENT>self.deserialize()<EOL><DEDENT>if not other.pub_key:<EOL><INDENT>other.deserialize()<EOL><DEDENT>try:<EOL><INDENT>pn1 = self.priv_key.private_numbers()<EOL>pn2 = other.priv_key.private_numbers()<EOL><DEDENT>except Ex... | Verify that this other key is the same as myself.
:param other: The other key
:return: True if equal otherwise False | f13645:c0:m6 |
def ensure_ec_params(jwk_dict, private): | provided = frozenset(jwk_dict.keys())<EOL>if private is not None and private:<EOL><INDENT>required = EC_PUBLIC_REQUIRED | EC_PRIVATE_REQUIRED<EOL><DEDENT>else:<EOL><INDENT>required = EC_PUBLIC_REQUIRED<EOL><DEDENT>return ensure_params('<STR_LIT>', provided, required)<EOL> | Ensure all required EC parameters are present in dictionary | f13646:m0 |
def ensure_rsa_params(jwk_dict, private): | provided = frozenset(jwk_dict.keys())<EOL>if private is not None and private:<EOL><INDENT>required = RSA_PUBLIC_REQUIRED | RSA_PRIVATE_REQUIRED<EOL><DEDENT>else:<EOL><INDENT>required = RSA_PUBLIC_REQUIRED<EOL><DEDENT>return ensure_params('<STR_LIT>', provided, required)<EOL> | Ensure all required RSA parameters are present in dictionary | f13646:m1 |
def ensure_params(kty, provided, required): | if not required <= provided:<EOL><INDENT>missing = required - provided<EOL>raise MissingValue('<STR_LIT>'.format(kty, str(list(missing))))<EOL><DEDENT> | Ensure all required parameters are present in dictionary | f13646:m2 |
def key_from_jwk_dict(jwk_dict, private=None): | <EOL>_jwk_dict = copy.copy(jwk_dict)<EOL>if '<STR_LIT>' not in _jwk_dict:<EOL><INDENT>raise MissingValue('<STR_LIT>')<EOL><DEDENT>if _jwk_dict['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>ensure_ec_params(_jwk_dict, private)<EOL>if private is not None and not private:<EOL><INDENT>for v in EC_PRIVATE:<EOL><INDENT>_jwk_dict.... | Load JWK from dictionary
:param jwk_dict: Dictionary representing a JWK | f13646:m3 |
def jwk_wrap(key, use="<STR_LIT>", kid="<STR_LIT>"): | if isinstance(key, rsa.RSAPublicKey) or isinstance(key, rsa.RSAPrivateKey):<EOL><INDENT>kspec = RSAKey(use=use, kid=kid).load_key(key)<EOL><DEDENT>elif isinstance(key, str):<EOL><INDENT>kspec = SYMKey(key=key, use=use, kid=kid)<EOL><DEDENT>elif isinstance(key, ec.EllipticCurvePublicKey):<EOL><INDENT>kspec = ECKey(use=u... | Instantiate a Key instance with the given key
:param key: The keys to wrap
:param use: What the key are expected to be use for
:param kid: A key id
:return: The Key instance | f13646:m4 |
def appropriate_for(self, usage, **kwargs): | try:<EOL><INDENT>_use = USE[usage]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>if usage in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if not self.use or _use == self.use:<EOL><INDENT>if self.priv_key:<EOL><INDENT>return self.priv_key<EOL><DEDENT><DEDENT>return None<... | Make sure there is a key instance present that can be used for
the specified usage.
:param usage: Usage specification, one of [sign, verify, decrypt,
encrypt]
:param kwargs: Extra keyword arguments
:return: Suitable key or None | f13647:c0:m1 |
def has_private_key(self): | if self.priv_key:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT> | Checks whether there is a private key avaliable.
:return: True/False | f13647:c0:m2 |
def public_key(self): | return self.pub_key<EOL> | Return a public key instance. | f13647:c0:m3 |
def private_key(self): | return self.priv_key<EOL> | Return a private key instance. | f13647:c0:m4 |
def to_dict(self): | res = self.serialize(private=True)<EOL>res.update(self.extra_args)<EOL>return res<EOL> | A wrapper for to_dict the makes sure that all the private information
as well as extra arguments are included. This method should *not* be
used for exporting information about the key.
:return: A dictionary representation of the JSON Web key | f13648:c0:m1 |
def common(self): | res = {"<STR_LIT>": self.kty}<EOL>if self.use:<EOL><INDENT>res["<STR_LIT>"] = self.use<EOL><DEDENT>if self.kid:<EOL><INDENT>res["<STR_LIT>"] = self.kid<EOL><DEDENT>if self.alg:<EOL><INDENT>res["<STR_LIT>"] = self.alg<EOL><DEDENT>return res<EOL> | Return the set of parameters that are common to all types of keys.
:return: Dictionary | f13648:c0:m2 |
def deserialize(self): | pass<EOL> | Starting with information gathered from the on-the-wire representation
initiate an appropriate key. | f13648:c0:m4 |
def serialize(self, private=False): | pass<EOL> | map key characteristics into attribute values that can be used
to create an on-the-wire representation of the key | f13648:c0:m5 |
def get_key(self, private=False, **kwargs): | pass<EOL> | Get a keys useful for signing and/or encrypting information.
:param private: Private key requested. If false return a public key.
:return: A key instance. This can be an RSA, EC or other
type of key. | f13648:c0:m6 |
def verify(self): | for param in self.longs:<EOL><INDENT>item = getattr(self, param)<EOL>if not item or isinstance(item, str):<EOL><INDENT>continue<EOL><DEDENT>if isinstance(item, bytes):<EOL><INDENT>item = item.decode('<STR_LIT:utf-8>')<EOL>setattr(self, param, item)<EOL><DEDENT>try:<EOL><INDENT>_ = base64url_to_long(item)<EOL><DEDENT>ex... | Verify that the information gathered from the on-the-wire
representation is of the right type.
This is supposed to be run before the info is deserialized.
:return: True/False | f13648:c0:m7 |
def __eq__(self, other): | if self.__class__ != other.__class__:<EOL><INDENT>return False<EOL><DEDENT>if set(self.__dict__.keys()) != set(other.__dict__.keys()):<EOL><INDENT>return False<EOL><DEDENT>for key in self.public_members:<EOL><INDENT>if getattr(other, key) != getattr(self, key):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<E... | Compare 2 Key instances to find out if they represent the same key
:param other: The other Key instance
:return: True if they are the same otherwise False. | f13648:c0:m8 |
def thumbprint(self, hash_function, members=None): | if members is None:<EOL><INDENT>members = self.required<EOL><DEDENT>members.sort()<EOL>ser = self.serialize()<EOL>_se = []<EOL>for elem in members:<EOL><INDENT>try:<EOL><INDENT>_val = ser[elem]<EOL><DEDENT>except KeyError: <EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if isinstance(_val, bytes):<EOL><INDENT>_val = a... | Create a thumbprint of the key following the outline in
https://tools.ietf.org/html/draft-jones-jose-jwk-thumbprint-01
:param hash_function: A hash function to use for hashing the
information
:param members: Which attributes of the Key instance that should
be included when computing the hash value. If members ... | f13648:c0:m10 |
def add_kid(self): | self.kid = b64e(self.thumbprint('<STR_LIT>')).decode('<STR_LIT:utf8>')<EOL> | Construct a Key ID using the thumbprint method and add it to
the key attributes. | f13648:c0:m11 |
def appropriate_for(self, usage, **kwargs): | return self.use == USE[usage]<EOL> | Make sure that key can be used for the specified usage.
:return: True/False | f13648:c0:m12 |
def appropriate_for(self, usage, alg='<STR_LIT>'): | try:<EOL><INDENT>_use = USE[usage]<EOL><DEDENT>except:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>if not self.use or self.use == _use:<EOL><INDENT>if _use == '<STR_LIT>':<EOL><INDENT>return self.get_key()<EOL><DEDENT>else:<EOL><INDENT>return self.encryption_key(alg)<EOL><DEDENT><DEDENT>rais... | Make sure there is a key instance present that can be used for
the specified usage. | f13649:c0:m4 |
def encryption_key(self, alg, **kwargs): | if not self.key:<EOL><INDENT>self.deserialize()<EOL><DEDENT>try:<EOL><INDENT>tsize = ALG2KEYLEN[alg]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise UnsupportedAlgorithm(alg)<EOL><DEDENT>if tsize <= <NUM_LIT:32>:<EOL><INDENT>_enc_key = sha256_digest(self.key)[:tsize]<EOL><DEDENT>elif tsize <= <NUM_LIT>:<EOL><INDENT>_enc... | Return an encryption key as per
http://openid.net/specs/openid-connect-core-1_0.html#Encryption
:param alg: encryption algorithm
:param kwargs:
:return: encryption key as byte string | f13649:c0:m5 |
def __eq__(self, other): | if self.__class__ != other.__class__:<EOL><INDENT>return False<EOL><DEDENT>if set(self.__dict__.keys()) != set(other.__dict__.keys()):<EOL><INDENT>return False<EOL><DEDENT>for key in self.public_members:<EOL><INDENT>if getattr(other, key) != getattr(self, key):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<E... | Compare 2 JWK instances to find out if they represent the same key
:param other: The other JWK instance
:return: True if they are the same otherwise False. | f13649:c0:m6 |
def sha256_digest(msg): | return hashlib.sha256(as_bytes(msg)).digest()<EOL> | Produce a SHA256 digest of a message
:param msg: The message
:return: A SHA256 digest | f13650:m0 |
def sha384_digest(msg): | return hashlib.sha384(as_bytes(msg)).digest()<EOL> | Produce a SHA384 digest of a message
:param msg: The message
:return: A SHA384 digest | f13650:m1 |
def sha512_digest(msg): | return hashlib.sha512(as_bytes(msg)).digest()<EOL> | Produce a SHA512 digest of a message
:param msg: The message
:return: A SHA512 digest | f13650:m2 |
def ec_construct_public(num): | ecpn = ec.EllipticCurvePublicNumbers(num['<STR_LIT:x>'], num['<STR_LIT:y>'],<EOL>NIST2SEC[as_unicode(num['<STR_LIT>'])]())<EOL>return ecpn.public_key(default_backend())<EOL> | Given a set of values on public attributes build a elliptic curve
public key instance.
:param num: A dictionary with public attributes and their values
:return: A
cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey
instance. | f13651:m0 |
def ec_construct_private(num): | pub_ecpn = ec.EllipticCurvePublicNumbers(num['<STR_LIT:x>'], num['<STR_LIT:y>'],<EOL>NIST2SEC[as_unicode(num['<STR_LIT>'])]())<EOL>priv_ecpn = ec.EllipticCurvePrivateNumbers(num['<STR_LIT:d>'], pub_ecpn)<EOL>return priv_ecpn.private_key(default_backend())<EOL> | Given a set of values on public and private attributes build a elliptic
curve private key instance.
:param num: A dictionary with public and private attributes and their values
:return: A
cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
instance. | f13651:m1 |
def import_private_key_from_file(filename, passphrase=None): | with open(filename, "<STR_LIT:rb>") as key_file:<EOL><INDENT>private_key = serialization.load_pem_private_key(<EOL>key_file.read(),<EOL>password=passphrase,<EOL>backend=default_backend())<EOL><DEDENT>return private_key<EOL> | Read a private Elliptic Curve key from a PEM file.
:param filename: The name of the file
:param passphrase: A pass phrase to use to unpack the PEM file.
:return: A
cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
instance | f13651:m2 |
def import_public_key_from_file(filename): | with open(filename, "<STR_LIT:rb>") as key_file:<EOL><INDENT>public_key = serialization.load_pem_public_key(<EOL>key_file.read(),<EOL>backend=default_backend())<EOL><DEDENT>return public_key<EOL> | Read a public Elliptic Curve key from a PEM file.
:param filename: The name of the file
:param passphrase: A pass phrase to use to unpack the PEM file.
:return: A
cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
instance | f13651:m3 |
def deserialize(self): | if isinstance(self.x, (str, bytes)):<EOL><INDENT>_x = deser(self.x)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if isinstance(self.y, (str, bytes)):<EOL><INDENT>_y = deser(self.y)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.d:<EOL><INDENT>try:<EOL><INDENT>... | Starting with information gathered from the on-the-wire representation
of an elliptic curve key (a JWK) initiate an
cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey
or EllipticCurvePrivateKey instance. So we have to get from having::
{
"kty":"EC",
"crv":"P-256",
"x":"MKBCTNIcKU... | f13651:c0:m1 |
def serialize(self, private=False): | if self.priv_key:<EOL><INDENT>self._serialize(self.priv_key)<EOL><DEDENT>else:<EOL><INDENT>self._serialize(self.pub_key)<EOL><DEDENT>res = self.common()<EOL>res.update({<EOL>"<STR_LIT>": self.crv,<EOL>"<STR_LIT:x>": self.x,<EOL>"<STR_LIT:y>": self.y<EOL>})<EOL>if private and self.d:<EOL><INDENT>res["<STR_LIT:d>"] = sel... | Go from a
cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
or EllipticCurvePublicKey instance to a JWK representation.
:param private: Whether we should include the private attributes or not.
:return: A JWK as a dictionary | f13651:c0:m3 |
def load_key(self, key): | self._serialize(key)<EOL>if isinstance(key, ec.EllipticCurvePrivateKey):<EOL><INDENT>self.priv_key = key<EOL>self.pub_key = key.public_key()<EOL><DEDENT>else:<EOL><INDENT>self.pub_key = key<EOL><DEDENT>return self<EOL> | Load an Elliptic curve key
:param key: An elliptic curve key instance, private or public.
:return: Reference to this instance | f13651:c0:m4 |
def load(self, filename): | return self.load_key(import_private_key_from_file(filename))<EOL> | Load an Elliptic curve key from a file.
:param filename: File name | f13651:c0:m5 |
def decryption_key(self): | return self.priv_key<EOL> | Get a key appropriate for decrypting a message.
:return: An ec.EllipticCurvePrivateKey instance | f13651:c0:m6 |
def encryption_key(self): | return self.pub_key<EOL> | Get a key appropriate for encrypting a message.
:return: An ec.EllipticCurvePublicKey instance | f13651:c0:m7 |
def __eq__(self, other): | if cmp_keys(self.pub_key, other.pub_key, ec.EllipticCurvePublicKey):<EOL><INDENT>if other.private_key():<EOL><INDENT>if cmp_keys(self.priv_key, other.priv_key,<EOL>ec.EllipticCurvePrivateKey):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>elif self.private_key():<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>ret... | Verify that the other key has the same properties as myself.
:param other: The other key
:return: True if the keys as the same otherwise False | f13651:c0:m8 |
def base64url_to_long(data): | _data = as_bytes(data)<EOL>_d = base64.urlsafe_b64decode(_data + b'<STR_LIT>')<EOL>if [e for e in [b'<STR_LIT:+>', b'<STR_LIT:/>', b'<STR_LIT:=>'] if e in _data]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return intarr2long(struct.unpack('<STR_LIT>' % len(_d), _d))<EOL> | Stricter then base64_to_long since it really checks that it's
base64url encoded
:param data: The base64 string
:return: | f13653:m6 |
def b64e(b): | return base64.urlsafe_b64encode(b).rstrip(b"<STR_LIT:=>")<EOL> | Base64 encode some bytes.
Uses the url-safe - and _ characters, and doesn't pad with = characters. | f13653:m7 |
def b64d(b): | cb = b.rstrip(b"<STR_LIT:=>") <EOL>if not _b64_re.match(cb):<EOL><INDENT>raise BadSyntax(cb, "<STR_LIT>")<EOL><DEDENT>if cb == b:<EOL><INDENT>b = add_padding(b)<EOL><DEDENT>return base64.urlsafe_b64decode(b)<EOL> | Decode some base64-encoded bytes.
Raises BadSyntax if the string contains invalid characters or padding.
:param b: bytes | f13653:m9 |
def as_bytes(s): | try:<EOL><INDENT>s = s.encode()<EOL><DEDENT>except (AttributeError, UnicodeDecodeError):<EOL><INDENT>pass<EOL><DEDENT>return s<EOL> | Convert an unicode string to bytes.
:param s: Unicode / bytes string
:return: bytes string | f13653:m12 |
def as_unicode(b): | try:<EOL><INDENT>b = b.decode()<EOL><DEDENT>except (AttributeError, UnicodeDecodeError):<EOL><INDENT>pass<EOL><DEDENT>return b<EOL> | Convert a byte string to a unicode string
:param b: byte string
:return: unicode string | f13653:m13 |
def deser(val): | if isinstance(val, str):<EOL><INDENT>_val = val.encode("<STR_LIT:utf-8>")<EOL><DEDENT>else:<EOL><INDENT>_val = val<EOL><DEDENT>return base64_to_long(_val)<EOL> | Deserialize from a string representation of an long integer
to the python representation of a long integer.
:param val: The string representation of the long integer.
:return: The long integer. | f13653:m17 |
def pick_keys(self, keys, use="<STR_LIT>", alg="<STR_LIT>"): | if not alg:<EOL><INDENT>alg = self["<STR_LIT>"]<EOL><DEDENT>if alg == "<STR_LIT:none>":<EOL><INDENT>return []<EOL><DEDENT>_k = self.alg2keytype(alg)<EOL>if _k is None:<EOL><INDENT>logger.error("<STR_LIT>" % alg)<EOL>raise ValueError('<STR_LIT>')<EOL><DEDENT>logger.debug("<STR_LIT>".format(_k))<EOL>_kty = [_k.lower(), _... | The assumption is that upper layer has made certain you only get
keys you can use.
:param alg: The crypto algorithm
:param use: What the key should be used for
:param keys: A list of JWK instances
:return: A list of JWK instances that fulfill the requirements | f13654:c0:m9 |
def sign(self, msg, key): | if not isinstance(key, rsa.RSAPrivateKey):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>")<EOL><DEDENT>sig = key.sign(msg, self.padding, self.hash)<EOL>return sig<EOL> | Create a signature over a message as defined in RFC7515 using an
RSA key
:param msg: the message.
:type msg: bytes
:returns: bytes, the signature of data.
:rtype: bytes | f13656:c0:m1 |
def verify(self, msg, signature, key): | if not isinstance(key, rsa.RSAPublicKey):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>key.verify(signature, msg, self.padding, self.hash)<EOL><DEDENT>except InvalidSignature as err:<EOL><INDENT>raise BadSignature(str(err))<EOL><DEDENT>except AttributeError:<EOL><INDENT>return False<EOL><D... | Verifies whether signature is a valid signature for message
:param msg: the message
:type msg: bytes
:param signature: The signature to be verified
:type signature: bytes
:param key: The key
:return: True is the signature is valid otherwise False | f13656:c0:m2 |
def sign(self, msg, key): | if not isinstance(key, ec.EllipticCurvePrivateKey):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>self._cross_check(key.public_key())<EOL>num_bits = key.curve.key_size<EOL>num_bytes = (num_bits + <NUM_LIT:7>) // <NUM_LIT:8><EOL>asn1sig = key.sign(msg, ec.ECDSA(self.hash_algorithm()))<EOL>(r,... | Create a signature over a message as defined in RFC7515 using an
Elliptic curve key
:param msg: The message
:param key: An ec.EllipticCurvePrivateKey instance
:return: | f13657:c0:m1 |
def verify(self, msg, sig, key): | if not isinstance(key, ec.EllipticCurvePublicKey):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>self._cross_check(key)<EOL>num_bits = key.curve.key_size<EOL>num_bytes = (num_bits + <NUM_LIT:7>) // <NUM_LIT:8><EOL>if len(sig) != <NUM_LIT:2> * num_bytes:<EOL><INDENT>raise ValueError('<STR_LIT... | Verify a message signature
:param msg: The message
:param sig: A signature
:param key: A ec.EllipticCurvePublicKey to use for the verification.
:raises: BadSignature if the signature can't be verified.
:return: True | f13657:c0:m2 |
def _cross_check(self, pub_key): | if self.curve_name != pub_key.curve.name:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(pub_key.curve.name, self.curve_name))<EOL><DEDENT> | In Ecdsa, both the key and the algorithm define the curve.
Therefore, we must cross check them to make sure they're the same.
:param key:
:raises: ValueError is the curves are not the same | f13657:c0:m3 |
@staticmethod<EOL><INDENT>def _split_raw_signature(sig):<DEDENT> | c_length = len(sig) // <NUM_LIT:2><EOL>r = int_from_bytes(sig[:c_length], byteorder='<STR_LIT>')<EOL>s = int_from_bytes(sig[c_length:], byteorder='<STR_LIT>')<EOL>return r, s<EOL> | Split raw signature into components
:param sig: The signature
:return: A 2-tuple | f13657:c0:m4 |
def factory(token, alg='<STR_LIT>'): | _jw = JWS(alg=alg)<EOL>if _jw.is_jws(token):<EOL><INDENT>return _jw<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT> | Instantiate an JWS instance if the token is a signed JWT.
:param token: The token that might be a signed JWT
:param alg: The expected signature algorithm
:return: A JWS instance if the token was a signed JWT, otherwise None | f13658:m0 |
def sign_compact(self, keys=None, protected=None, **kwargs): | _headers = self._header<EOL>_headers.update(kwargs)<EOL>key, xargs, _alg = self.alg_keys(keys, '<STR_LIT>', protected)<EOL>if "<STR_LIT>" in self:<EOL><INDENT>xargs["<STR_LIT>"] = self["<STR_LIT>"]<EOL><DEDENT>_headers.update(xargs)<EOL>jwt = JWSig(**_headers)<EOL>if _alg == "<STR_LIT:none>":<EOL><INDENT>return jwt.pac... | Produce a JWS using the JWS Compact Serialization
:param keys: A dictionary of keys
:param protected: The protected headers (a dictionary)
:param kwargs: claims you want to add to the standard headers
:return: A signed JSON Web Token | f13658:c1:m2 |
def verify_compact(self, jws=None, keys=None, allow_none=False,<EOL>sigalg=None): | return self.verify_compact_verbose(jws, keys, allow_none, sigalg)['<STR_LIT>']<EOL> | Verify a JWT signature
:param jws: A signed JSON Web Token
:param keys: A list of keys that can possibly be used to verify the
signature
:param allow_none: If signature algorithm 'none' is allowed
:param sigalg: Expected sigalg
:return: Dictionary with 2 keys 'msg' required, 'key' optional | f13658:c1:m3 |
def verify_compact_verbose(self, jws=None, keys=None, allow_none=False,<EOL>sigalg=None): | if jws:<EOL><INDENT>jwt = JWSig().unpack(jws)<EOL>if len(jwt) != <NUM_LIT:3>:<EOL><INDENT>raise WrongNumberOfParts(len(jwt))<EOL><DEDENT>self.jwt = jwt<EOL><DEDENT>elif not self.jwt:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>jwt = self.jwt<EOL><DEDENT>try:<EOL><INDENT>_alg = jwt.headers["<... | Verify a JWT signature and return dict with validation results
:param jws: A signed JSON Web Token
:param keys: A list of keys that can possibly be used to verify the
signature
:param allow_none: If signature algorithm 'none' is allowed
:param sigalg: Expected sigalg
:return: Dictionary with 2 keys 'msg' required,... | f13658:c1:m4 |
def sign_json(self, keys=None, headers=None, flatten=False): | def create_signature(protected, unprotected):<EOL><INDENT>protected_headers = protected or {}<EOL>protected_headers.setdefault("<STR_LIT>", self.alg)<EOL>_jws = JWS(self.msg, **protected_headers)<EOL>encoded_header, payload, signature = _jws.sign_compact(<EOL>protected=protected,<EOL>keys=keys).split("<STR_LIT:.>")<EOL... | Produce JWS using the JWS JSON Serialization
:param keys: list of keys to use for signing the JWS
:param headers: list of tuples (protected headers, unprotected
headers) for each signature
:return: A signed message using the JSON serialization format. | f13658:c1:m5 |
def verify_json(self, jws, keys=None, allow_none=False, sigalg=None): | _jwss = json.loads(jws)<EOL>try:<EOL><INDENT>_payload = _jwss["<STR_LIT>"]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise FormatError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>_signs = _jwss["<STR_LIT>"]<EOL><DEDENT>except KeyError:<EOL><INDENT>signature = {}<EOL>for key in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL>... | :param jws:
:param keys:
:return: | f13658:c1:m6 |
def is_jws(self, jws): | try:<EOL><INDENT>try:<EOL><INDENT>json_jws = json.loads(jws)<EOL><DEDENT>except TypeError:<EOL><INDENT>jws = jws.decode('<STR_LIT:utf8>')<EOL>json_jws = json.loads(jws)<EOL><DEDENT>return self._is_json_serialized_jws(json_jws)<EOL><DEDENT>except ValueError:<EOL><INDENT>return self._is_compact_jws(jws)<EOL><DEDENT> | :param jws:
:return: | f13658:c1:m7 |
def _is_json_serialized_jws(self, json_jws): | json_ser_keys = {"<STR_LIT>", "<STR_LIT>"}<EOL>flattened_json_ser_keys = {"<STR_LIT>", "<STR_LIT>"}<EOL>if not json_ser_keys.issubset(<EOL>json_jws.keys()) and not flattened_json_ser_keys.issubset(<EOL>json_jws.keys()):<EOL><INDENT>return False<EOL><DEDENT>return True<EOL> | Check if we've got a JSON serialized signed JWT.
:param json_jws: The message
:return: True/False | f13658:c1:m8 |
def _is_compact_jws(self, jws): | try:<EOL><INDENT>jwt = JWSig().unpack(jws)<EOL><DEDENT>except Exception as err:<EOL><INDENT>logger.warning('<STR_LIT>'.format(err))<EOL>return False<EOL><DEDENT>if "<STR_LIT>" not in jwt.headers:<EOL><INDENT>return False<EOL><DEDENT>if jwt.headers["<STR_LIT>"] is None:<EOL><INDENT>jwt.headers["<STR_LIT>"] = "<STR_LIT:n... | Check if we've got a compact signed JWT
:param jws: The message
:return: True/False | f13658:c1:m9 |
def alg2keytype(self, alg): | return alg2keytype(alg)<EOL> | Translate a signing algorithm into a specific key type.
:param alg: The signing algorithm
:return: A key type or None if there is no key type matching the
algorithm | f13658:c1:m10 |
def set_header_claim(self, key, value): | self._header[key] = value<EOL> | Set a specific claim in the header to a specific value.
:param key: The name of the claim
:param value: The value of the claim | f13658:c1:m11 |
def verify_alg(self, alg): | try:<EOL><INDENT>return self.jwt.verify_header('<STR_LIT>', alg)<EOL><DEDENT>except KeyError:<EOL><INDENT>return False<EOL><DEDENT> | Specifically check that the 'alg' claim has a specific value
:param alg: The expected alg value
:return: True if the alg value in the header is the same as the one
given. Returns False if no 'alg' claim exists in the header. | f13658:c1:m12 |
def sign(self, msg, key): | raise NotImplementedError()<EOL> | Sign ``msg`` with ``key`` and return the signature. | f13659:c0:m0 |
def verify(self, msg, sig, key): | raise NotImplementedError()<EOL> | Return True if ``sig`` is a valid signature for ``msg``. | f13659:c0:m1 |
def sign(self, msg, key): | hasher = hashes.Hash(self.hash_algorithm(), backend=default_backend())<EOL>hasher.update(msg)<EOL>digest = hasher.finalize()<EOL>sig = key.sign(<EOL>digest,<EOL>padding.PSS(<EOL>mgf=padding.MGF1(self.hash_algorithm()),<EOL>salt_length=padding.PSS.MAX_LENGTH),<EOL>utils.Prehashed(self.hash_algorithm()))<EOL>return sig<E... | Create a signature over a message
:param msg: The message
:param key: The key
:return: A signature | f13660:c0:m1 |
def verify(self, msg, signature, key): | try:<EOL><INDENT>key.verify(signature, msg,<EOL>padding.PSS(mgf=padding.MGF1(self.hash_algorithm()),<EOL>salt_length=padding.PSS.MAX_LENGTH),<EOL>self.hash_algorithm())<EOL><DEDENT>except InvalidSignature as err:<EOL><INDENT>raise BadSignature(err)<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT> | Verify a message signature
:param msg: The message
:param sig: A signature
:param key: A ec.EllipticCurvePublicKey to use for the verification.
:raises: BadSignature if the signature can't be verified.
:return: True | f13660:c0:m2 |
def sign(self, msg, key): | h = hmac.HMAC(key, self.algorithm(), default_backend())<EOL>h.update(msg)<EOL>return h.finalize()<EOL> | Create a signature over a message as defined in RFC7515 using a
symmetric key
:param msg: The message
:param key: The key
:return: A signature | f13661:c0:m1 |
def verify(self, msg, sig, key): | try:<EOL><INDENT>h = hmac.HMAC(key, self.algorithm(), default_backend())<EOL>h.update(msg)<EOL>h.verify(sig)<EOL>return True<EOL><DEDENT>except:<EOL><INDENT>return False<EOL><DEDENT> | Verifies whether sig is the correct message authentication code of data.
:param msg: The data
:param sig: The message authentication code to verify against data.
:param key: The key to use
:return: Returns true if the mac was valid otherwise it will raise an
Exception. | f13661:c0:m2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.