Skip to content

Commit 3195e6e

Browse files
authored
Merge pull request #60 from web-push-libs/feat/59
feat: add new class method to suss out key from string
2 parents 26d2465 + 37d825f commit 3195e6e

File tree

4 files changed

+25
-3
lines changed

4 files changed

+25
-3
lines changed

python/py_vapid/__init__.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,22 @@ def from_file(cls, private_key_file=None):
125125
logging.error("Could not open private key file: %s", repr(exc))
126126
raise VapidException(exc)
127127

128+
@classmethod
129+
def from_string(cls, private_key):
130+
"""Initialize VAPID using a string containing the private key. This
131+
will try to determine if the key is in RAW or DER format.
132+
133+
:param private_key: String containing the key info
134+
:type private_key: str
135+
136+
"""
137+
138+
pkey = private_key.encode().replace(b"\n", b"")
139+
key = b64urldecode(pkey)
140+
if len(key) == 32:
141+
return cls.from_raw(pkey)
142+
return cls.from_der(pkey)
143+
128144
@classmethod
129145
def verify(cls, key, auth):
130146
"""Verify a VAPID authorization token.

python/py_vapid/tests/test_vapid.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,14 @@ def test_from_raw(self):
122122
v = Vapid01.from_raw(T_RAW)
123123
self.check_keys(v)
124124

125+
def test_from_string(self):
126+
v1 = Vapid01.from_string(T_DER)
127+
v2 = Vapid01.from_string(T_RAW.decode())
128+
self.check_keys(v1)
129+
self.check_keys(v2)
130+
125131
def test_sign_01(self):
126-
v = Vapid01.from_file("/tmp/private")
132+
v = Vapid01.from_string(T_DER)
127133
claims = {"aud": "https://example.com",
128134
"sub": "mailto:[email protected]"}
129135
result = v.sign(claims, "id=previous")

python/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
ecdsa==0.13
2-
cryptography>=1.8.2,<=2.0.3
2+
cryptography>=1.8.2

python/setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
from setuptools import setup, find_packages
55

6-
__version__ = "1.2.6"
6+
__version__ = "1.3.0"
77

88

99
def read_from(file):

0 commit comments

Comments
 (0)