Adds unit testing for jws
This commit is contained in:
55
jwt/signer_test.go
Normal file
55
jwt/signer_test.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func NewHMACKey(n int) []byte {
|
||||
res := make([]byte, n)
|
||||
rand.Reader.Read(res)
|
||||
return res
|
||||
}
|
||||
|
||||
func CachedRSAkey() (*rsa.PrivateKey, error) {
|
||||
keyPath := filepath.Join(os.TempDir(), "narco-jwt-test.key")
|
||||
f, err := os.Open(keyPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) == false {
|
||||
return nil, err
|
||||
}
|
||||
// generate a key
|
||||
log.Printf("Generating a new key")
|
||||
key, err := rsa.GenerateKey(rand.Reader, 1024)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
f, err := os.Create(keyPath)
|
||||
if err != nil {
|
||||
log.Printf("Could not cache the generated key: %s", err)
|
||||
return key, nil
|
||||
}
|
||||
|
||||
data := x509.MarshalPKCS1PrivateKey(key)
|
||||
_, err = f.Write(data)
|
||||
if err != nil {
|
||||
log.Printf("Could not cache the generated key: %s", err)
|
||||
}
|
||||
|
||||
return key, nil
|
||||
}
|
||||
|
||||
keydata, err := ioutil.ReadAll(f)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Could not read %s: %s", keyPath, err)
|
||||
}
|
||||
|
||||
return x509.ParsePKCS1PrivateKey(keydata)
|
||||
}
|
||||
Reference in New Issue
Block a user