Skip to content

Commit 822d057

Browse files
committed
reformat code
1 parent 8ab1af2 commit 822d057

File tree

8 files changed

+155
-138
lines changed

8 files changed

+155
-138
lines changed

jwt_rsa/__init__.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
11
try:
22
from .version import __version__, version_info
33
except ImportError:
4-
version_info = (0, 0, 0, 'x')
5-
__version__ = '{}.{}.{}+{}'.format(*version_info)
4+
version_info = (0, 0, 0, "x")
5+
__version__ = "{}.{}.{}+{}".format(*version_info)
66

77
authors = (
8-
('Dmitry Orlov', '[email protected]'),
8+
("Dmitry Orlov", "[email protected]"),
99
)
1010

1111
# TODO: Use mailing list instead
1212
authors_email = ", ".join(
13-
'{}'.format(email) for _, email in authors
13+
f"{email}" for _, email in authors
1414
)
1515

16-
__license__ = 'MIT',
16+
__license__ = "MIT",
1717
__author__ = ", ".join(
18-
'{} <{}>'.format(name, email) for name, email in authors
18+
f"{name} <{email}>" for name, email in authors
1919
)
2020

21-
package_info = 'RSA helpers for PyJWT'
21+
package_info = "RSA helpers for PyJWT"
2222

2323
# It's same persons right now
2424
__maintainer__ = __author__
2525

2626
__all__ = (
27-
'__author__', '__author__', '__license__',
28-
'__maintainer__', '__version__', 'version_info',
27+
"__author__", "__author__", "__license__",
28+
"__maintainer__", "__version__", "version_info",
2929
)

jwt_rsa/issue.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,23 @@
11
import argparse
22
import json
33

4-
from .token import JWT
54
from .rsa import load_private_key
5+
from .token import JWT
66

77

88
parser = argparse.ArgumentParser()
9-
parser.add_argument("-K", "--private-key", required=True,
10-
help="Private JWT key", type=load_private_key)
11-
parser.add_argument("--expired", help="Token expiration",
12-
type=float, default=...)
13-
parser.add_argument("--nbf", help="Token nbf claim",
14-
type=float, default=...)
9+
parser.add_argument(
10+
"-K", "--private-key", required=True,
11+
help="Private JWT key", type=load_private_key,
12+
)
13+
parser.add_argument(
14+
"--expired", help="Token expiration",
15+
type=float, default=...,
16+
)
17+
parser.add_argument(
18+
"--nbf", help="Token nbf claim",
19+
type=float, default=...,
20+
)
1521

1622

1723
def main() -> None:
@@ -21,10 +27,10 @@ def main() -> None:
2127
jwt.encode(
2228
expired=arguments.expired,
2329
nbf=arguments.nbf,
24-
**json.loads(input("Paste JSON content here: "))
25-
)
30+
**json.loads(input("Paste JSON content here: ")),
31+
),
2632
)
2733

2834

29-
if __name__ == '__main__':
35+
if __name__ == "__main__":
3036
main()

jwt_rsa/keygen.py

Lines changed: 36 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,56 @@
1+
import argparse
12
import base64
23
import json
3-
import argparse
44

5-
from .rsa import generate_rsa
65
from cryptography.hazmat.primitives import serialization
76

7+
from .rsa import generate_rsa
8+
89

910
def main() -> None:
1011
parser = argparse.ArgumentParser()
11-
parser.add_argument('-b', '--bits', dest="bits", type=int, default=2048)
12-
parser.add_argument('-P', '--pem', dest="pem", action='store_true')
12+
parser.add_argument("-b", "--bits", dest="bits", type=int, default=2048)
13+
parser.add_argument("-P", "--pem", dest="pem", action="store_true")
1314

1415
arguments = parser.parse_args()
1516

1617
private_key, public_key = generate_rsa(arguments.bits)
1718

