Skip to content

Commit 788c8cb

Browse files
committed
Use format specifiers instead of percent format
1 parent 9907b2a commit 788c8cb

File tree

12 files changed

+30
-30
lines changed

12 files changed

+30
-30
lines changed

src/cryptojwt/exception.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def __init__(self, value, msg):
2020
self.msg = msg
2121

2222
def __str__(self):
23-
return "%s: %r" % (self.msg, self.value)
23+
return f"{self.msg}: {self.value!r}"
2424

2525

2626
class BadSignature(Invalid):

src/cryptojwt/jwe/jwe.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ def decrypt(self, token=None, keys=None, alg=None, cek=None):
199199
except (KeyError, DecryptionFailed):
200200
pass
201201
else:
202-
logger.debug("Decrypted message using key with kid=%s" % key.kid)
202+
logger.debug(f"Decrypted message using key with kid={key.kid}")
203203
return msg
204204

205205
raise DecryptionFailed("No available key that could decrypt the message")

src/cryptojwt/jwe/jwe_ec.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def enc_setup(self, msg, key=None, auth_data=b"", **kwargs):
112112
try:
113113
dk_len = KEY_LEN[self.enc]
114114
except KeyError as exc:
115-
raise ValueError("Unknown key length for algorithm %s" % self.enc) from exc
115+
raise ValueError(f"Unknown key length for algorithm {self.enc}") from exc
116116

117117
cek = ecdh_derive_key(_epk, key.pub_key, apu, apv, str(self.enc).encode(), dk_len)
118118
elif self.alg in ["ECDH-ES+A128KW", "ECDH-ES+A192KW", "ECDH-ES+A256KW"]:
@@ -122,7 +122,7 @@ def enc_setup(self, msg, key=None, auth_data=b"", **kwargs):
122122
cek = self._generate_key(self.enc, cek=cek)
123123
encrypted_key = aes_key_wrap(kek, cek)
124124
else:
125-
raise Exception("Unsupported algorithm %s" % self.alg)
125+
raise Exception(f"Unsupported algorithm {self.alg}")
126126

127127
return cek, encrypted_key, iv, params, epk
128128

@@ -174,7 +174,7 @@ def dec_setup(self, token, key=None, **kwargs):
174174
kek = ecdh_derive_key(key, epubkey.pub_key, apu, apv, str(_post).encode(), klen)
175175
self.cek = aes_key_unwrap(kek, token.encrypted_key())
176176
else:
177-
raise Exception("Unsupported algorithm %s" % self.headers["alg"])
177+
raise Exception("Unsupported algorithm {}".format(self.headers["alg"]))
178178

179179
return self.cek
180180

src/cryptojwt/jwe/jwe_rsa.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def encrypt(self, key, iv="", cek="", **kwargs):
4949
if self["zip"] == "DEF":
5050
_msg = zlib.compress(_msg)
5151
else:
52-
raise ParameterError("Zip has unknown value: %s" % self["zip"])
52+
raise ParameterError("Zip has unknown value: {}".format(self["zip"]))
5353

5454
kwarg_cek = cek or None
5555

@@ -58,7 +58,7 @@ def encrypt(self, key, iv="", cek="", **kwargs):
5858
cek = self._generate_key(_enc, cek)
5959
self["cek"] = cek
6060

61-
logger.debug("cek: %s, iv: %s" % ([c for c in cek], [c for c in iv]))
61+
logger.debug(f"cek: {[c for c in cek]}, iv: {[c for c in iv]}")
6262

6363
_encrypt = RSAEncrypter(self.with_digest).encrypt
6464

src/cryptojwt/jwe/jwekey.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def _generate_key(encalg, cek=""):
3030
try:
3131
_key = get_random_bytes(KEY_LEN_BYTES[encalg])
3232
except KeyError as exc:
33-
raise ValueError("Unsupported encryption algorithm %s" % encalg) from exc
33+
raise ValueError(f"Unsupported encryption algorithm {encalg}") from exc
3434

3535
return _key
3636

@@ -77,7 +77,7 @@ def _decrypt(enc, key, ctxt, iv, tag, auth_data=b""):
7777
elif enc in ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512"]:
7878
aes = AES_CBCEncrypter(key=key)
7979
else:
80-
raise Exception("Unsupported encryption algorithm %s" % enc)
80+
raise Exception(f"Unsupported encryption algorithm {enc}")
8181

