JWT key is invalid - go

I am following this example https://www.youtube.com/watch?v=eVlxuST7dCA to make a jwt auth. When I run the code below I get "Key is invalid" error. When I try printing tokenString it is empty. The GitHub to this sample is https://github.com/potatogopher/jwt-go-example/blob/master/server.go Why am I getting invalid error?
var privateKey []byte
privateKey, err := ioutil.ReadFile("demo.rsa")
token := jwt.New(jwt.GetSigningMethod("RS256"))
tokenString, err := token.SignedString(privateKey)
fmt.Println("TOKEN:", tokenString)

I think the example code you're referring to uses an outdated API of jwt-go. The RS256 signing method requires the key to be a rsa.PrivateKey and not a byte buffer. This means, that the private key first has to be parsed using the jwt.ParseRSAPrivateKeyFromPEMfunction.
I've updated your example below:
func main() {
tokenString, err := createSignedTokenString()
if err != nil {
panic(err)
}
fmt.Printf("Signed token string:\n%v\n", tokenString)
token, err := parseTokenFromSignedTokenString(tokenString)
if err != nil {
panic(err)
}
fmt.Printf("Parsed token valid = %v, raw token:\n%v\n", token.Valid, token.Raw)
}
func createSignedTokenString() (string, error) {
privateKey, err := ioutil.ReadFile("demo.rsa")
if err != nil {
return "", fmt.Errorf("error reading private key file: %v\n", err)
}
key, err := jwt.ParseRSAPrivateKeyFromPEM(privateKey)
if err != nil {
return "", fmt.Errorf("error parsing RSA private key: %v\n", err)
}
token := jwt.New(jwt.SigningMethodRS256)
tokenString, err := token.SignedString(key)
if err != nil {
return "", fmt.Errorf("error signing token: %v\n", err)
}
return tokenString, nil
}
func parseTokenFromSignedTokenString(tokenString string) (*jwt.Token, error) {
publicKey, err := ioutil.ReadFile("demo.rsa.pub")
if err != nil {
return nil, fmt.Errorf("error reading public key file: %v\n", err)
}
key, err := jwt.ParseRSAPublicKeyFromPEM(publicKey)
if err != nil {
return nil, fmt.Errorf("error parsing RSA public key: %v\n", err)
}
parsedToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return key, nil
})
if err != nil {
return nil, fmt.Errorf("error parsing token: %v", err)
}
return parsedToken, nil
}

You need to create the private key with this command: openssl genrsa -out demo.rsa
If you dont want to do that, you can also use the hmac signing method where you only have to supply a secret key/string.
Example:
key := []byte("test")
token := jwt.New(jwt.SigningMethodHS256)
tokenString, err := token.SignedString(key)
fmt.Println("TOKEN:", tokenString)

Related

How to read pcap and decrypt these payload with private key at Golang

i want to decrypt tls payloads with private key but I take an error.
This snippet is read the pcap's payload and decrypt.
Could not decrypt text crypto/rsa: decryption error
func ReadFromPcap(path string) {
handle, err := pcap.OpenOffline(path)
if err != nil {
log.Fatal(err)
}
defer handle.Close()
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range packetSource.Packets() {
appLayer := packet.ApplicationLayer()
if appLayer != nil {
privateKey, err := GetKeys()
fmt.Println(privateKey)
if err != nil {
fmt.Println("Could not retrieve key file", err)
}
decryptedText, err := Decrypt(privateKey, appLayer.Payload())
if err != nil {
fmt.Println("Could not decrypt text", err.Error())
return
}
fmt.Println("decrypted text: ", string(decryptedText))
}
}
}
func Decrypt(privKey *rsa.PrivateKey, cipherText []byte) ([]byte, error) {
decryptedBytes, err := rsa.DecryptOAEP(sha256.New(), nil, privKey, cipherText, nil)
if err != nil {
return nil, err
}
return decryptedBytes, nil
}

Encrypting/Decrypting JWE with Jose in Go

