Created
December 21, 2018 15:25
-
-
Save tom-code/3428a6c73309af684f699810554d5c2a to your computer and use it in GitHub Desktop.
jws sign and verify example
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
| package main | |
| import( | |
| "fmt" | |
| "gopkg.in/square/go-jose.v2" | |
| "encoding/json" | |
| "io/ioutil" | |
| "crypto/ecdsa" | |
| ) | |
| func readKey() jose.JSONWebKey { | |
| body, err := ioutil.ReadFile("key.json") | |
| if err != nil { | |
| panic(err) | |
| } | |
| var key jose.JSONWebKey | |
| if err := json.Unmarshal(body, &key); err != nil { | |
| panic(err) | |
| } | |
| return key | |
| } | |
| func sign() string { | |
| key := readKey() | |
| options := &jose.SignerOptions{} | |
| options.WithHeader("url", "http://a.b.c") | |
| signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.ES256, Key: key}, options) | |
| if err != nil { | |
| panic(err) | |
| } | |
| payload:= `{"iss":"joe","exp":1300819380,"http://example.com/is_root":true}` | |
| jws, err := signer.Sign([]byte(payload)) | |
| if err != nil { | |
| fmt.Println(err.Error()) | |
| } | |
| zz := jws.FullSerialize() | |
| fmt.Println(zz) | |
| output, _ := jws.CompactSerialize() | |
| fmt.Println(output) | |
| return output | |
| } | |
| func verify(in string) { | |
| key := readKey() | |
| jws, err := jose.ParseSigned(in) | |
| if err != nil { | |
| panic(err) | |
| } | |
| fmt.Println(jws) | |
| payload := jws.UnsafePayloadWithoutVerification() | |
| fmt.Println(string(payload[:])) | |
| for _, signature := range(jws.Signatures) { | |
| fmt.Println(signature.Header) | |
| fmt.Println(signature.Unprotected) | |
| fmt.Println(signature.Protected) | |
| fmt.Println(signature.Protected.ExtraHeaders) | |
| } | |
| fmt.Println(key) | |
| privateKey := key.Key.(*ecdsa.PrivateKey) | |
| publicKey := privateKey.PublicKey | |
| output, err := jws.Verify(&publicKey) | |
| if err != nil { | |
| panic(err) | |
| } | |
| fmt.Printf(string(output)) | |
| } | |
| func main() { | |
| fmt.Println("test") | |
| signed := sign() | |
| verify(signed) | |
| } |
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
| { | |
| "kty":"EC", | |
| "crv":"P-256", | |
| "x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU", | |
| "y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0", | |
| "d":"jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment