-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkeyvalidator
More file actions
executable file
·76 lines (66 loc) · 2.27 KB
/
keyvalidator
File metadata and controls
executable file
·76 lines (66 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/python3
import argparse
import os
import cryptography
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa
from cryptography.hazmat.primitives.serialization import load_pem_private_key
# False: Key valid, True: Key invalid, None: Key not checkable
def checkkeyobj(priv):
if isinstance(priv, rsa.RSAPrivateKey):
# checked on import so ok
return False
if isinstance(priv, (ec.EllipticCurvePrivateKey, dsa.DSAPrivateKey)):
if isinstance(priv, ec.EllipticCurvePrivateKey):
alg = ec.ECDSA(hashes.SHA256())
else:
alg = hashes.SHA256()
try:
sig = priv.sign(b"2u_Yg7", alg)
pubkey = priv.public_key()
except ValueError:
return True
try:
pubkey.verify(sig, b"2u_Yg7", alg)
except cryptography.exceptions.InvalidSignature:
return True
return False
return None
def checkkeyfile(fp, quiet=False):
with open(fp, "rb") as f:
d = f.read()
try:
key = load_pem_private_key(d, password=None)
except ValueError as e:
if str(e) == "Invalid private key":
print(f"{fp} looks like invalid RSA key")
elif "Could not deserialize key data" in str(e):
print(f"{fp} does not contain parsable key")
else:
print(f"Unexpected error ({fp}): {e}")
return
except TypeError:
# password-protected key
return
except cryptography.exceptions.UnsupportedAlgorithm:
# e.g. unsupported elliptic curve
return
r = checkkeyobj(key)
kn = type(key).__name__.removesuffix("PrivateKey")
if r:
print(f"{kn} invalid {fp}")
elif r is None and not quiet:
print(f"{kn} cannot be checked {fp}")
elif r is False and not quiet:
print(f"{kn} ok {fp}")
ap = argparse.ArgumentParser()
ap.add_argument("input", nargs="+", help="dir or files")
ap.add_argument("-q", "--quiet", action="store_true")
args = ap.parse_args()
for f in args.input:
if os.path.isdir(f):
for root, _, files in os.walk(f):
for fn in files:
checkkeyfile(os.path.join(root, fn), args.quiet)
else:
checkkeyfile(f, args.quiet)