Skip to content

Commit 0cfb77d

Browse files
committed
add rough public key parser
1 parent b912756 commit 0cfb77d

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

tlslite/utils/python_key.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,39 @@ def parsePEM(s, passwordCallback=None):
3333
elif pemSniff(s, "EC PRIVATE KEY"):
3434
bytes = dePem(s, "EC PRIVATE KEY")
3535
return Python_Key._parse_ecc_ssleay(bytes)
36+
elif pemSniff(s, "PUBLIC KEY"):
37+
bytes = dePem(s, "PUBLIC KEY")
38+
return Python_Key._parse_public_key(bytes)
3639
else:
3740
raise SyntaxError("Not a PEM private key file")
3841

42+
@staticmethod
43+
def _parse_public_key(bytes):
44+
# public keys are encoded as the subject_public_key_info objects
45+
spk_info = ASN1Parser(bytes)
46+
47+
# first element of the SEQUENCE is the AlgorithmIdentifier
48+
alg_id = spk_info.getChild(0)
49+
50+
# AlgId has two elements, the OID of the algorithm and parameters
51+
# parameters generally have to be NULL, with exception of RSA-PSS
52+
53+
alg_oid = alg_id.getChild(0)
54+
55+
if list(alg_oid.value) != [42, 134, 72, 134, 247, 13, 1, 1, 1]:
56+
raise SyntaxError("Only RSA Public keys supported")
57+
58+
subject_public_key = ASN1Parser(
59+
ASN1Parser(spk_info.getChildBytes(1)).value[1:])
60+
61+
modulus = subject_public_key.getChild(0)
62+
exponent = subject_public_key.getChild(1)
63+
64+
n = bytesToNumber(modulus.value)
65+
e = bytesToNumber(exponent.value)
66+
67+
return Python_RSAKey(n, e, key_type="rsa")
68+
3969
@staticmethod
4070
def _parse_pkcs8(bytes):
4171
parser = ASN1Parser(bytes)

0 commit comments

Comments
 (0)