I'm trying to create a JWE decryption function but having trouble determining how to use the Go Jose interface for doing so. I've factored the encryption using passphrase (I prefer a passphrase for this use case):
token := jwt.NewWithClaims(
jwt.SigningMethodHS256,
claims,
)
ss, err := token.SignedString("thisisatestpassphraserighthere")
if err != nil {
panic("COULD_NOT_GENERATE")
return
}
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(err)
}
publicKey := &privateKey.PublicKey
encrypter, err := jose.NewEncrypter(
jose.A128CBC_HS256,
jose.Recipient{Algorithm: jose.RSA_OAEP, Key: publicKey},
nil,
)
if err != nil {
return
}
object, err := encrypter.Encrypt([]byte(ss))
if err != nil {
errRes = s.Error(codes.Internal, err, nil)
return
}
key, err := object.CompactSerialize()
if err != nil {
errRes = s.Error(codes.Internal, err, nil)
return
}
fmt.Println(key)
The above code creates a JWT, encodes it, compacts it and returns the key. It's not however totally clear how to decrypt it with the passphrase now.
There is an example for JWE on the Jose docs: https://godoc.org/gopkg.in/square/go-jose.v2#example-Encrypter--Encrypt
So I've factored this:
object, err = jose.ParseEncrypted(Key)
if err != nil {
panic(err)
}
decrypted, err := object.Decrypt(...)
Inside the ellipses I'm not sure what to put though. I can't seem to determine how to pass in a key based on passphrase.
I was doing a few things wrong it seems. First of all rsa.GenerateKey uses a randomized value. This was totally wrong :-p the following is how you can encrypt a JWT into a JWE using a token:
rcpt := jose.Recipient{
Algorithm: jose.PBES2_HS256_A128KW,
Key: "mypassphrase",
PBES2Count: 4096,
PBES2Salt: []byte{ your salt... },
}
enc, err := jose.NewEncrypter(jose.A128CBC_HS256, rcpt, nil)
if err != nil {
panic("oops")
}
jewPlaintextToken, err := enc.Encrypt(jwtToken)
if err != nil {
panic("oops")
}
key, err := object.CompactSerialize()
if err != nil {
panic("oops")
}
This is how you decrypt:
// Decrypt the receive key
jwe, err := jose.ParseEncrypted(jewPlaintextToken)
if err != nil {
panic("oops")
}
decryptedKey, err := jwe.Decrypt("mypassphrase")
if err != nil {
panic("oops")
}
If anyone sees any major problems/security issues with this method, please mention it.
Inside the ellipses I'm not sure what to put though. I can't seem to determine how to pass in a key based on passphrase.
From the JWE example in the documentation, you must pass the private key. See the below part for decryption
https://godoc.org/gopkg.in/square/go-jose.v2#JSONWebEncryption.Decrypt
// Generate a public/private key pair to use for this example.
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(err)
}
// Parse the serialized, encrypted JWE object. An error would indicate that
// the given input did not represent a valid message.
object, err = ParseEncrypted(serialized)
if err != nil {
panic(err)
}
// Now we can decrypt and get back our original plaintext. An error here
// would indicate the the message failed to decrypt, e.g. because the auth
// tag was broken or the message was tampered with.
decrypted, err := object.Decrypt(privateKey)
if err != nil {
panic(err)
}
fmt.Printf(string(decrypted))

unstable decryption, sometimes got cipher: message authentication failed

