python implementation of JSON Web Signatures

Overview

python-jws

🚨 This is Unmaintained 🚨

This library is unmaintained and you should probably use https://github.com/latchset/jwcrypto instead.

For historical purposes, here are the docs

A Python implementation of JSON Web Signatures draft 02

Also now works on Python 3.3+ as well as Python 2.7+. However, it's a naive conversion to support both Python 2 and Python 3 so there may well be hidden bugs.

Installing

$ pip install jws

Algorithms

The JWS spec reserves several algorithms for cryptographic signing. Out of the 9, this library currently supports 7:

HMAC – native

  • HS256 – HMAC using SHA-256 hash algorithm
  • HS384 – HMAC using SHA-384 hash algorithm
  • HS512 – HMAC using SHA-512 hash algorithm

RSA – requires pycrypto >= 2.5: pip install pycrypto

  • RS256 – RSA using SHA-256 hash algorithm

ECDSA – requires ecdsa lib: pip install ecdsa

  • ES256 – ECDSA using P-256 curve and SHA-256 hash algorithm
  • ES384 – ECDSA using P-384 curve and SHA-384 hash algorithm
  • ES512 – ECDSA using P-521 curve and SHA-512 hash algorithm

There is also a mechanism for extending functionality by adding your own algorithms without cracking open the whole codebase. See the advanced usage section for an example.

For RSA and ECDSA, all crypto libraries are lazily loaded so you won't need the dependencies unless you try to use the functionality.

Usage

Let's check out some examples.

>>> import jws
>>> header  = { 'alg': 'HS256' }
>>> payload = { 'claim': 'JSON is the raddest.', 'iss': 'brianb' }
>>> signature = jws.sign(header, payload, 'secret')
>>> jws.verify(header, payload, signature, 'secret')
True
>>> jws.verify(header, payload, signature, 'badbadbad')
Traceback (most recent call last):
...
jws.exceptions.SignatureError: Could not validate signature

Now with a real key!

>>> import ecdsa
>>> sk256 = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
>>> vk = sk256.get_verifying_key()
>>> header = { 'alg': 'ES256' }
>>> sig = jws.sign(header, payload, sk256)
>>> jws.verify(header, payload, sig, vk)
True

Advanced Usage

Make this file

# file: sillycrypto.py
import jws
from jws.algos import AlgorithmBase, SignatureError
class FXUY(AlgorithmBase):
    def __init__(self, x, y):
        self.x = int(x)
        self.y = int(y)
    def sign(self, msg, key):
        return 'verysecure' * self.x + key * self.y

    def verify(self, msg, sig, key):
        if sig != self.sign(msg, key):
            raise SignatureError('nope')
        return True

jws.algos.CUSTOM += [
   # a regular expression with two named matching groups. (x and y)
    # named groups will be sent to the class constructor
    (r'^F(?P
   
    \d)U(?P
    
     \d{2})$',  FXUY),
]

    
   

And in an interpreter:

>> >>> import sillycrypto >>> sig = jws.sign(header, payload, ' ') >>> jws.verify(header, payload, sig, ' ') True >>> jws.verify(header, payload, sig, 'y u no verify?') Traceback (most recent call last): .... jws.exceptions.SignatureError: nope">
>>> import jws
>>> header = { 'alg': 'F7U12' }
>>> payload = { 'claim': 'wutt' }
>>> sig = jws.sign(header, payload, '
     
      ')
Traceback (most recent call last):
  ....
jws.exceptions.AlgorithmNotImplemented: "F7U12" not implemented.
>>>
>>> import sillycrypto
>>> sig = jws.sign(header, payload, '
      
       ')
>>> jws.verify(header, payload, sig, '
       
        ')
True
>>> jws.verify(header, payload, sig, 'y u no verify?')
Traceback (most recent call last):
....
jws.exceptions.SignatureError: nope

       
      
     

Other Stuff

Check out https://github.com/brianloveswords/python-jws/blob/master/examples/minijwt.py for a 14-line implemention of JWT.

See https://github.com/brianloveswords/python-jws/blob/master/examples/ragecrypto.py for a rage-comic inspired cryptography extension.

TODO

  • Write about all the rad stuff that can be done around headers (as extensible as crypto algos)
  • Pull in JWK support

Tests

use nosetests

License

MIT

Comments
  • Verify the input JSON, don't re-gen it

    Verify the input JSON, don't re-gen it

    Python dict keys are in an undefined order, which means json.dumps() doesn't reliably produce the same string. So in JWT, it's best to verify the input JSON, rather than decoding it, re-encoding it, and verifying it. Otherwise you get spurious verification failures.

    opened by tgs 4
  • Add support for PS256, PS384 and PS512 algorithms

    Add support for PS256, PS384 and PS512 algorithms

    (see http://self-issued.info/docs/draft-ietf-jose-json-web-algorithms-11.html#DefiningPSS)

    Using salt len = hash len as per http://www.ietf.org/mail-archive/web/jose/current/msg02901.html Tests added but I've not touched the README

    opened by davedoesdev 4
  • ASCII Readme

    ASCII Readme

    Currently setup.py pulls in the long description from the README.md: (long_description=read('README.md')

    Sadly, because you have unicode emdashes ("\xe2\x80\x93" instead of "--") in the readme.md python will fail trying to stringify those characters and error with:

    Collecting jws>=0.1.3 (from python_jwt==1.1.0->-r /tmp/tmpEbDt97/requirements.txt (line 27))
      Downloading jws-0.1.3.tar.gz
        Complete output from command python setup.py egg_info:
        Traceback (most recent call last):
          File "<string>", line 1, in <module>
          File "/tmp/pip-build-db5dsmc7/jws/setup.py", line 17, in <module>
            long_description=read('README.md'),
          File "/tmp/pip-build-db5dsmc7/jws/setup.py", line 5, in read
            return open(os.path.join(os.path.dirname(__file__), fname)).read()
          File "/venv3/lib/python3.5/encodings/ascii.py", line 26, in decode
            return codecs.ascii_decode(input, self.errors)[0]
        UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 500: ordinal not in range(128)
    

    To reproduce, under Python 3.5 run: LC_CTYPE=C pip3 install jws

    This fixes this, but it would require a subsequent point release (0.1.4) to actually to keep it from happening on future pip installs.

    opened by notpeter 2
  • Fix TypeError with format string

    Fix TypeError with format string

    The '%s.%s.%s' was giving me a 'not enough arguments for format string' TypeError, so I switched it to use string join instead. It would be equally good to use a tuple instead of a list for the list of format parameters.

    opened by tgs 1
  • Special pycrypto is no longer required if using pycrypto >= 2.5.

    Special pycrypto is no longer required if using pycrypto >= 2.5.

    The special notices and submodule reference regarding pycrypto for RSA are no longer required.

    • As of 2.5, pycrypto supports PKCS #1.5
    • As of 2.4, pycrypto supports SHA384 & SHA512.
    opened by mark-adams 1
  • Add to Python Package Index

    Add to Python Package Index

    I'd like to try your software, but couldn't find it in the python package index at http://pypi.python.org/ — could you submit it there ?

    You probably want to change name = "python-jws" in setup.py to "jws" (still available!) or "json-web-signatures" before submitting, because the "python-" prefix is kind of redundant on PyPI.

    opened by peritus 1
  • Add possibility to sign and verify JSON strings directly

    Add possibility to sign and verify JSON strings directly

    Problem

    Imagine the following:

    • Sign some data on a smartphone, using smartphone libraries
    • Trying to verify that in python-jws, we first need to parse the JSON and python-jws will re-convert the generated object to JSON in its verification process. But if the re-conversion does not format the JSON in exactly the same way as the library on the smartphone did (i.e. the way it was in the payload), verification fails. But the signature was good!

    Solution

    Add the possibility to verify a signature on a json string, not only python objects.

    opened by wehlutyk 1
  • Fixes error when attempting to install with Python 3.5.

    Fixes error when attempting to install with Python 3.5.

    # pip install jws
    Collecting jws
      Downloading jws-0.1.3.tar.gz
        Complete output from command python setup.py egg_info:
        Traceback (most recent call last):
          File "<string>", line 20, in <module>
          File "/tmp/pip-build-4smf5vyz/jws/setup.py", line 17, in <module>
            long_description=read('README.md'),
          File "/tmp/pip-build-4smf5vyz/jws/setup.py", line 5, in read
            return open(os.path.join(os.path.dirname(__file__), fname)).read()
          File "/opt/venv/lib/python3.5/encodings/ascii.py", line 26, in decode
            return codecs.ascii_decode(input, self.errors)[0]
        UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 500: ordinal not in range(128)
    
    opened by saebyn 0
  • Changes to allow python-jws to work on Python 3.3

    Changes to allow python-jws to work on Python 3.3

    I've tested it on Python 2.7.x and Python 3.3+. I did the changes so I could use python-jwt but in the end I went with PyJWT instead. However, since I did the changes, I thought I'd offer them up to you if you'd like them included.

    opened by ajkavanagh 0
  • docs: fix simple typo, implemention -> implementation

    docs: fix simple typo, implemention -> implementation

    There is a small typo in README.md.

    Should read implementation rather than implemention.

    Semi-automated pull request generated by https://github.com/timgates42/meticulous/blob/master/docs/NOTE.md

    opened by timgates42 0
  • Cannot install in windows

    Cannot install in windows

    While I tried to install this package via 'pip install jws' in Windows 10 (python 3.7), 'UnicodeDecodeError: 'cp949' codec can't decode byte 0xe2 in position 500: illegal multibyte sequence' occured. I end up modifying 'setup.py' file (add parameter "encoding='UTF8'" in open function in line 5).

    opened by therealnlee 3
  • parser failed wth

    parser failed wth "ParameterNotUnderstood: Could not find an action for Header Parameter 'ppt''"

    payload ={"alg":"ES256","typ":"passport","ppt":"shaken","x5u":"https://wiresharkserver.mtimslab.atttest.com/vesper/dig-sig.crt"} payload ={} header = {"alg":"ES256","typ":"passport","ppt":"shaken","x5u":"https://wiresharkserver.mtimslab.atttest.com/vesper/dig-sig.crt"} payload = {"attest":"A","dest":{"tn":["+12249587065"]},"iat":1504163217,"orig":{"tn":"+12249587035"},"origid":"6cf14ce7-5c58-403c-8982-07f11b8680d5"} signature = jws.sign(header, payload, 'secret') Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/site-packages/jws/init.py", line 23, in sign header.process(data, 'sign') File "/usr/lib/python2.7/site-packages/jws/header.py", line 67, in process instance = cls(param, data['header'][param], data) File "/usr/lib/python2.7/site-packages/jws/header.py", line 10, in init self.value = self.clean(value) File "/usr/lib/python2.7/site-packages/jws/header.py", line 30, in clean raise ParameterNotUnderstood("Could not find an action for Header Parameter '%s'" % self.name) jws.exceptions.ParameterNotUnderstood: Could not find an action for Header Parameter 'ppt'

    opened by veluvarti835 1
  • Doesn't work with pycryptodome

    Doesn't work with pycryptodome

    pycrypto is dead. pycryptodome is a drop-in replacement. However, python-jws uses a private member (_RSAobj) of pycrypto:

    https://github.com/brianloveswords/python-jws/blob/master/jws/algos.py#L87

    which pycryptodome doesn't have.

    But pycryptodome does have the RsaKey member in the same place.

    So a change something like https://github.com/mpdavis/python-jose/pull/8/files#diff-f5aa2743c17dabc292333673fe591c30R20 is required where the presence of each member is checked for.

    opened by davedoesdev 0
Owner
Brian J Brennan
professional computers user
Brian J Brennan
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Simple JWT 3.3k Jan 1, 2023
JSON Web Token Authentication support for Django REST Framework

REST framework JWT Auth Notice This project is currently unmaintained. Check #484 for more details and suggested alternatives. JSON Web Token Authenti

José Padilla 3.2k Dec 31, 2022
JSON Web Token Authentication support for Django REST Framework

REST framework JWT Auth JSON Web Token Authentication support for Django REST Framework Overview This package provides JSON Web Token Authentication s

Styria Digital Development 178 Jan 2, 2023
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.2k Dec 29, 2022
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.2k Dec 28, 2022
CheckList-Api - Created with django rest framework and JWT(Json Web Tokens for Authentication)

CheckList Api created with django rest framework and JWT(Json Web Tokens for Aut

shantanu nimkar 1 Jan 24, 2022
This app makes it extremely easy to build Django powered SPA's (Single Page App) or Mobile apps exposing all registration and authentication related functionality as CBV's (Class Base View) and REST (JSON)

Welcome to django-rest-auth Repository is unmaintained at the moment (on pause). More info can be found on this issue page: https://github.com/Tivix/d

Tivix 2.4k Jan 3, 2023
A full Rest-API With Oauth2 and JWT for request & response a JSON file Using FastAPI and SQLAlchemy 🔑

Pexon-Rest-API A full Rest-API for request & response a JSON file, Building a Simple WorkFlow that help you to Request a JSON File Format and Handling

Yasser Tahiri 15 Jul 22, 2022
Simple yet powerful authorization / authentication client library for Python web applications.

Authomatic Authomatic is a framework agnostic library for Python web applications with a minimalistic but powerful interface which simplifies authenti

null 1k Dec 28, 2022
Simple yet powerful authorization / authentication client library for Python web applications.

Authomatic Authomatic is a framework agnostic library for Python web applications with a minimalistic but powerful interface which simplifies authenti

null 962 Feb 4, 2021
Simple yet powerful authorization / authentication client library for Python web applications.

Authomatic Authomatic is a framework agnostic library for Python web applications with a minimalistic but powerful interface which simplifies authenti

null 962 Feb 19, 2021
Simplifying third-party authentication for web applications.

Velruse is a set of authentication routines that provide a unified way to have a website user authenticate to a variety of different identity provider

Ben Bangert 253 Nov 14, 2022
Web authentication testing framework

What is this This is a framework designed to test authentication for web applications. While web proxies like ZAProxy and Burpsuite allow authenticate

OWASP 88 Jan 1, 2023
Django-react-firebase-auth - A web app showcasing OAuth2.0 + OpenID Connect using Firebase, Django-Rest-Framework and React

Demo app to show Django Rest Framework working with Firebase for authentication

Teshank Raut 6 Oct 13, 2022
A JOSE implementation in Python

python-jose A JOSE implementation in Python Docs are available on ReadTheDocs. The JavaScript Object Signing and Encryption (JOSE) technologies - JSON

Michael Davis 1.2k Dec 28, 2022
A generic, spec-compliant, thorough implementation of the OAuth request-signing logic

OAuthLib - Python Framework for OAuth1 & OAuth2 *A generic, spec-compliant, thorough implementation of the OAuth request-signing logic for Python 3.5+

OAuthlib 2.5k Jan 2, 2023
Implementation of Supervised Contrastive Learning with AMP, EMA, SWA, and many other tricks

SupCon-Framework The repo is an implementation of Supervised Contrastive Learning. It's based on another implementation, but with several differencies

Ivan Panshin 132 Dec 14, 2022
A generic, spec-compliant, thorough implementation of the OAuth request-signing logic

OAuthLib - Python Framework for OAuth1 & OAuth2 *A generic, spec-compliant, thorough implementation of the OAuth request-signing logic for Python 3.5+

OAuthlib 2.5k Jan 1, 2023
REST implementation of Django authentication system.

djoser REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such

Sunscrapers 2.2k Jan 1, 2023