Last active
April 23, 2019 05:05
-
-
Save Flushot/f7ab386996750c963e8888e9a80303c0 to your computer and use it in GitHub Desktop.
JWT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
set -e | |
openssl genpkey -algorithm RSA -out private.pem -pkeyopt rsa_keygen_bits:4096 | |
openssl rsa -pubout -in private.pem -out public.pem |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from __future__ import print_function, with_statement, unicode_literals | |
import getpass | |
import socket | |
import datetime | |
import json | |
import jwt | |
def read_key(file_name): | |
with open(file_name, 'r') as f: | |
return f.read() | |
def generate_token(subject, expires=None): | |
payload = { | |
# Reserved claims | |
'iss': '{}@{}'.format(getpass.getuser(), socket.gethostname()), # issuer | |
'nbf': datetime.datetime.now(), # not before | |
'sub': subject # subject | |
} | |
if expires is not None: | |
payload['exp'] = expires | |
return jwt.encode(payload, | |
read_key('private.pem'), | |
algorithm='RS256') | |
def get_token_payload(token): | |
return jwt.decode(token, | |
read_key('public.pem'), | |
algorithms=['RS256']) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$private_key = openssl_pkey_get_private('file://./private.pem'); | |
$public_key = openssl_pkey_get_public('file://./public.pem'); | |
$algo = OPENSSL_ALGO_SHA256; | |
try { | |
$message = 'foo bar'; | |
// Sign | |
$signature = null; | |
if (!openssl_sign($message, $signature, $private_key, $algo)) { | |
throw new Exception('OpenSSL failed to sign message: ' . openssl_error_string()); | |
} | |
echo 'Message: ' . $message . PHP_EOL; | |
echo 'Signature: ' . base64_encode($signature) . PHP_EOL; | |
// Verify | |
$verify_result = openssl_verify($message, $signature, $public_key, $algo); | |
if ($verify_result === -1) { | |
throw new Exception('OpenSSL failed to verify message: ' . openssl_error_string()); | |
} | |
echo 'Verified: ' . ($verify_result === 1 ? 'Yes' : 'No') . PHP_EOL; | |
} finally { | |
openssl_pkey_free($private_key); | |
openssl_pkey_free($public_key); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment