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

JWE Support #1

Merged
merged 5 commits into from
Aug 15, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
47 changes: 47 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: build

on:
push:
branches:
- main
pull_request:
types: [opened, synchronize, reopened]

jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- uses: reviewdog/action-staticcheck@v1
with:
github_token: ${{ secrets.github_token }}
reporter: github-pr-review
filter_mode: nofilter
fail_on_error: true

build:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
go: [1.16, 1.17, 1.18]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Go
uses: actions/setup-go@v3
with:
go-version: "${{ matrix.go }}"
- name: Check Go code formatting
run: |
if [ "$(gofmt -s -l . | wc -l)" -gt 0 ]; then
gofmt -s -l .
echo "Please format Go code by running: go fmt ./..."
exit 1
fi
- name: Build
run: |
go vet ./...
go test -v ./...
go build ./...
71 changes: 71 additions & 0 deletions .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"

on:
push:
branches: [ main ]
# pull_request:
# The branches below must be a subset of the branches above
# branches: [ main ]
schedule:
- cron: '31 10 * * 5'

jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write

strategy:
fail-fast: false
matrix:
language: [ 'go' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
# Learn more:
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed

steps:
- name: Checkout repository
uses: actions/checkout@v2

# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main

# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1

# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl

# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language

#- run: |
# make bootstrap
# make release

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.DS_Store
bin
.idea/

9 changes: 9 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Copyright (c) 2012 Dave Grijalva
oxisto marked this conversation as resolved.
Show resolved Hide resolved
Copyright (c) 2021 golang-jwt maintainers

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

92 changes: 92 additions & 0 deletions aesgcm.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package jwe

import (
"crypto/aes"
"crypto/cipher"
"errors"
"io"
)

var (
ErrInvalidKeySize = errors.New("invalid key size")
ErrInvalidTagSize = errors.New("invalid tag size")
ErrInvalidNonceSize = errors.New("invalid nonce size")
ErrUnsupportedEncryptionType = errors.New("unsupported encryption type")
)

const TagSizeAESGCM = 16

type EncryptionType string

var EncryptionTypeA256GCM = EncryptionType("A256GCM")

type cipherAESGCM struct {
keySize int
getAEAD func(key []byte) (cipher.AEAD, error)
}

func (ci cipherAESGCM) encrypt(key, aad, plaintext []byte) (iv []byte, ciphertext []byte, tag []byte, err error) {
if len(key) != ci.keySize {
return nil, nil, nil, ErrInvalidKeySize
}

aead, err := ci.getAEAD(key)
if err != nil {
return nil, nil, nil, err
}

iv = make([]byte, aead.NonceSize())
_, err = io.ReadFull(RandReader, iv)
if err != nil {
return nil, nil, nil, err
}

res := aead.Seal(nil, iv, plaintext, aad)
tagIndex := len(res) - TagSizeAESGCM

return iv, res[:tagIndex], res[tagIndex:], nil
}

func (ci cipherAESGCM) decrypt(key, aad, iv []byte, ciphertext []byte, tag []byte) ([]byte, error) {
if len(key) != ci.keySize {
return nil, ErrInvalidKeySize
}

if len(tag) != TagSizeAESGCM {
return nil, ErrInvalidTagSize
}

aead, err := ci.getAEAD(key)
if err != nil {
return nil, err
}

if len(iv) != aead.NonceSize() {
return nil, ErrInvalidNonceSize
}

return aead.Open(nil, iv, append(ciphertext, tag...), aad)
}

func newAESGCM(keySize int) *cipherAESGCM {
return &cipherAESGCM{
keySize: keySize,
getAEAD: func(key []byte) (cipher.AEAD, error) {
aesCipher, err := aes.NewCipher(key)
if err != nil {
return nil, err
}

return cipher.NewGCM(aesCipher)
},
}
}

func getCipher(alg EncryptionType) (*cipherAESGCM, error) {
switch alg {
case EncryptionTypeA256GCM:
return newAESGCM(32), nil
default:
return nil, ErrUnsupportedEncryptionType
}
}
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/golang-jwt/jwe

go 1.16
oxisto marked this conversation as resolved.
Show resolved Hide resolved
80 changes: 80 additions & 0 deletions jwe.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package jwe

import (
"encoding/base64"
"encoding/json"
"strings"
)

// NewJWE creates a new JWE token.
// The plaintext will be encrypted with the method using a cek(Content Encryption Key).
oxisto marked this conversation as resolved.
Show resolved Hide resolved
// The cek will be encrypted with the alg using the key.
func NewJWE(alg KeyAlgorithm, key interface{}, method EncryptionType, plaintext []byte) (*jwe, error) {
jwe := &jwe{}

jwe.protected.Enc = method
chipher, err := getCipher(method)
if err != nil {
return nil, err
}

// Generate a random Content Encryption Key (CEK).
cek, err := generateKey(chipher.keySize)
if err != nil {
return nil, err
}

// Encrypt the CEK with the recipient's public key to produce the JWE Encrypted Key.
jwe.protected.Alg = alg
encrypter, err := createEncrypter(key)
if err != nil {
return nil, err
}
jwe.recipientKey, err = encrypter.Encrypt(cek, alg)
if err != nil {
return nil, err
}

// Serialize Authenticated Data
rawProtected, err := json.Marshal(jwe.protected)
if err != nil {
return nil, err
}
rawProtectedBase64 := base64.RawURLEncoding.EncodeToString(rawProtected)

// Perform authenticated encryption on the plaintext
jwe.iv, jwe.ciphertext, jwe.tag, err = chipher.encrypt(cek, []byte(rawProtectedBase64), plaintext)
if err != nil {
return nil, err
}

return jwe, nil
}

type jwe struct {
oxisto marked this conversation as resolved.
Show resolved Hide resolved
protected struct {
Alg KeyAlgorithm `json:"alg,omitempty"`
Enc EncryptionType `json:"enc,omitempty"`
}
recipientKey []byte
iv []byte
ciphertext []byte
tag []byte
}

// CompactSerialize serialize JWE to compact form.
// https://datatracker.ietf.org/doc/html/rfc7516#section-3.1
func (jwe *jwe) CompactSerialize() (string, error) {
rawProtected, err := json.Marshal(jwe.protected)
if err != nil {
return "", err
}

protected := base64.RawURLEncoding.EncodeToString(rawProtected)
encryptedKey := base64.RawURLEncoding.EncodeToString(jwe.recipientKey)
iv := base64.RawURLEncoding.EncodeToString(jwe.iv)
ciphertext := base64.RawURLEncoding.EncodeToString(jwe.ciphertext)
tag := base64.RawURLEncoding.EncodeToString(jwe.tag)

return strings.Join([]string{protected, encryptedKey, iv, ciphertext, tag}, "."), nil
}
45 changes: 45 additions & 0 deletions jwe_decrypt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package jwe

import (
"encoding/base64"
"encoding/json"
"errors"
)

func (jwe jwe) Decrypt(key interface{}) ([]byte, error) {
oxisto marked this conversation as resolved.
Show resolved Hide resolved

method := jwe.protected.Enc
if len(method) == 0 {
return nil, errors.New("no \"enc\" header")
oxisto marked this conversation as resolved.
Show resolved Hide resolved
}
cipher, err := getCipher(method)
if err != nil {
return nil, err
}

alg := jwe.protected.Alg
if len(alg) == 0 {
return nil, errors.New("no \"alg\" header")
}
decrypter, err := createDecrypter(key)
if err != nil {
return nil, err
}
// Decrypt JWE Encrypted Key with the recipient's private key to produce CEK.
cek, err := decrypter.Decrypt(jwe.recipientKey, alg)
if err != nil {
return nil, err
}

// Serialize Authenticated Data
rawProtected, err := json.Marshal(jwe.protected)
if err != nil {
return nil, err
}
rawProtectedBase64 := base64.RawURLEncoding.EncodeToString(rawProtected)

// Perform authenticated decryption on the ciphertext
data, err := cipher.decrypt(cek, []byte(rawProtectedBase64), jwe.iv, jwe.ciphertext, jwe.tag)

return data, err
}
Loading