8282
try:
8383
return aes.decrypt(ctxt, iv=iv, auth_data=auth_data, tag=tag)

src/cryptojwt/jwe/jwenc.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def is_jwe(self):
4848
if "alg" in self.headers and "enc" in self.headers:
4949
for typ in ["alg", "enc"]:
5050
if self.headers[typ] not in SUPPORTED[typ]:
51-
logger.debug("Not supported %s algorithm: %s" % (typ, self.headers[typ]))
51+
logger.debug(f"Not supported {typ} algorithm: {self.headers[typ]}")
5252
return False
5353
else:
5454
return False

src/cryptojwt/jwe/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def get_keys_seclen_dgst(key, iv):
1919
try:
2020
seclen, hash_method = LENMET[len(key)]
2121
except KeyError as exc:
22-
raise Exception("Invalid CBC+HMAC key length: %s bytes" % len(key)) from exc
22+
raise Exception(f"Invalid CBC+HMAC key length: {len(key)} bytes") from exc
2323

2424
# Split the key
2525
ka = key[:seclen]

src/cryptojwt/jwk/jwk.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def key_from_jwk_dict(jwk_dict, private=None):
100100
if _jwk_dict["crv"] in NIST2SEC:
101101
curve = NIST2SEC[_jwk_dict["crv"]]()
102102
else:
103-
raise UnsupportedAlgorithm("Unknown curve: %s" % (_jwk_dict["crv"]))
103+
raise UnsupportedAlgorithm("Unknown curve: {}".format(_jwk_dict["crv"]))
104104

105105
if _jwk_dict.get("d", None) is not None:
106106
# Ecdsa private key.

src/cryptojwt/jwk/x509.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,9 @@ def load_x509_cert(url, httpc, spec2key, **get_args):
106106
elif isinstance(public_key, ec.EllipticCurvePublicKey):
107107
return {"ec": public_key}
108108
else:
109-
raise Exception("HTTP Get error: %s" % r.status_code)
109+
raise Exception(f"HTTP Get error: {r.status_code}")
110110
except Exception as err: # not a RSA key
111-
logger.warning("Can't load key: %s" % err)
111+
logger.warning(f"Can't load key: {err}")
112112
return []
113113

114114

src/cryptojwt/jws/jws.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,10 @@ def alg_keys(self, keys, use, protected=None):
9393
else:
9494
if "kid" in self:
9595
raise NoSuitableSigningKeys(
96-
"No key for algorithm: %s and kid: %s" % (_alg, self["kid"])
96+
"No key for algorithm: {} and kid: {}".format(_alg, self["kid"])
9797
)
9898
else:
99-
raise NoSuitableSigningKeys("No key for algorithm: %s" % _alg)
99+
raise NoSuitableSigningKeys(f"No key for algorithm: {_alg}")
100100

101101
return key, xargs, _alg
102102

@@ -137,7 +137,7 @@ def sign_compact(self, keys=None, protected=None, **kwargs):
137137
else:
138138
sig = _signer.sign(_input.encode("utf-8"), key.key)
139139

140-
logger.debug("Signed message using key with kid=%s" % key.kid)
140+
logger.debug(f"Signed message using key with kid={key.kid}")
141141
return ".".join([_input, b64encode_item(sig).decode("utf-8")])
142142

143143
def verify_compact(self, jws=None, keys=None, allow_none=False, sigalg=None):
@@ -209,11 +209,11 @@ def verify_compact_verbose(self, jws=None, keys=None, allow_none=False, sigalg=N
209209

210210
if not _keys:
211211
if "kid" in self:
212-
raise NoSuitableSigningKeys("No key with kid: %s" % (self["kid"]))
212+
raise NoSuitableSigningKeys("No key with kid: {}".format(self["kid"]))
213213
elif "kid" in self.jwt.headers:
214-
raise NoSuitableSigningKeys("No key with kid: %s" % (self.jwt.headers["kid"]))
214+
raise NoSuitableSigningKeys("No key with kid: {}".format(self.jwt.headers["kid"]))
215215
else:
216-
raise NoSuitableSigningKeys("No key for algorithm: %s" % _alg)
216+
raise NoSuitableSigningKeys(f"No key for algorithm: {_alg}")
217217

218218
verifier = SIGNER_ALGS[_alg]
219219

@@ -228,7 +228,7 @@ def verify_compact_verbose(self, jws=None, keys=None, allow_none=False, sigalg=N
228228
except (ValueError, TypeError) as err:
229229
logger.warning(f'Exception "{err}" caught')
230230
else:
231-
logger.debug("Verified message using key with kid=%s" % key.kid)
231+
logger.debug(f"Verified message using key with kid={key.kid}")
232232
self.msg = jwt.payload()
233233
self.key = key
234234
self._protected_headers = jwt.headers.copy()
@@ -408,7 +408,7 @@ def _is_compact_jws(self, jws):
408408
jwt.headers["alg"] = "none"
409409

410410
if jwt.headers["alg"] not in SIGNER_ALGS:
411-
logger.debug("UnknownSignerAlg: %s" % jwt.headers["alg"])
411+
logger.debug("UnknownSignerAlg: {}".format(jwt.headers["alg"]))
412412
return False
413413

414414
self.jwt = jwt

src/cryptojwt/key_bundle.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1007,7 +1007,7 @@ def build_key_bundle(key_conf, kid_template=""):
10071007
if "key" in spec and spec["key"]:
10081008
if os.path.isfile(spec["key"]):
10091009
_bundle = KeyBundle(
1010-
source="file://%s" % spec["key"],
1010+
source="file://{}".format(spec["key"]),
10111011
fileformat="der",
10121012
keytype=typ,
10131013
keyusage=spec["use"],
@@ -1018,7 +1018,7 @@ def build_key_bundle(key_conf, kid_template=""):
10181018
if "key" in spec and spec["key"]:
10191019
if os.path.isfile(spec["key"]):
10201020
_bundle = KeyBundle(
1021-
source="file://%s" % spec["key"],
1021+
source="file://{}".format(spec["key"]),
10221022
fileformat="der",
10231023
keytype=typ,
10241024
keyusage=spec["use"],
@@ -1029,7 +1029,7 @@ def build_key_bundle(key_conf, kid_template=""):
10291029
if "key" in spec and spec["key"]:
10301030
if os.path.isfile(spec["key"]):
10311031
_bundle = KeyBundle(
1032-
source="file://%s" % spec["key"],
1032+
source="file://{}".format(spec["key"]),
10331033
fileformat="der",
10341034
keytype=typ,
10351035
keyusage=spec["use"],

src/cryptojwt/utils.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,11 @@
2020

2121

2222
def intarr2bin(arr):
23-
return unhexlify("".join(["%02x" % byte for byte in arr]))
23+
return unhexlify("".join([f"{byte:02x}" for byte in arr]))
2424

2525

2626
def intarr2long(arr):
27-
return int("".join(["%02x" % byte for byte in arr]), 16)
27+
return int("".join([f"{byte:02x}" for byte in arr]), 16)
2828

2929

3030
def intarr2str(arr):
@@ -45,7 +45,7 @@ def long_to_base64(n, mlen=0):
4545
_len = mlen - len(bys)
4646
if _len:
4747
bys = [0] * _len + bys
48-
data = struct.pack("%sB" % len(bys), *bys)
48+
data = struct.pack(f"{len(bys)}B", *bys)
4949
if not len(data):
5050
data = b"\x00"
5151
s = base64.urlsafe_b64encode(data).rstrip(b"=")
@@ -58,7 +58,7 @@ def base64_to_long(data):
5858

5959
# urlsafe_b64decode will happily convert b64encoded data
6060
_d = base64.urlsafe_b64decode(as_bytes(data) + b"==")
61-
return intarr2long(struct.unpack("%sB" % len(_d), _d))
61+
return intarr2long(struct.unpack(f"{len(_d)}B", _d))
6262

6363

6464
def base64url_to_long(data):
@@ -75,7 +75,7 @@ def base64url_to_long(data):
7575
# that is no '+' and '/' characters and not trailing "="s.
7676
if [e for e in [b"+", b"/", b"="] if e in _data]:
7777
raise ValueError("Not base64url encoded")
78-
return intarr2long(struct.unpack("%sB" % len(_d), _d))
78+
return intarr2long(struct.unpack(f"{len(_d)}B", _d))
7979

8080

8181
# =============================================================================

0 commit comments

Comments
 (0)