Skip to content

Commit 5916513

Browse files
author
Kit Cambridge
committed
Add Vapid.from_raw. Closes #35.
1 parent 987cc34 commit 5916513

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

python/py_vapid/__init__.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@
1616
VERSION = "VAPID-DRAFT-02/ECE-DRAFT-07"
1717

1818

19+
def b64urldecode(data):
20+
return base64.urlsafe_b64decode(data + "===="[:len(data) % 4])
21+
22+
1923
class VapidException(Exception):
2024
"""An exception wrapper for Vapid."""
2125
pass
@@ -42,6 +46,13 @@ def __init__(self, private_key=None):
4246
"""
4347
self.private_key = private_key
4448

49+
@classmethod
50+
def from_raw(cls, private_key):
51+
key = ecdsa.SigningKey.from_string(b64urldecode(private_key),
52+
curve=cls._curve,
53+
hashfunc=cls._hasher)
54+
return cls(key)
55+
4556
@classmethod
4657
def from_pem(cls, private_key):
4758
"""Initialize VAPID using a private key in PEM format.

python/py_vapid/tests/test_vapid.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@
2121
T_PRIVATE = ("-----BEGIN EC PRIVATE KEY-----{}"
2222
"-----END EC PRIVATE KEY-----\n").format(T_DER)
2323

24+
# This is the same private key, as a point in uncompressed form. This should
25+
# be Base64url-encoded without padding.
26+
T_RAW = """
27+
943WICKkdu3z78pnY0gXw143biOoCacwsVkQyhxjxFs
28+
"""
29+
2430
# This is a public key in PEM form.
2531
T_PUBLIC = """-----BEGIN PUBLIC KEY-----
2632
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEJwJZq/GN8jJbo1GGpyU70hmP2hb
@@ -104,6 +110,11 @@ def test_same_public_key(self):
104110
v.save_public_key("/tmp/p2")
105111
os.unlink("/tmp/p2")
106112

113+
def test_from_raw(self):
114+
v = Vapid01.from_raw(T_RAW)
115+
eq_(v.private_key.to_pem(), T_PRIVATE.encode('utf8'))
116+
eq_(v.public_key.to_pem(), T_PUBLIC.encode('utf8'))
117+
107118
def test_validate(self):
108119
v = Vapid01.from_file("/tmp/private")
109120
msg = "foobar".encode('utf8')

0 commit comments

Comments
 (0)