Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
dajiaji committed Apr 17, 2021
1 parent 388ca34 commit 93d5086
Show file tree
Hide file tree
Showing 23 changed files with 1,651 additions and 2 deletions.
36 changes: 36 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
repos:
- repo: https://github.com/psf/black
rev: 20.8b1
hooks:
- id: black
args: ["--target-version=py36"]

- repo: https://github.com/asottile/blacken-docs
rev: v1.10.0
hooks:
- id: blacken-docs
args: ["--target-version=py36"]

- repo: https://github.com/PyCQA/flake8
rev: 3.9.0
hooks:
- id: flake8
language_version: python3.8

- repo: https://github.com/PyCQA/isort
rev: 5.8.0
hooks:
- id: isort

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: debug-statements

- repo: https://github.com/mgedmin/check-manifest
rev: "0.46"
hooks:
- id: check-manifest
args: [--no-build-isolation]
Empty file added CHANGES.rst
Empty file.
46 changes: 46 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at ajitomi@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [https://www.contributor-covenant.org/version/1/4/code-of-conduct.html][version]

[homepage]: https://www.contributor-covenant.org/
[version]: https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
8 changes: 8 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
include CHANGES.rst
include LICENSE
include tox.ini
graft docs
prune docs/_build
graft tests
global-exclude *.py[co]
recursive-exclude * __pycache__
118 changes: 116 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,116 @@
# python-cwt
A Python implementation of CWT/COSE.
# Python CWT

A Python (>= 3.6) implementation of CBOR Web Token (CWT) and CBOR Object Signing and Encryption (COSE) compliant with:
- [RFC8392: CBOR Web Token (CWT)](https://tools.ietf.org/html/rfc8392)
- [RFC8152: CBOR Object Signing and Encryption (COSE)](https://tools.ietf.org/html/rfc8152)

## Installing

Install with pip after cloning this repository.

```
pip install .
```

## Usase

Python CWT is easy to use.
If you already know about [JSON Web Token (JWT)](https://tools.ietf.org/html/rfc7519),
little knowledge of [CBOR](https://tools.ietf.org/html/rfc7049), [COSE](https://tools.ietf.org/html/rfc8152)
and [CWT](https://tools.ietf.org/html/rfc8392) is required to use this library.

Followings are basic examples which create CWT, verify and decode it:

- [MACed CWT](#maced-cwt)
- [Signed CWT](#signed-cwt)
- [Encrypted CWT](#encrypted-cwt)
- [Nested CWT](#nested-cwt)

### MACed CWT

Create a MACed CWT, verify and decode it as follows:

```py
import cwt
from cwt import cose_key, claims

key = cose_key.from_symmetric_key("mysecretpassword") # "HMAC256/256" is the default algorithm.
encoded = cwt.encode_and_mac(claims.from_json({"iss":"https://as.example", "sub":"dajiaji", "cti":"123"}), key)
decoded = cwt.decode(encoded, key)
```

CBOR-like structure (Dict[int, Any]) can be used as follows:

```py
import cwt

key = cwt.cose_key.from_symmetric_key("mysecretpassword")
encoded = cwt.encode_and_mac({1:"https://as.example", 2:"dajiaji", 7:b"123"}, key)
decoded = cwt.decode(encoded, key)
```

### Signed CWT

Create an ECDSA (with SHA-256) key pair:

```sh
$ openssl ecparam -genkey -name prime256v1 -noout -out private_key.pem
$ openssl ec -in private_key.pem -pubout -out public_key.pem
```

Create a Signed CWT, verify and decode it with the key pair as follows:

```py
import cwt
from cwt import cose_key, claims

# Load PEM-formatted keys as COSE keys.
with open("./private_key.pem") as key_file:
private_key = cose_key.from_pem(key_file.read())
with open("./public_key.pem") as key_file:
public_key = cose_key.from_pem(key_file.read())

# Encode with ES256 signing.
encoded = cwt.encode_and_sign(
claims.from_json({"iss":"https://as.example", "sub":"dajiaji", "cti":"123"}), private_key)

# Verify and decode.
decoded = cwt.decode(encoded, public_key)
```

### Encrypted CWT

Create an Ed25519 key pair:

```sh
$ openssl genpkey -algorithm ed25519 -out private_key.pem
$ openssl pkey -in private_key.pem -pubout -out public_key.pem
```

Create an Encrypted CWT, verify and decode it with the key pair as follows:

```py
import cwt
from cwt import cose_key, claims

# Load PEM-formatted keys as COSE keys.
with open("./private_key.pem") as key_file:
private_key = cose_key.from_pem(key_file.read())
with open("./public_key.pem") as key_file:
public_key = cose_key.from_pem(key_file.read())

# Encode with ES256 encryption.
encoded = cwt.encode_and_encrypt(
claims.from_json({"iss":"https://as.example", "sub":"dajiaji", "cti":"123"}), private_key)

# Verify and decode.
decoded = cwt.decode(encoded, public_key)
```

## Tests

You can run tests from the project root after cloning with:

```sh
$ tox
```
31 changes: 31 additions & 0 deletions cwt/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from .claims import Claims, claims
from .cose import COSE
from .cwt import CWT, decode, encode_and_encrypt, encode_and_mac, encode_and_sign
from .exceptions import PyCWTDecodeError, PyCWTEncodeError, PyCWTError
from .key_builder import KeyBuilder, cose_key

__version__ = "0.1.0"
__title__ = "Python CWT"
__description__ = "A Python implementation of CWT/COSE"
__url__ = "https://python-cwt.readthedocs.io"
__uri__ = __url__
__doc__ = __description__ + " <" + __uri__ + ">"
__author__ = "AJITOMI Daisuke"
__email__ = "ajitomi@gmail.com"
__license__ = "MIT"
__copyright__ = "Copyright 2021 AJITOMI Daisuke"
__all__ = [
"CWT",
"encode_and_mac",
"encode_and_sign",
"encode_and_encrypt",
"decode",
"COSE",
"KeyBuilder",
"cose_key",
"Claims",
"claims",
"PyCWTError",
"PyCWTEncodeError",
"PyCWTDecodeError",
]
49 changes: 49 additions & 0 deletions cwt/claims.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import json
from typing import Any, Dict, Optional, Union


class Claims:
""""""

REGISTERED_NAMES = {
"iss": 1, # text string
"sub": 2, # text string
"aud": 3, # text string
"exp": 4, # integer or floating-point number
"nbf": 5, # integer or floating-point number
"iat": 6, # integer or floating-point number
"cti": 7, # byte string
}

def __init__(self, options: Optional[Dict[str, Any]] = None):
""""""
self._options = options
return

def from_json(self, claims: Union[str, bytes, Dict[str, Any]]) -> Dict[int, Any]:
""""""
json_claims: Dict[str, Any]
if isinstance(claims, str) or isinstance(claims, bytes):
json_claims = json.loads(claims)
else:
json_claims = claims

for k in json_claims:
if not isinstance(k, int):
break
ValueError("It is already CBOR-like format.")

# Convert JSON to CBOR (Convert the type of key from str to int).
cbor_claims = {}
for k, v in json_claims.items():
if k not in Claims.REGISTERED_NAMES:
# TODO Support additional arguments.
continue
cbor_claims[Claims.REGISTERED_NAMES[k]] = v
if 7 in cbor_claims and isinstance(cbor_claims[7], str):
cbor_claims[7] = cbor_claims[7].encode("utf-8")
return cbor_claims


# export
claims = Claims()
32 changes: 32 additions & 0 deletions cwt/const.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
COSE_KEY_TYPES = {
"OKP": 1, # OCtet Key Pair
"EC2": 2, # Elliptic Curve Keys w/ x- and y-coordinate pair
"RSA": 3, # RSA Key
"Symmetric": 4, # Symmetric Keys
"HSS-LMS": 5, # Public key for HSS/LMS hash-based digital signature
"WalnutDSA": 6, # WalnutDSA public key
}

# COSE Algorithms for Content Encryption Key (CEK).
COSE_ALGORITHMS_CEK = {
"A128GCM": 1, # AES-GCM mode w/ 128-bit key, 128-bit tag
"A192GCM": 2, # AES-GCM mode w/ 192-bit key, 128-bit tag
"A256GCM": 3, # AES-GCM mode w/ 256-bit key, 128-bit tag
# etc.
}

# COSE Algorithms for MAC.
COSE_ALGORITHMS_MAC = {
"HMAC256/64": 4, # HMAC w/ SHA-256 truncated to 64 bits
"HMAC256/256": 5, # HMAC w/ SHA-256
"HMAC384/384": 6, # HMAC w/ SHA-384
"HMAC512/512": 7, # HMAC w/ SHA-512
"AES-MAC128/64": 14, # AES-MAC 128-bit key, 64-bit tag
"AES-MAC256/64": 15, # AES-MAC 256-bit key, 64-bit tag
"AES-MAC128/128": 25, # AES-MAC 128-bit key, 128-bit tag
"AES-MAC256/128": 26, # AES-MAC 256-bit key, 128-bit tag
# etc.
}

# COSE Algorithms for Symmetric Keys.
COSE_ALGORITHMS_SYMMETRIC = dict(COSE_ALGORITHMS_MAC, **COSE_ALGORITHMS_CEK)
Loading

0 comments on commit 93d5086

Please sign in to comment.