1819
if arguments.pem:
19-
print(private_key.private_bytes(
20-
encoding=serialization.Encoding.PEM,
21-
encryption_algorithm=serialization.NoEncryption(),
22-
format=serialization.PrivateFormat.PKCS8
23-
).decode())
24-
print(public_key.public_bytes(
25-
encoding=serialization.Encoding.PEM,
26-
format=serialization.PublicFormat.PKCS1
27-
).decode())
20+
print(
21+
private_key.private_bytes(
22+
encoding=serialization.Encoding.PEM,
23+
encryption_algorithm=serialization.NoEncryption(),
24+
format=serialization.PrivateFormat.PKCS8,
25+
).decode(),
26+
)
27+
print(
28+
public_key.public_bytes(
29+
encoding=serialization.Encoding.PEM,
30+
format=serialization.PublicFormat.PKCS1,
31+
).decode(),
32+
)
2833
else:
2934
print(
30-
json.dumps({
31-
'private': base64.b64encode(
32-
private_key.private_bytes(
33-
encoding=serialization.Encoding.DER,
34-
encryption_algorithm=serialization.NoEncryption(),
35-
format=serialization.PrivateFormat.PKCS8
36-
)
37-
).decode(),
38-
'public': base64.b64encode(
39-
public_key.public_bytes(
40-
encoding=serialization.Encoding.DER,
41-
format=serialization.PublicFormat.PKCS1
42-
)
43-
).decode()
44-
}, indent='\t')
35+
json.dumps(
36+
{
37+
"private": base64.b64encode(
38+
private_key.private_bytes(
39+
encoding=serialization.Encoding.DER,
40+
encryption_algorithm=serialization.NoEncryption(),
41+
format=serialization.PrivateFormat.PKCS8,
42+
),
43+
).decode(),
44+
"public": base64.b64encode(
45+
public_key.public_bytes(
46+
encoding=serialization.Encoding.DER,
47+
format=serialization.PublicFormat.PKCS1,
48+
),
49+
).decode(),
50+
}, indent="\t",
51+
),
4552
)
4653

4754

48-
if __name__ == '__main__':
55+
if __name__ == "__main__":
4956
main()

jwt_rsa/rsa.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@
44
from cryptography.hazmat.backends import default_backend
55
from cryptography.hazmat.primitives import serialization
66
from cryptography.hazmat.primitives.asymmetric import rsa
7-
from cryptography.hazmat.primitives.asymmetric.rsa import (
8-
RSAPrivateKeyWithSerialization as RSAPrivateKey,
9-
RSAPublicKeyWithSerialization as RSAPublicKey,
10-
)
7+
from cryptography.hazmat.primitives.asymmetric.rsa import \
8+
RSAPrivateKeyWithSerialization as RSAPrivateKey
9+
from cryptography.hazmat.primitives.asymmetric.rsa import \
10+
RSAPublicKeyWithSerialization as RSAPublicKey
1111

12-
KeyPair = namedtuple('KeyPair', ('private', 'public'))
12+
13+
KeyPair = namedtuple("KeyPair", ("private", "public"))
1314

1415

1516
def generate_rsa(bits: int = 2048) -> KeyPair:
@@ -22,7 +23,7 @@ def generate_rsa(bits: int = 2048) -> KeyPair:
2223
private_key = rsa.generate_private_key(
2324
public_exponent=65537,
2425
key_size=bits,
25-
backend=default_backend()
26+
backend=default_backend(),
2627
)
2728

2829
public_key = private_key.public_key()
@@ -32,11 +33,11 @@ def generate_rsa(bits: int = 2048) -> KeyPair:
3233

3334
def load_private_key(data: str) -> RSAPrivateKey:
3435
return serialization.load_der_private_key(
35-
base64.b64decode(data), None, default_backend()
36+
base64.b64decode(data), None, default_backend(),
3637
)
3738

3839

3940
def load_public_key(data: str) -> RSAPublicKey:
4041
return serialization.load_der_public_key(
41-
base64.b64decode(data), default_backend()
42+
base64.b64decode(data), default_backend(),
4243
)

jwt_rsa/token.py

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,32 @@
11
import time
22
from datetime import datetime, timedelta
33
from operator import add, sub
4-
from typing import Any, Callable, Dict, Optional, TYPE_CHECKING, TypeVar, \
5-
Union
4+
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, TypeVar, Union
65

76
from jwt import PyJWT
8-
97
from jwt_rsa.rsa import RSAPrivateKey, RSAPublicKey
108

9+
1110
if TYPE_CHECKING:
1211
# pylama:ignore=E0602
1312
DateType = Union[timedelta, datetime, float, int, ellipsis]
1413
else:
1514
DateType = Union[timedelta, datetime, float, int, type(Ellipsis)]
1615

17-
R = TypeVar('R')
16+
R = TypeVar("R")
1817

1918

2019
class JWT:
21-
__slots__ = ('__private_key', '__public_key', '__jwt',
22-
'__expires', '__nbf_delta', '__algorithm')
20+
__slots__ = (
21+
"__private_key", "__public_key", "__jwt",
22+
"__expires", "__nbf_delta", "__algorithm",
23+
)
2324

2425
DEFAULT_EXPIRATION = 86400 * 30 # one month
2526
NBF_DELTA = 20
2627
ALGORITHMS = tuple({
27-
'RS256', 'RS384', 'RS512', 'ES256', 'ES384',
28-
'ES521', 'ES512', 'PS256', 'PS384', 'PS512'
28+
"RS256", "RS384", "RS512", "ES256", "ES384",
29+
"ES521", "ES512", "PS256", "PS384", "PS512",
2930
})
3031

3132
def __init__(
@@ -34,7 +35,7 @@ def __init__(
3435
public_key: Optional[RSAPublicKey] = None,
3536
expires: Optional[int] = None,
3637
nbf_delta: Optional[int] = None,
37-
algorithm: str = "RS512"
38+
algorithm: str = "RS512",
3839
):
3940

4041
self.__private_key = private_key
@@ -48,7 +49,7 @@ def _date_to_timestamp(
4849
self,
4950
value: DateType,
5051
default: Callable[[], R],
51-
timedelta_func: Callable[[float, float], int] = add
52+
timedelta_func: Callable[[float, float], int] = add,
5253
) -> Union[int, float, R]:
5354
if isinstance(value, timedelta):
5455
return timedelta_func(time.time(), value.total_seconds())
@@ -65,7 +66,7 @@ def encode(
6566
self,
6667
expired: DateType = ...,
6768
nbf: DateType = ...,
68-
**claims: int
69+
**claims: int,
6970
) -> str:
7071
if not self.__private_key:
7172
raise RuntimeError("Can't encode without private key")
@@ -75,17 +76,17 @@ def encode(
7576
exp=int(
7677
self._date_to_timestamp(
7778
expired,
78-
lambda: time.time() + self.__expires
79-
)
79+
lambda: time.time() + self.__expires,
80+
),
8081
),
8182
nbf=int(
8283
self._date_to_timestamp(
8384
nbf,
8485
lambda: time.time() - self.__nbf_delta,
85-
timedelta_func=sub
86-
)
86+
timedelta_func=sub,
87+
),
8788
),
88-
)
89+
),
8990
)
9091

9192
return self.__jwt.encode(
@@ -95,7 +96,7 @@ def encode(
9596
).decode()
9697

9798
def decode(
98-
self, token: str, verify: bool = True, **kwargs: Any
99+
self, token: str, verify: bool = True, **kwargs: Any,
99100
) -> Dict[str, Any]:
100101
if not self.__public_key:
101102
raise RuntimeError("Can't decode without public key")
@@ -105,11 +106,11 @@ def decode(
105106
key=self.__public_key,
106107
verify=verify,
107108
algorithms=self.ALGORITHMS,
108-
**kwargs
109+
**kwargs,
109110
)
110111

111112

112-
if __name__ == '__main__':
113+
if __name__ == "__main__":
113114
from jwt_rsa.rsa import generate_rsa
114115

115116
key, public = generate_rsa(2048)
@@ -118,5 +119,5 @@ def decode(
118119

119120
token = jwt.encode()
120121

121-
print('Token', token)
122-
print('Content', jwt.decode(token))
122+
print("Token", token)
123+
print("Content", jwt.decode(token))

jwt_rsa/verify.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import json
2-
import sys
3-
import os
42
import logging
3+
import os
4+
import sys
55

66
from cryptography.hazmat.primitives import hashes
77
from cryptography.hazmat.primitives.asymmetric import padding
8+
89
from jwt_rsa.rsa import load_private_key, load_public_key
910

1011

@@ -14,18 +15,18 @@ def main() -> None:
1415
logging.info("Awaiting JSON on stdin...")
1516
data = json.load(sys.stdin)
1617

17-
public_key = load_public_key(data['public'])
18-
private_key = load_private_key(data['private'])
18+
public_key = load_public_key(data["public"])
19+
private_key = load_private_key(data["private"])
1920

2021
payload = os.urandom(1024 * 16)
2122

2223
signature = private_key.sign(
2324
payload,
2425
padding.PSS(
2526
mgf=padding.MGF1(hashes.SHA256()),
26-
salt_length=padding.PSS.MAX_LENGTH
27+
salt_length=padding.PSS.MAX_LENGTH,
2728
),
28-
hashes.SHA256()
29+
hashes.SHA256(),
2930
)
3031

3132
logging.info("Signing OK")
@@ -35,15 +36,15 @@ def main() -> None:
3536
payload,
3637
padding.PSS(
3738
mgf=padding.MGF1(hashes.SHA256()),
38-
salt_length=padding.PSS.MAX_LENGTH
39+
salt_length=padding.PSS.MAX_LENGTH,
3940
),
40-
hashes.SHA256()
41+
hashes.SHA256(),
4142
)
4243

4344
assert result is None
4445

4546
logging.info("Verifying OK")
4647

4748

48-
if __name__ == '__main__':
49+
if __name__ == "__main__":
4950
main()

0 commit comments

Comments
 (0)