Last active
June 13, 2017 15:03
-
-
Save seriousben/c26ce23f27f263d32c2c8ee7c99da746 to your computer and use it in GitHub Desktop.
jwt validation with cgo and openssl
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 | |
// https://github.com/nodejs/node/blob/master/src/node_crypto.cc#L4374 | |
import ( | |
"log" | |
"strings" | |
"github.com/spacemonkeygo/openssl" | |
) | |
/* | |
CGO_CFLAGS="-I /usr/local/opt/openssl/include/" CGO_LDFLAGS="-L/usr/local/opt/openssl@1.0/lib" go run --ldflags '-extldflags "-static"' main_openssl.go | |
*/ | |
func main() { | |
const token = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQmVuamFtaW4gQm91ZHJlYXUiLCJ1c2VyX3JvbGVzIjoiQWRtaW4iLCJzdWIiOiJzZXJpb3VzYmVuIiwiaWF0IjoxNDk3MzY2MDUxfQ.SJrhbZDfb2dPzJuZml4BCWNS5IWSo9_dMOJfZW3YHx_5-qneJE-mUi4tDEUQedjmu2hb5O9pP5mUY_r6cnSBs" | |
const pubPEM = `-----BEGIN PUBLIC KEY----- | |
MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEHmtsC5qTi1O17410zIACT0f1iB8iAmIY | |
hJ3Qq2bFGiBBBvNn4JwO4LO84hhj0mhDTgW7CHyGgOn6Nq2bHcF//g== | |
-----END PUBLIC KEY-----` | |
parts := strings.Split(token, ".") | |
data := strings.Join(parts[0:2], ".") | |
pub, err := openssl.LoadECPublicKeyFromPEM([]byte(pubPEM)) | |
if err != nil { | |
log.Fatalln("EC PK from PEM", err) | |
} | |
log.Println("data", data) | |
log.Println("signature", parts[2]) | |
err = pub.VerifyPKCS1v15(openssl.SHA256_Method, []byte(data), []byte(parts[2])) | |
if err != nil { | |
log.Fatalln("Not valid", err) | |
} | |
log.Println("Valid") | |
} |
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
func ValidateJWT(data, sig []byte) error { | |
ctx := C.X_EVP_MD_CTX_new() | |
defer C.X_EVP_MD_CTX_free(ctx) | |
C.ERR_load_crypto_strings() | |
if 1 != C.X_EVP_VerifyInit(ctx, method) { | |
return errors.New("verifypkcs1v15: failed to init verify") | |
} | |
if len(data) > 0 { | |
if 1 != C.X_EVP_VerifyUpdate( | |
ctx, unsafe.Pointer(&data[0]), C.uint(len(data))) { | |
return errors.New("verifypkcs1v15: failed to update verify") | |
} | |
} | |
if 1 != C.X_EVP_VerifyFinal(ctx, ((*C.uchar)(unsafe.Pointer(&sig[0]))), C.uint(len(sig)), key.key) { | |
msg := C.ERR_error_string(500, nil) | |
return errors.New("verifypkcs1v15: failed to finalize verify " + C.GoString(msg)) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment