code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
keys = pick_key(self.my_keys(owner_id, 'sig'), 'sig', alg=self.alg,
kid=kid)
if not keys:
raise NoSuitableSigningKeys('kid={}'.format(kid))
return keys[0] | def pack_key(self, owner_id='', kid='') | Find a key to be used for signing the Json Web Token
:param owner_id: Owner of the keys to chose from
:param kid: Key ID
:return: One key | 8.452515 | 8.671718 | 0.974722 |
keys = self.key_jar.get_jwt_verify_keys(rj.jwt)
return rj.verify_compact(token, keys) | def _verify(self, rj, token) | Verify a signed JSON Web Token
:param rj: A :py:class:`cryptojwt.jws.JWS` instance
:param token: The signed JSON Web Token
:return: A verified message | 9.384644 | 7.201982 | 1.303064 |
if self.iss:
keys = self.key_jar.get_jwt_decrypt_keys(rj.jwt, aud=self.iss)
else:
keys = self.key_jar.get_jwt_decrypt_keys(rj.jwt)
return rj.decrypt(token, keys=keys) | def _decrypt(self, rj, token) | Decrypt an encrypted JsonWebToken
:param rj: :py:class:`cryptojwt.jwe.JWE` instance
:param token: The encrypted JsonWebToken
:return: | 4.127586 | 4.048976 | 1.019415 |
_msg = msg_cls(**info)
if not _msg.verify(**kwargs):
raise VerificationError()
return _msg | def verify_profile(msg_cls, info, **kwargs) | If a message type is known for this JSON document. Verify that the
document complies with the message specifications.
:param msg_cls: The message class. A
:py:class:`oidcmsg.message.Message` instance
:param info: The information in the JSON document as a dictionary
:param kw... | 4.879199 | 5.024755 | 0.971032 |
if not token:
raise KeyError
_jwe_header = _jws_header = None
# Check if it's an encrypted JWT
darg = {}
if self.allowed_enc_encs:
darg['enc'] = self.allowed_enc_encs
if self.allowed_enc_algs:
darg['alg'] = self.allowed_enc_a... | def unpack(self, token) | Unpack a received signed or signed and encrypted Json Web Token
:param token: The Json Web Token
:return: If decryption and signature verification work the payload
will be returned as a Message instance if possible. | 3.357651 | 3.294251 | 1.019246 |
_jw = JWS(alg=alg)
if _jw.is_jws(token):
return _jw
else:
return None | def factory(token, alg='') | 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 | 5.50936 | 4.352625 | 1.265756 |
_headers = self._header
_headers.update(kwargs)
key, xargs, _alg = self.alg_keys(keys, 'sig', protected)
if "typ" in self:
xargs["typ"] = self["typ"]
_headers.update(xargs)
jwt = JWSig(**_headers)
if _alg == "none":
return jwt.... | def sign_compact(self, keys=None, protected=None, **kwargs) | 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 | 5.052679 | 5.033079 | 1.003894 |
return self.verify_compact_verbose(jws, keys, allow_none, sigalg)['msg'] | def verify_compact(self, jws=None, keys=None, allow_none=False,
sigalg=None) | 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' r... | 6.570881 | 7.724743 | 0.850628 |
if jws:
jwt = JWSig().unpack(jws)
if len(jwt) != 3:
raise WrongNumberOfParts(len(jwt))
self.jwt = jwt
elif not self.jwt:
raise ValueError('Missing singed JWT')
else:
jwt = self.jwt
try:
_al... | def verify_compact_verbose(self, jws=None, keys=None, allow_none=False,
sigalg=None) | 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
... | 2.844672 | 2.780296 | 1.023155 |
def create_signature(protected, unprotected):
protected_headers = protected or {}
# always protect the signing alg header
protected_headers.setdefault("alg", self.alg)
_jws = JWS(self.msg, **protected_headers)
encoded_header, payload, signatu... | def sign_json(self, keys=None, headers=None, flatten=False) | 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. | 3.992627 | 3.608747 | 1.106375 |
json_ser_keys = {"payload", "signatures"}
flattened_json_ser_keys = {"payload", "signature"}
if not json_ser_keys.issubset(
json_jws.keys()) and not flattened_json_ser_keys.issubset(
json_jws.keys()):
return False
return True | def _is_json_serialized_jws(self, json_jws) | Check if we've got a JSON serialized signed JWT.
:param json_jws: The message
:return: True/False | 3.251415 | 3.62325 | 0.897375 |
try:
jwt = JWSig().unpack(jws)
except Exception as err:
logger.warning('Could not parse JWS: {}'.format(err))
return False
if "alg" not in jwt.headers:
return False
if jwt.headers["alg"] is None:
jwt.headers["alg"] = ... | def _is_compact_jws(self, jws) | Check if we've got a compact signed JWT
:param jws: The message
:return: True/False | 3.603338 | 3.50829 | 1.027092 |
try:
_use = USE[usage]
except:
raise ValueError('Unknown key usage')
else:
if not self.use or self.use == _use:
if _use == 'sig':
return self.get_key()
else:
return self.encryptio... | def appropriate_for(self, usage, alg='HS256') | Make sure there is a key instance present that can be used for
the specified usage. | 5.378983 | 4.943982 | 1.087986 |
if not self.key:
self.deserialize()
try:
tsize = ALG2KEYLEN[alg]
except KeyError:
raise UnsupportedAlgorithm(alg)
if tsize <= 32:
# SHA256
_enc_key = sha256_digest(self.key)[:tsize]
elif tsize <= 48:
... | def encryption_key(self, alg, **kwargs) | 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 | 2.7855 | 2.770537 | 1.005401 |
if not isinstance(key, rsa.RSAPrivateKey):
raise TypeError(
"The key must be an instance of rsa.RSAPrivateKey")
sig = key.sign(msg, self.padding, self.hash)
return sig | def sign(self, msg, key) | 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 | 3.32879 | 2.971962 | 1.120065 |
if not isinstance(key, rsa.RSAPublicKey):
raise TypeError(
"The public key must be an instance of RSAPublicKey")
try:
key.verify(signature, msg, self.padding, self.hash)
except InvalidSignature as err:
raise BadSignature(str(err))
... | def verify(self, msg, signature, key) | 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 | 3.216663 | 3.064919 | 1.04951 |
try:
_use = USE[usage]
except KeyError:
raise ValueError('Unknown key usage')
else:
if usage in ['sign', 'decrypt']:
if not self.use or _use == self.use:
if self.priv_key:
return self.priv_ke... | def appropriate_for(self, usage, **kwargs) | 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 | 3.86856 | 3.211443 | 1.204617 |
private_key = rsa.generate_private_key(public_exponent=65537,
key_size=key_size,
backend=default_backend())
with open(filename, "wb") as keyfile:
if passphrase:
pem = private_key.private_bytes(
... | def generate_and_store_rsa_key(key_size=2048, filename='rsa.key',
passphrase='') | 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.
... | 1.462842 | 1.529769 | 0.95625 |
with open(filename, "rb") as key_file:
public_key = serialization.load_pem_public_key(
key_file.read(),
backend=default_backend())
return public_key | def import_public_rsa_key_from_file(filename) | 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 | 1.690659 | 2.55251 | 0.662352 |
if not pem_data.startswith(PREFIX):
pem_data = bytes('{}\n{}\n{}'.format(PREFIX, pem_data, POSTFIX),
'utf-8')
else:
pem_data = bytes(pem_data, 'utf-8')
cert = x509.load_pem_x509_certificate(pem_data, default_backend())
return cert.public_key() | def import_rsa_key(pem_data) | Extract an RSA key from a PEM-encoded X.509 certificate
:param pem_data: RSA key encoded in standard form
:return: rsa.RSAPublicKey instance | 2.358304 | 2.662138 | 0.885868 |
pn1 = key1.public_numbers()
pn2 = key2.public_numbers()
# Check if two RSA keys are in fact the same
if pn1 == pn2:
return True
else:
return False | def rsa_eq(key1, key2) | Only works for RSAPublic Keys
:param key1:
:param key2:
:return: | 3.598326 | 3.877238 | 0.928064 |
pub_key = import_rsa_key(txt)
if isinstance(pub_key, rsa.RSAPublicKey):
return [("rsa", pub_key)] | def x509_rsa_load(txt) | So I get the same output format as loads produces
:param txt:
:return: | 4.067739 | 5.263881 | 0.772764 |
if isinstance(der_data, str):
der_data = bytes(der_data, 'utf-8')
return x509.load_der_x509_certificate(der_data, default_backend()) | def der_cert(der_data) | Load a DER encoded certificate
:param der_data: DER-encoded certificate
:return: A cryptography.x509.certificate instance | 1.779066 | 2.186212 | 0.813766 |
try:
r = httpc('GET', url, allow_redirects=True, **get_args)
if r.status_code == 200:
cert = str(r.text)
try:
public_key = spec2key[cert] # If I've already seen it
except KeyError:
public_key = import_rsa_key(cert)
... | def load_x509_cert(url, httpc, spec2key, **get_args) | 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) | 3.196756 | 3.142534 | 1.017254 |
if pn1.n == pn2.n:
if pn1.e == pn2.e:
return True
return False | def cmp_public_numbers(pn1, pn2) | 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. | 2.514285 | 3.077358 | 0.817027 |
if not cmp_public_numbers(pn1.public_numbers, pn2.public_numbers):
return False
for param in ['d', 'p', 'q']:
if getattr(pn1, param) != getattr(pn2, param):
return False
return True | def cmp_private_numbers(pn1, pn2) | 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. | 2.676566 | 3.204027 | 0.835375 |
if isinstance(cert, str):
der_cert = base64.b64decode(cert.encode('ascii'))
else:
der_cert = base64.b64decode(cert)
return b64e(hashlib.sha1(der_cert).digest()) | def x5t_calculation(cert) | 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 | 2.27204 | 2.520802 | 0.901316 |
_key = rsa.generate_private_key(public_exponent=public_exponent,
key_size=key_size,
backend=default_backend())
_rk = RSAKey(priv_key=_key, use=use, kid=kid)
if not kid:
_rk.add_kid()
return _rk | def new_rsa_key(key_size=2048, kid='', use='', public_exponent=65537) | 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:... | 2.90899 | 3.373754 | 0.862241 |
# first look for the public parts of a RSA key
if self.n and self.e:
try:
numbers = {}
# loop over all the parameters that define a RSA key
for param in self.longs:
item = getattr(self, param)
i... | def deserialize(self) | Based on a text based representation of an RSA key this method
instantiates a
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey or
RSAPublicKey instance | 3.555617 | 3.463313 | 1.026652 |
if not self.priv_key and not self.pub_key:
raise SerializationNotPossible()
res = self.common()
public_longs = list(set(self.public_members) & set(self.longs))
for param in public_longs:
item = getattr(self, param)
if item:
r... | def serialize(self, private=False) | 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 | 3.588255 | 3.371494 | 1.064292 |
self._serialize(key)
if isinstance(key, rsa.RSAPrivateKey):
self.priv_key = key
self.pub_key = key.public_key()
else:
self.pub_key = key
return self | def load_key(self, key) | Load a RSA key. Try to serialize the key before binding it to this
instance.
:param key: An RSA key instance | 3.480872 | 3.172585 | 1.097172 |
if not isinstance(key, ec.EllipticCurvePrivateKey):
raise TypeError(
"The private key must be an instance of "
"ec.EllipticCurvePrivateKey")
self._cross_check(key.public_key())
num_bits = key.curve.key_size
num_bytes = (num_bits + 7)... | def sign(self, msg, key) | 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: | 3.770258 | 3.804157 | 0.991089 |
if not isinstance(key, ec.EllipticCurvePublicKey):
raise TypeError(
"The public key must be an instance of "
"ec.EllipticCurvePublicKey")
self._cross_check(key)
num_bits = key.curve.key_size
num_bytes = (num_bits + 7) // 8
if ... | def verify(self, msg, sig, key) | 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 | 3.873288 | 3.897993 | 0.993662 |
if self.curve_name != pub_key.curve.name:
raise ValueError(
"The curve in private key {} and in algorithm {} don't "
"match".format(pub_key.curve.name, self.curve_name)) | def _cross_check(self, pub_key) | 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 | 4.014726 | 3.494124 | 1.148994 |
c_length = len(sig) // 2
r = int_from_bytes(sig[:c_length], byteorder='big')
s = int_from_bytes(sig[c_length:], byteorder='big')
return r, s | def _split_raw_signature(sig) | Split raw signature into components
:param sig: The signature
:return: A 2-tuple | 2.694719 | 2.972116 | 0.906667 |
if func == 'HS256':
return as_unicode(b64e(sha256_digest(msg)[:16]))
elif func == 'HS384':
return as_unicode(b64e(sha384_digest(msg)[:24]))
elif func == 'HS512':
return as_unicode(b64e(sha512_digest(msg)[:32])) | def left_hash(msg, func="HS256") | Calculate left hash as described in
https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
for at_hash and in
for c_hash
:param msg: The message over which the hash should be calculated
:param func: Which hash function that was used for the ID token | 1.881977 | 2.095823 | 0.897966 |
if not alg or alg.lower() == "none":
return "none"
elif alg.startswith("RS") or alg.startswith("PS"):
return "RSA"
elif alg.startswith("HS") or alg.startswith("A"):
return "oct"
elif alg.startswith("ES") or alg.startswith("ECDH-ES"):
return "EC"
else:
ret... | def alg2keytype(alg) | Go from algorithm name to key type.
:param alg: The algorithm name
:return: The key type | 2.47628 | 2.799667 | 0.884491 |
if algorithm == "RS256":
return hashes.SHA256(), padding.PKCS1v15()
elif algorithm == "RS384":
return hashes.SHA384(), padding.PKCS1v15()
elif algorithm == "RS512":
return hashes.SHA512(), padding.PKCS1v15()
elif algorithm == "PS256":
return (hashes.SHA256(),
... | def parse_rsa_algorithm(algorithm) | Parses a RSA algorithm and returns tuple (hash, padding).
:param algorithm: string, RSA algorithm as defined at
https://tools.ietf.org/html/rfc7518#section-3.1.
:raises: UnsupportedAlgorithm: if the algorithm is not supported.
:returns: (hash, padding) tuple. | 1.324036 | 1.274183 | 1.039126 |
# Compute shared secret
shared_key = key.exchange(ec.ECDH(), epk)
# Derive the key
# AlgorithmID || PartyUInfo || PartyVInfo || SuppPubInfo
otherInfo = bytes(alg) + \
struct.pack("!I", len(apu)) + apu + \
struct.pack("!I", len(apv)) + apv + \
stru... | def ecdh_derive_key(key, epk, apu, apv, alg, dk_len) | 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 | 3.762017 | 3.671627 | 1.024619 |
_msg = as_bytes(self.msg)
_args = self._dict
try:
_args["kid"] = kwargs["kid"]
except KeyError:
pass
if 'params' in kwargs:
if 'apu' in kwargs['params']:
_args['apu'] = kwargs['params']['apu']
if 'apv' in ... | def encrypt(self, key=None, iv="", cek="", **kwargs) | 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 encry... | 3.816313 | 3.764699 | 1.01371 |
_msg = as_bytes(self.msg)
if "zip" in self:
if self["zip"] == "DEF":
_msg = zlib.compress(_msg)
else:
raise ParameterError("Zip has unknown value: %s" % self["zip"])
kwarg_cek = cek or None
_enc = self["enc"]
iv ... | def encrypt(self, key, iv="", cek="", **kwargs) | 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 | 3.757559 | 3.689803 | 1.018363 |
if not isinstance(token, JWEnc):
jwe = JWEnc().unpack(token)
else:
jwe = token
self.jwt = jwe.encrypted_key()
jek = jwe.encrypted_key()
_decrypt = RSAEncrypter(self.with_digest).decrypt
_alg = jwe.headers["alg"]
if cek:
... | def decrypt(self, token, key, cek=None) | Decrypts a JWT
:param token: The JWT
:param key: A key to use for decrypting
:param cek: Ephemeral cipher key
:return: The decrypted message | 2.933282 | 3.074564 | 0.954048 |
_alg = self["alg"]
# Find Usable Keys
if keys:
keys = self.pick_keys(keys, use="enc")
else:
keys = self.pick_keys(self._get_keys(), use="enc")
if not keys:
logger.error(KEY_ERR.format(_alg))
raise NoSuitableEncryptionKey... | def encrypt(self, keys=None, cek="", iv="", **kwargs) | 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 | 3.39121 | 3.395632 | 0.998698 |
_data = as_bytes(data)
_d = base64.urlsafe_b64decode(_data + b'==')
# verify that it's base64url encoded and not just base64
# that is no '+' and '/' characters and not trailing "="s.
if [e for e in [b'+', b'/', b'='] if e in _data]:
raise ValueError("Not base64url encoded")
return ... | def base64url_to_long(data) | Stricter then base64_to_long since it really checks that it's
base64url encoded
:param data: The base64 string
:return: | 5.290165 | 5.556289 | 0.952104 |
cb = b.rstrip(b"=") # shouldn't but there you are
# Python's base64 functions ignore invalid characters, so we need to
# check for them explicitly.
if not _b64_re.match(cb):
raise BadSyntax(cb, "base64-encoded data contains illegal characters")
if cb == b:
b = add_padding(b)... | def b64d(b) | Decode some base64-encoded bytes.
Raises BadSyntax if the string contains invalid characters or padding.
:param b: bytes | 6.846935 | 6.508676 | 1.05197 |
if isinstance(val, str):
_val = val.encode("utf-8")
else:
_val = val
return base64_to_long(_val) | def deser(val) | 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. | 3.889523 | 4.777984 | 0.814051 |
res = self.serialize(private=True)
res.update(self.extra_args)
return res | def to_dict(self) | 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 | 10.289712 | 8.266839 | 1.244697 |
res = {"kty": self.kty}
if self.use:
res["use"] = self.use
if self.kid:
res["kid"] = self.kid
if self.alg:
res["alg"] = self.alg
return res | def common(self) | Return the set of parameters that are common to all types of keys.
:return: Dictionary | 2.526089 | 2.687601 | 0.939905 |
for param in self.longs:
item = getattr(self, param)
if not item or isinstance(item, str):
continue
if isinstance(item, bytes):
item = item.decode('utf-8')
setattr(self, param, item)
try:
_... | def verify(self) | 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 | 4.310648 | 4.404638 | 0.978661 |
if members is None:
members = self.required
members.sort()
ser = self.serialize()
_se = []
for elem in members:
try:
_val = ser[elem]
except KeyError: # should never happen with the required set
pass
... | def thumbprint(self, hash_function, members=None) | 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 wh... | 4.781652 | 4.677691 | 1.022225 |
dkm = b''
dk_bytes = int(ceil(dk_len / 8.0))
counter = 0
while len(dkm) < dk_bytes:
counter += 1
counter_bytes = struct.pack("!I", counter)
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
digest.update(counter_bytes)
digest.update(secret)
... | def concat_sha256(secret, dk_len, other_info) | 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: Th... | 2.201027 | 2.257271 | 0.975083 |
if not alg:
alg = self["alg"]
if alg == "none":
return []
_k = self.alg2keytype(alg)
if _k is None:
logger.error("Unknown algorithm '%s'" % alg)
raise ValueError('Unknown cryptography algorithm')
logger.debug("Picking ke... | def pick_keys(self, keys, use="", alg="") | 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 | 2.772628 | 2.758021 | 1.005296 |
self._add_result = Sensor.float("add.result",
"Last ?add result.", "", [-10000, 10000])
self._add_result.set_value(0, Sensor.UNREACHABLE)
self._time_result = Sensor.timestamp("time.result",
"Last ?time result.", "")
self._time_result.set_value(0, Sensor.... | def setup_sensors(self) | Setup some server sensors. | 3.090622 | 2.974686 | 1.038974 |
r = x + y
self._add_result.set_value(r)
return ("ok", r) | def request_add(self, req, x, y) | Add two numbers | 9.328113 | 9.090274 | 1.026164 |
r = time.time()
self._time_result.set_value(r)
return ("ok", r) | def request_time(self, req) | Return the current time in ms since the Unix Epoch. | 11.162601 | 10.161813 | 1.098485 |
r = str(eval(expression))
self._eval_result.set_value(r)
return ("ok", r) | def request_eval(self, req, expression) | Evaluate a Python expression. | 7.876569 | 7.503796 | 1.049678 |
r = random.choice(self.FRUIT + [None])
if r is None:
return ("fail", "No fruit.")
delay = random.randrange(1,5)
req.inform("Picking will take %d seconds" % delay)
def pick_handler():
self._fruit_result.set_value(r)
req.reply("ok", r)
... | def request_pick_fruit(self, req) | Pick a random fruit. | 6.984055 | 6.649679 | 1.050284 |
sensor = self.get_sensor(sensor_name)
ts, status, value = sensor.read()
sensor.set_value(value, sensor.INACTIVE, ts)
return('ok',) | def request_set_sensor_inactive(self, req, sensor_name) | Set sensor status to inactive | 7.24809 | 7.360072 | 0.984785 |
sensor = self.get_sensor(sensor_name)
ts, status, value = sensor.read()
sensor.set_value(value, sensor.UNREACHABLE, ts)
return('ok',) | def request_set_sensor_unreachable(self, req, sensor_name) | Set sensor status to unreachable | 6.32173 | 6.241682 | 1.012825 |
# msg is a katcp.Message.request object
reversed_args = msg.arguments[::-1]
# req.make_reply() makes a katcp.Message.reply using the correct request
# name and message ID
return req.make_reply(*reversed_args) | def request_raw_reverse(self, req, msg) | A raw request handler to demonstrate the calling convention if
@request decoraters are not used. Reverses the message arguments. | 8.972035 | 8.581867 | 1.045464 |
new_future = tornado_Future()
def _transform(f):
assert f is future
if f.exc_info() is not None:
new_future.set_exc_info(f.exc_info())
else:
try:
new_future.set_result(transformation(f.result()))
except Exception:
#... | def transform_future(transformation, future) | Returns a new future that will resolve with a transformed value
Takes the resolution value of `future` and applies transformation(*future.result())
to it before setting the result of the new future with the transformed value. If
future() resolves with an exception, it is passed through to the new future.
... | 3.31319 | 3.200621 | 1.035171 |
filter_re = re.compile(filter)
found_sensors = []
none_strat = resource.normalize_strategy_parameters('none')
sensor_dict = dict(sensor_items)
for sensor_identifier in sorted(sensor_dict.keys()):
sensor_obj = sensor_dict[sensor_identifier]
search_name = (sensor_identifier if use... | def list_sensors(parent_class, sensor_items, filter, strategy, status,
use_python_identifiers, tuple, refresh) | Helper for implementing :meth:`katcp.resource.KATCPResource.list_sensors`
Parameters
----------
sensor_items : tuple of sensor-item tuples
As would be returned the items() method of a dict containing KATCPSensor objects
keyed by Python-identifiers.
parent_class: KATCPClientResource or ... | 3.877071 | 3.628012 | 1.068649 |
exit_event = exit_event or AsyncEvent()
callback(False) # Initial condition, assume resource is not connected
while not exit_event.is_set():
# Wait for resource to be synced
yield until_any(resource.until_synced(), exit_event.until_set())
if exit_event.is_set():
... | def monitor_resource_sync_state(resource, callback, exit_event=None) | Coroutine that monitors a KATCPResource's sync state.
Calls callback(True/False) whenever the resource becomes synced or unsynced. Will
always do an initial callback(False) call. Exits without calling callback() if
exit_event is set | 3.333701 | 3.299946 | 1.010229 |
f = tornado_Future()
try:
use_mid = kwargs.get('use_mid')
timeout = kwargs.get('timeout')
mid = kwargs.get('mid')
msg = Message.request(request, *args, mid=mid)
except Exception:
f.set_exc_info(sys.exc_info())
retur... | def wrapped_request(self, request, *args, **kwargs) | Create and send a request to the server.
This method implements a very small subset of the options
possible to send an request. It is provided as a shortcut to
sending a simple wrapped request.
Parameters
----------
request : str
The request to call.
... | 5.295326 | 3.609535 | 1.467038 |
return self._state.until_state(state, timeout=timeout) | def until_state(self, state, timeout=None) | Future that resolves when a certain client state is attained
Parameters
----------
state : str
Desired state, one of ("disconnected", "syncing", "synced")
timeout: float
Timeout for operation in seconds. | 7.258297 | 14.462563 | 0.501868 |
# TODO (NM 2015-03-12) Some checking to prevent multiple calls to start()
host, port = self.address
ic = self._inspecting_client = self.inspecting_client_factory(
host, port, self._ioloop_set_to)
self.ioloop = ic.ioloop
if self._preset_protocol_flags:
... | def start(self) | Start the client and connect | 6.583428 | 6.559311 | 1.003677 |
return ReplyWrappedInspectingClientAsync(
host, port, ioloop=ioloop_set_to, auto_reconnect=self.auto_reconnect) | def inspecting_client_factory(self, host, port, ioloop_set_to) | Return an instance of :class:`ReplyWrappedInspectingClientAsync` or similar
Provided to ease testing. Dynamically overriding this method after instantiation
but before start() is called allows for deep brain surgery. See
:class:`katcp.fake_clients.fake_inspecting_client_factory` | 7.599838 | 3.78254 | 2.009189 |
not_synced_states = [state for state in self._state.valid_states
if state != 'synced']
not_synced_futures = [self._state.until_state(state)
for state in not_synced_states]
return until_any(*not_synced_futures, timeout=timeout) | def until_not_synced(self, timeout=None) | Convenience method to wait (with Future) until client is not synced | 3.946881 | 3.640045 | 1.084295 |
sensor_list = yield self.list_sensors(filter=filter)
sensor_dict = {}
for sens in sensor_list:
# Set the strategy on each sensor
try:
sensor_name = sens.object.normalised_name
yield self.set_sampling_strategy(sensor_name, strategy_... | def set_sampling_strategies(self, filter, strategy_and_parms) | Set a strategy for all sensors matching the filter, including unseen sensors
The strategy should persist across sensor disconnect/reconnect.
filter : str
Filter for sensor names
strategy_and_params : seq of str or str
As tuple contains (<strat_name>, [<strat_parm1>, ...]... | 5.412076 | 5.288043 | 1.023455 |
sensor_name = resource.escape_name(sensor_name)
sensor_obj = dict.get(self._sensor, sensor_name)
self._sensor_strategy_cache[sensor_name] = strategy_and_parms
sensor_dict = {}
self._logger.debug(
'Cached strategy {} for sensor {}'
.format(... | def set_sampling_strategy(self, sensor_name, strategy_and_parms) | Set a strategy for a sensor even if it is not yet known.
The strategy should persist across sensor disconnect/reconnect.
sensor_name : str
Name of the sensor
strategy_and_params : seq of str or str
As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the strategy... | 4.107545 | 4.201224 | 0.977702 |
sensor_name = resource.escape_name(sensor_name)
# drop from both the internal cache, and the sensor manager's cache
self._sensor_strategy_cache.pop(sensor_name, None)
self._sensor_manager.drop_sampling_strategy(sensor_name) | def drop_sampling_strategy(self, sensor_name) | Drop the sampling strategy for the named sensor from the cache
Calling :meth:`set_sampling_strategy` requires the requested strategy to
be memorised so that it can automatically be reapplied. This method
causes the strategy to be forgotten. There is no change to the current
strategy. ... | 5.170333 | 6.755823 | 0.765315 |
sensor_name = resource.escape_name(sensor_name)
sensor_obj = dict.get(self._sensor, sensor_name)
self._sensor_listener_cache[sensor_name].append(listener)
sensor_dict = {}
self._logger.debug(
'Cached listener {} for sensor {}'
.format(lis... | def set_sensor_listener(self, sensor_name, listener) | Set a sensor listener for a sensor even if it is not yet known
The listener registration should persist across sensor disconnect/reconnect.
sensor_name : str
Name of the sensor
listener : callable
Listening callable that will be registered on the named sensor when it bec... | 4.082339 | 4.066289 | 1.003947 |
# try for a direct match first, otherwise do full comparison
if sensor_name in self._strategy_cache:
return sensor_name
else:
escaped_name = resource.escape_name(sensor_name)
for key in self._strategy_cache:
escaped_key = resource.esca... | def _get_strategy_cache_key(self, sensor_name) | Lookup sensor name in cache, allowing names in escaped form
The strategy cache uses the normal KATCP sensor names as the keys.
In order to allow access using an escaped sensor name, this method
tries to find the normal form of the name.
Returns
-------
key : str
... | 3.594167 | 3.47332 | 1.034793 |
cache_key = self._get_strategy_cache_key(sensor_name)
cached = self._strategy_cache.get(cache_key)
if not cached:
return resource.normalize_strategy_parameters('none')
else:
return cached | def get_sampling_strategy(self, sensor_name) | Get the current sampling strategy for the named sensor
Parameters
----------
sensor_name : str
Name of the sensor (normal or escaped form)
Returns
-------
strategy : tuple of str
contains (<strat_name>, [<strat_parm1>, ...]) where the strategy ... | 5.779981 | 5.685621 | 1.016596 |
try:
strategy_and_params = resource.normalize_strategy_parameters(
strategy_and_params)
self._strategy_cache[sensor_name] = strategy_and_params
reply = yield self._inspecting_client.wrapped_request(
'sensor-sampling', sensor_name, *str... | def set_sampling_strategy(self, sensor_name, strategy_and_params) | Set the sampling strategy for the named sensor
Parameters
----------
sensor_name : str
Name of the sensor
strategy_and_params : seq of str or str
As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the
strategy names and parameters are as de... | 4.504522 | 3.962734 | 1.136721 |
cache_key = self._get_strategy_cache_key(sensor_name)
self._strategy_cache.pop(cache_key, None) | def drop_sampling_strategy(self, sensor_name) | Drop the sampling strategy for the named sensor from the cache
Calling :meth:`set_sampling_strategy` requires the sensor manager to
memorise the requested strategy so that it can automatically be reapplied.
If the client is no longer interested in the sensor, or knows the sensor
may be ... | 4.034231 | 6.006219 | 0.671676 |
check_sensor = self._inspecting_client.future_check_sensor
for sensor_name, strategy in list(self._strategy_cache.items()):
try:
sensor_exists = yield check_sensor(sensor_name)
if not sensor_exists:
self._logger.warn('Did not set s... | def reapply_sampling_strategies(self) | Reapply all sensor strategies using cached values | 3.77688 | 3.471109 | 1.08809 |
timeout = kwargs.pop('timeout', None)
if timeout is None:
timeout = self.timeout_hint
kwargs['timeout'] = timeout
return self._client.wrapped_request(self.name, *args, **kwargs) | def issue_request(self, *args, **kwargs) | Issue the wrapped request to the server.
Parameters
----------
*args : list of objects
Arguments to pass on to the request.
Keyword Arguments
-----------------
timeout : float or None, optional
Timeout after this amount of seconds (keyword argume... | 4.320929 | 4.877084 | 0.885966 |
futures_dict = {}
for res_obj in self.clients:
futures_dict[res_obj.name] = res_obj.set_sampling_strategies(
filter, strategy_and_params)
sensors_strategies = yield futures_dict
raise tornado.gen.Return(sensors_strategies) | def set_sampling_strategies(self, filter, strategy_and_params) | Set sampling strategy for the sensors of all the group's clients.
Only sensors that match the specified filter are considered. See the
`KATCPResource.set_sampling_strategies` docstring for parameter
definitions and more info.
Returns
-------
sensors_strategies : tornado... | 4.236555 | 3.014909 | 1.405202 |
futures_dict = {}
for res_obj in self.clients:
futures_dict[res_obj.name] = res_obj.set_sampling_strategy(
sensor_name, strategy_and_params)
sensors_strategies = yield futures_dict
raise tornado.gen.Return(sensors_strategies) | def set_sampling_strategy(self, sensor_name, strategy_and_params) | Set sampling strategy for the sensors of all the group's clients.
Only sensors that match the specified filter are considered. See the
`KATCPResource.set_sampling_strategies` docstring for parameter
definitions and more info.
Returns
-------
sensors_strategies : tornado... | 3.803136 | 3.013692 | 1.261952 |
if quorum is None:
quorum = len(self.clients)
elif quorum > 1:
if not isinstance(quorum, int):
raise TypeError('Quorum parameter %r must be an integer '
'if outside range [0, 1]' % (quorum,))
elif isinstance(quorum,... | def wait(self, sensor_name, condition_or_value, timeout=5.0, quorum=None,
max_grace_period=1.0) | Wait for sensor present on all group clients to satisfy a condition.
Parameters
----------
sensor_name : string
The name of the sensor to check
condition_or_value : obj or callable, or seq of objs or callables
If obj, sensor.value is compared with obj. If callabl... | 3.777385 | 3.785934 | 0.997742 |
return KATCPClientResource(res_spec, parent=self, logger=logger) | def client_resource_factory(self, res_spec, parent, logger) | Return an instance of :class:`KATCPClientResource` or similar
Provided to ease testing. Overriding this method allows deep brain surgery. See
:func:`katcp.fake_clients.fake_KATCP_client_resource_factory` | 8.007259 | 5.662302 | 1.414135 |
group_configs = self._resources_spec.get('groups', {})
group_configs[group_name] = group_client_names
self._resources_spec['groups'] = group_configs
self._init_groups() | def add_group(self, group_name, group_client_names) | Add a new :class:`ClientGroup` to container groups member.
Add the group named *group_name* with sequence of client names to the
container groups member. From there it will be wrapped appropriately
in the higher-level thread-safe container. | 3.578304 | 4.331336 | 0.826143 |
ioloop = ioloop or tornado.ioloop.IOLoop.current()
self.ioloop = ioloop
for res in dict.values(self.children):
res.set_ioloop(ioloop) | def set_ioloop(self, ioloop=None) | Set the tornado ioloop to use
Defaults to tornado.ioloop.IOLoop.current() if set_ioloop() is not called or if
ioloop=None. Must be called before start() | 3.107394 | 3.958627 | 0.784967 |
return all([r.is_connected() for r in dict.values(self.children)]) | def is_connected(self) | Indication of the connection state of all children | 11.22712 | 7.107965 | 1.579513 |
futures = [r.until_synced(timeout) for r in dict.values(self.children)]
yield tornado.gen.multi(futures, quiet_exceptions=tornado.gen.TimeoutError) | def until_synced(self, timeout=None) | Return a tornado Future; resolves when all subordinate clients are synced | 7.648281 | 6.056131 | 1.262899 |
yield until_any(*[r.until_not_synced() for r in dict.values(self.children)],
timeout=timeout) | def until_not_synced(self, timeout=None) | Return a tornado Future; resolves when any subordinate client is not synced | 12.203305 | 10.025229 | 1.21726 |
return until_any(*[r.until_state(state) for r in dict.values(self.children)],
timeout=timeout) | def until_any_child_in_state(self, state, timeout=None) | Return a tornado Future; resolves when any client is in specified state | 9.178947 | 9.046895 | 1.014596 |
futures = [r.until_state(state, timeout=timeout)
for r in dict.values(self.children)]
yield tornado.gen.multi(futures, quiet_exceptions=tornado.gen.TimeoutError) | def until_all_children_in_state(self, state, timeout=None) | Return a tornado Future; resolves when all clients are in specified state | 6.374424 | 5.73055 | 1.112358 |
result_list = yield self.list_sensors(filter=filter)
sensor_dict = {}
for result in result_list:
sensor_name = result.object.normalised_name
resource_name = result.object.parent_name
if resource_name not in sensor_dict:
sensor_dict[res... | def set_sampling_strategies(self, filter, strategy_and_parms) | Set sampling strategies for filtered sensors - these sensors have to exsist | 2.541878 | 2.519746 | 1.008783 |
res_spec = dict(res_spec)
res_spec['name'] = res_name
res = self.client_resource_factory(
res_spec, parent=self, logger=self._logger)
self.children[resource.escape_name(res_name)] = res;
self._children_dirty = True
res.set_ioloop(self.ioloop)
... | def add_child_resource_client(self, res_name, res_spec) | Add a resource client to the container and start the resource connection | 4.134435 | 4.087295 | 1.011533 |
for child_name, child in dict.items(self.children):
# Catch child exceptions when stopping so we make sure to stop all children
# that want to listen.
try:
child.stop()
except Exception:
self._logger.exception('Exception st... | def stop(self) | Stop all child resources | 6.934161 | 6.488183 | 1.068737 |
# skip signature
i = 8
# yield chunks
while i < len(b):
data_len, = struct.unpack("!I", b[i:i+4])
type_ = b[i+4:i+8].decode("latin-1")
yield Chunk(type_, b[i:i+data_len+12])
i += data_len + 12 | def parse_chunks(b) | Parse PNG bytes into multiple chunks.
:arg bytes b: The raw bytes of the PNG file.
:return: A generator yielding :class:`Chunk`.
:rtype: Iterator[Chunk] | 3.140841 | 3.108436 | 1.010425 |
out = struct.pack("!I", len(chunk_data))
chunk_data = chunk_type.encode("latin-1") + chunk_data
out += chunk_data + struct.pack("!I", binascii.crc32(chunk_data) & 0xffffffff)
return out | def make_chunk(chunk_type, chunk_data) | Create a raw chunk by composing chunk type and data. It
calculates chunk length and CRC for you.
:arg str chunk_type: PNG chunk type.
:arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**.
:rtype: bytes | 2.679699 | 2.703962 | 0.991027 |
# pylint: disable=redefined-builtin
if type == "tEXt":
data = key.encode("latin-1") + b"\0" + value.encode("latin-1")
elif type == "zTXt":
data = (
key.encode("latin-1") + struct.pack("!xb", compression_method) +
zlib.compress(value.encode("latin-1"))
)
elif type == "iTXt":
data = (
key.encode("l... | def make_text_chunk(
type="tEXt", key="Comment", value="",
compression_flag=0, compression_method=0, lang="", translated_key="") | Create a text chunk with a key value pair.
See https://www.w3.org/TR/PNG/#11textinfo for text chunk information.
Usage:
.. code:: python
from apng import APNG, make_text_chunk
im = APNG.open("file.png")
png, control = im.frames[0]
png.chunks.append(make_text_chunk("tEXt", "Comment", "some text"))
im.s... | 2.057444 | 1.966712 | 1.046134 |
if hasattr(file, "read"):
return file.read()
if hasattr(file, "read_bytes"):
return file.read_bytes()
with open(file, "rb") as f:
return f.read() | def read_file(file) | Read ``file`` into ``bytes``.
:arg file type: path-like or file-like
:rtype: bytes | 1.95735 | 1.936011 | 1.011022 |
if hasattr(file, "write_bytes"):
file.write_bytes(b)
elif hasattr(file, "write"):
file.write(b)
else:
with open(file, "wb") as f:
f.write(b) | def write_file(file, b) | Write ``b`` to file ``file``.
:arg file type: path-like or file-like object.
:arg bytes b: The content. | 1.842604 | 1.90136 | 0.969098 |
if hasattr(file, "read"):
return file
if hasattr(file, "open"):
return file.open(mode)
return open(file, mode) | def open_file(file, mode) | Open a file.
:arg file: file-like or path-like object.
:arg str mode: ``mode`` argument for :func:`open`. | 2.367348 | 2.996791 | 0.789961 |
import PIL.Image # pylint: disable=import-error
with io.BytesIO() as dest:
PIL.Image.open(fp).save(dest, "PNG", optimize=True)
return dest.getvalue() | def file_to_png(fp) | Convert an image to PNG format with Pillow.
:arg file-like fp: The image file.
:rtype: bytes | 2.904195 | 2.939399 | 0.988024 |
for type_, data in self.chunks:
if type_ == "IHDR":
self.hdr = data
elif type_ == "IEND":
self.end = data
if self.hdr:
# grab w, h info
self.width, self.height = struct.unpack("!II", self.hdr[8:16]) | def init(self) | Extract some info from chunks | 3.604221 | 3.124681 | 1.153468 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.