I'm trying to create E2E Encryption for my software, but the decryption are very unstable, sometime can successfully decrypt, sometime got cipher: message authentication failed, here's my encrypt & decrypt code
func Encrypt(data []byte, passphrase string) ([]byte, error) {
// create aes.NewCipher from hashed md5 passphrase
block, _ := aes.NewCipher([]byte(createHash(passphrase)))
// NewGCM returns the given 128-bit, block cipher wrapped in
// Galois Counter Mode with the standard nonce length.
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
// initialize slice with length of nonce that must be passed to Seal and Open.
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
return ciphertext, nil
}
func Decrypt(data []byte, passphrase string) ([]byte, error) {
// create md5 byte slice
key := []byte(createHash(passphrase))
// just `reverse` algorithm with passphrase until return
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
the encrypted binary value are transferred via http :
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
decrypt, err := Decrypt(body, r.Passphrase)
what i already try is to check, is ioutil.ReadAll read content correctly, or something wrong with decryptor
sorry, the problem was not in encryption/decryption, but in http server for transferring the chipertext, and already fixes now https://github.com/codenoid/GoTral-Server/commit/493c7f654753cae36f074c1c5f382953e227d295

Decrypting a non ASCII armored PGP file in Go

Is it possible to decrypt binary .PGP file with Go's "golang.org/x/crypto/openpgp" library?
The following code works with an armored ASCII encoded file but throws EOF error with a binary PGP file. Is there a similar function to armor.Decode() that allows for the binary file to be decrypted?
func DecryptFile(encryptedFilePath string, decryptedFilePath string) error {
pubKey := decodePublicKey()
privKey := decodePrivateKey()
entity := createEntityFromKeys(pubKey, privKey)
file := readFile(encryptedFilePath)
block, err := armor.Decode(file)
if err != nil {
log.Printf("Error reading OpenPGP Armor: %s", err)
return err
}
if block.Type != "Message" {
log.Println("Invalid message type")
return err
}
var entityList openpgp.EntityList
entityList = append(entityList, entity)
messageDetails, err := openpgp.ReadMessage(block.Body, entityList, nil, nil)
if err != nil {
log.Printf("Error reading message: %s", err)
return err
}
compressed, err := gzip.NewReader(messageDetails.UnverifiedBody)
if err != nil {
log.Printf("Invalid compression level: %s", err)
return err
}
defer compressed.Close()
buffer := bytes.NewBuffer(nil)
n, err := io.Copy(buffer, compressed)
if err != nil {
log.Printf("Error reading encrypted file: %s", err)
return err
}
err = ioutil.WriteFile(decryptedFilePath, buffer.Bytes(), 0644)
if err != nil {
log.Println(err)
return err
}
log.Printf("Decrypted %d bytes\n", n)
return nil
}
I encountered the same exact problem with PGP, also got EOF on my first trial.
The encrypted file is in binary(.pgp)
The private/public key in key ring armored file(.asc) like this:
----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----
Here is the code that I use:
keyRing, err := os.Open("keyArmoredFile.asc")
if err != nil {
log.Fatal(err)
}
entityList, err := openpgp.ReadArmoredKeyRing(keyRing)
if err != nil {
log.Fatal(err)
}
entity := entityList[0]
passphraseByte := []byte("password")
err = entity.PrivateKey.Decrypt(passphraseByte)
if err != nil {
log.Fatal(err)
}
for _, subkey := range entity.Subkeys {
subkey.PrivateKey.Decrypt(passphraseByte)
}
encryptedContent, err := os.Open("encryptedFile.pgp")
if err != nil {
log.Fatal(err)
}
md, err := openpgp.ReadMessage(encryptedContent, entityList, nil, nil)
if err != nil {
log.Fatal(err)}
bytes, err := ioutil.ReadAll(md.UnverifiedBody)
if err != nil {
log.Fatal(err)
}
// decryption result
decStr := string(bytes)
Reference:
https://gist.github.com/stuart-warren/93750a142d3de4e8fdd2

How to refactor semantic duplication

I have defined two funcs that do slightly different things but are syntactically the same.
Functions in question send POST requests to an api.
The duplication occurs in constructing the request, adding headers, etc.
How can I refactor the code to remove said duplication.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
)
type token struct {
Token string
}
type config struct {
Foo string
}
func main() {
token, err := getAuthToken()
if err != nil {
log.Fatal(err)
}
config, err := getConfig("foo", token)
if err != nil {
log.Fatal(err)
}
_ = config
}
func getAuthToken() (string, error) {
endpoint := "foo"
body := struct {
UserName string `json:"username"`
Password string `json:"password"`
}{
UserName: "foo",
Password: "bar",
}
jsnBytes, err := json.Marshal(body)
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", endpoint, bytes.NewReader(jsnBytes))
if err != nil {
return "", fmt.Errorf("Unable to create request. %v", err)
}
req.Header.Add("Content-Type", "application/json")
dump, err := httputil.DumpRequest(req, true)
if err != nil {
return "", fmt.Errorf("Could not dump request. ", err)
}
log.Println("Request: ", string(dump))
client := http.Client{}
log.Println("Initiating http request")
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("HTTP Error: %v", err)
}
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("Error reading response body: %v", err)
}
var token token
err = json.Unmarshal(bytes, &token)
if err != nil {
return "", fmt.Errorf("Could not unamrshal json. ", err)
}
return token.Token, nil
}
func getConfig(id string, token string) (*config, error) {
endpoint := "foo"
body := struct {
ID string `json:"id"`
}{
ID: id,
}
jsnBytes, err := json.Marshal(body)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", endpoint, bytes.NewReader(jsnBytes))
if err != nil {
return nil, fmt.Errorf("Unable to create request. %v", err)
}
req.Header.Add("Authorization", "Bearer "+token)
req.Header.Add("Content-Type", "application/json")
dump, err := httputil.DumpRequest(req, true)
if err != nil {
return nil, fmt.Errorf("Could not dump request. ", err)
}
log.Println("Request: ", string(dump))
client := http.Client{}
log.Println("Initiating http request")
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("HTTP Error: %v", err)
}
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Error reading response body: %v", err)
}
var config config
err = json.Unmarshal(bytes, &config)
if err != nil {
return nil, fmt.Errorf("Could not unamrshal json. ", err)
}
return &config, nil
}
I would say the essence of sending the request is that you are sending a body to an endpoint and parsing a result. The headers are then optional options that you can add to the request along the way. With this in mind I would make a single common function for sending the request with this signature:
type option func(*http.Request)
func sendRequest(endpoint string, body interface{}, result interface{}, options ...option) error {
Note this is using functional options which Dave Cheney did an excellent description of here:
https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis
The complete code then becomes:
https://play.golang.org/p/GV6FeipIybA
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
)
type token struct {
Token string
}
type config struct {
Foo string
}
func main() {
token, err := getAuthToken()
if err != nil {
log.Fatal(err)
}
config, err := getConfig("foo", token)
if err != nil {
log.Fatal(err)
}
_ = config
}
func getAuthToken() (string, error) {
endpoint := "foo"
body := struct {
UserName string `json:"username"`
Password string `json:"password"`
}{
UserName: "foo",
Password: "bar",
}
var token token
err := sendRequest(endpoint, body, &token)
if err != nil {
return "", err
}
return token.Token, nil
}
func getConfig(id string, token string) (*config, error) {
endpoint := "foo"
body := struct {
ID string `json:"id"`
}{
ID: id,
}
var config config
err := sendRequest(endpoint, body, &config, header("Content-Type", "application/json"))
if err != nil {
return nil, err
}
return &config, nil
}
type option func(*http.Request)
func header(key, value string) func(*http.Request) {
return func(req *http.Request) {
req.Header.Add(key, value)
}
}
func sendRequest(endpoint string, body interface{}, result interface{}, options ...option) error {
jsnBytes, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequest("POST", endpoint, bytes.NewReader(jsnBytes))
if err != nil {
return fmt.Errorf("Unable to create request. %v", err)
}
req.Header.Add("Content-Type", "application/json")
for _, option := range options {
option(req)
}
dump, err := httputil.DumpRequest(req, true)
if err != nil {
return fmt.Errorf("Could not dump request. ", err)
}
log.Println("Request: ", string(dump))
client := http.Client{}
log.Println("Initiating http request")
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("HTTP Error: %v", err)
}
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Error reading response body: %v", err)
}
err = json.Unmarshal(bytes, result)
if err != nil {
return fmt.Errorf("Could not unamrshal json. ", err)
}
return nil
}
The way I would do this is to extract the two parts that are common to both request executions: 1) create a request and 2) execute the request.
Gist with new code using HTTP Bin as an example
Creating the request includes setting up the endpoint, headers and marshaling the request body to JSON. In your case, you're also dumping the request to the log, that can also go in there. This is how it would look like:
func buildRequest(endpoint string, body interface{}, extraHeaders map[string]string) (*http.Request, error) {
jsnBytes, err := json.Marshal(body)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", endpoint, bytes.NewReader(jsnBytes))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
for name, value := range extraHeaders {
req.Header.Add(name, value)
}
dump, err := httputil.DumpRequest(req, true)
if err != nil {
return nil, err
}
log.Println("Request: ", string(dump))
return req, nil
}
If you have no extra headers, you can pass nil as the third argument here.
The second part to extract is actually executing the request and unmarshalling the data. This is how the executeRequest would look like:
func executeRequest(req *http.Request, responseBody interface{}) error {
client := http.Client{}
log.Println("Initiating http request")
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
log.Printf("Response is: %s\n", string(bytes))
err = json.Unmarshal(bytes, &responseBody)
return err
}

Resources