Created
April 22, 2020 18:33
-
-
Save jrwren/7af93943c9f04988e24c9bcbcdd1bdcd to your computer and use it in GitHub Desktop.
bosses boss linked me to this... JWT in <50 lines of code.
This file contains 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
package main | |
import ( | |
"crypto" | |
"crypto/rand" | |
"crypto/rsa" | |
"crypto/sha256" | |
"encoding/base64" | |
"os" | |
) | |
func main() { | |
key, err := rsa.GenerateKey(rand.Reader, 4096) | |
if err != nil { | |
panic(err) | |
} | |
payload := []byte(`{"verb":"hello","object":"world"}`) | |
message := signRS256(payload, key) | |
os.Stdout.Write(message) | |
} | |
func signRS256(payload []byte, key *rsa.PrivateKey) []byte { | |
msg := make([]byte, base64.RawURLEncoding.EncodedLen(len(payload)+37+513)) | |
// {"alg":"RS256","typ":"JWT"} | |
n := copy(msg, `eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.`) | |
n += encodeBase64(msg[n:], payload) | |
signature := generateRS256(msg[:n], key) | |
msg[n], n = '.', n+1 | |
msg = append(msg, '.') | |
n += encodeBase64(msg[n:], signature) | |
return msg[:n] | |
} | |
func encodeBase64(buf, msg []byte) int { | |
n := base64.RawURLEncoding.EncodedLen(len(msg)) | |
if n > len(buf) { | |
panic(`encoding overflow`) | |
} | |
base64.RawURLEncoding.Encode(buf, msg) | |
return n | |
} | |
func generateRS256(msg []byte, key *rsa.PrivateKey) []byte { | |
h := sha256.New() | |
h.Write(msg) | |
sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, h.Sum(nil)) | |
if err != nil { | |
panic(err) | |
} | |
println(len(sig)) | |
return sig | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment