Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throw an error on invalid base64 strings #28

Merged
merged 1 commit into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/joserfc/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import Any
import base64
import struct
import binascii
import json


Expand All @@ -26,8 +27,10 @@ def json_dumps(data: Any, ensure_ascii: bool = False) -> str:


def urlsafe_b64decode(s: bytes) -> bytes:
if b"+" in s or b"/" in s:
raise binascii.Error
s += b"=" * (-len(s) % 4)
return base64.urlsafe_b64decode(s)
return base64.b64decode(s, b"-_", validate=True)


def urlsafe_b64encode(s: bytes) -> bytes:
Expand Down
10 changes: 9 additions & 1 deletion tests/test_util.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from unittest import TestCase
from joserfc import util

import binascii

class TestUtil(TestCase):
def test_to_bytes(self):
Expand All @@ -22,3 +22,11 @@ def test_int_to_base64(self):

def test_json_b64encode(self):
self.assertEqual(util.json_b64encode("{}"), b"e30")

def test_urlsafe_b64decode(self):
self.assertEqual(util.urlsafe_b64decode(b'_foo123-'), b'\xfd\xfa(\xd7m\xfe')
self.assertRaises(
binascii.Error,
util.urlsafe_b64decode,
b'+foo123/'
)
Loading