Merge branch 'wider' into two_point_oh

This commit is contained in:
Dave Grijalva 2014-08-26 13:45:08 -07:00
commit 358ed97e4b
6 changed files with 154 additions and 77 deletions

65
hmac.go Normal file
View File

@ -0,0 +1,65 @@
package jwt
import (
"bytes"
"crypto"
"crypto/hmac"
"errors"
)
type SigningMethodHMAC struct {
Name string
Hash crypto.Hash
}
var (
SigningMethodHS256 *SigningMethodHMAC
SigningMethodHS384 *SigningMethodHMAC
SigningMethodHS512 *SigningMethodHMAC
)
func init() {
// HS256
SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256}
RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod {
return SigningMethodHS256
})
// HS384
SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384}
RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod {
return SigningMethodHS384
})
// HS512
SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512}
RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod {
return SigningMethodHS512
})
}
func (m *SigningMethodHMAC) Alg() string {
return m.Name
}
func (m *SigningMethodHMAC) Verify(signingString, signature string, key []byte) error {
// Key
var sig []byte
var err error
if sig, err = DecodeSegment(signature); err == nil {
hasher := hmac.New(m.Hash.New, key)
hasher.Write([]byte(signingString))
if !bytes.Equal(sig, hasher.Sum(nil)) {
err = errors.New("Signature is invalid")
}
}
return err
}
func (m *SigningMethodHMAC) Sign(signingString string, key []byte) (string, error) {
hasher := hmac.New(m.Hash.New, key)
hasher.Write([]byte(signingString))
return EncodeSegment(hasher.Sum(nil)), nil
}

View File

@ -1,44 +1,57 @@
package jwt package jwt
import ( import (
"io/ioutil"
"strings" "strings"
"testing" "testing"
) )
var sha256TestData = []struct { var hmacTestData = []struct {
name string name string
tokenString string tokenString string
alg string
claims map[string]interface{} claims map[string]interface{}
valid bool valid bool
}{ }{
{ {
"web sample", "web sample",
"eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",
"HS256",
map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
true,
},
{
"HS384",
"eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.KWZEuOD5lbBxZ34g7F-SlVLAQ_r5KApWNWlZIIMyQVz5Zs58a7XdNzj5_0EcNoOy",
"HS384",
map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
true,
},
{
"HS512",
"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.CN7YijRX6Aw1n2jyI2Id1w90ja-DEMYiWixhYCyHnrZ1VfJRaFQz1bEbjjA5Fn4CLYaUG432dEYmSbS4Saokmw",
"HS512",
map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
true, true,
}, },
{ {
"web sample: invalid", "web sample: invalid",
"eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXo", "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXo",
"HS256",
map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
false, false,
}, },
} }
// Sample data from http://tools.ietf.org/html/draft-jones-json-web-signature-04#appendix-A.1 // Sample data from http://tools.ietf.org/html/draft-jones-json-web-signature-04#appendix-A.1
var sha256TestKey = []byte{ var hmacTestKey, _ = ioutil.ReadFile("test/hmacTestKey")
3, 35, 53, 75, 43, 15, 165, 188, 131, 126, 6, 101, 119, 123, 166,
143, 90, 179, 40, 230, 240, 84, 201, 40, 169, 15, 132, 178, 210, 80,
46, 191, 211, 251, 90, 146, 210, 6, 71, 239, 150, 138, 180, 195, 119,
98, 61, 34, 61, 46, 33, 114, 5, 46, 79, 8, 192, 205, 154, 245, 103,
208, 128, 163}
func TestHS256Verify(t *testing.T) { func TestHMACVerify(t *testing.T) {
for _, data := range sha256TestData { for _, data := range hmacTestData {
parts := strings.Split(data.tokenString, ".") parts := strings.Split(data.tokenString, ".")
method := GetSigningMethod("HS256") method := GetSigningMethod(data.alg)
err := method.Verify(strings.Join(parts[0:2], "."), parts[2], sha256TestKey) err := method.Verify(strings.Join(parts[0:2], "."), parts[2], hmacTestKey)
if data.valid && err != nil { if data.valid && err != nil {
t.Errorf("[%v] Error while verifying key: %v", data.name, err) t.Errorf("[%v] Error while verifying key: %v", data.name, err)
} }
@ -48,12 +61,12 @@ func TestHS256Verify(t *testing.T) {
} }
} }
func TestHS256Sign(t *testing.T) { func TestHMACSign(t *testing.T) {
for _, data := range sha256TestData { for _, data := range hmacTestData {
if data.valid { if data.valid {
parts := strings.Split(data.tokenString, ".") parts := strings.Split(data.tokenString, ".")
method := GetSigningMethod("HS256") method := GetSigningMethod(data.alg)
sig, err := method.Sign(strings.Join(parts[0:2], "."), sha256TestKey) sig, err := method.Sign(strings.Join(parts[0:2], "."), hmacTestKey)
if err != nil { if err != nil {
t.Errorf("[%v] Error signing token: %v", data.name, err) t.Errorf("[%v] Error signing token: %v", data.name, err)
} }

View File

@ -4,25 +4,47 @@ import (
"crypto" "crypto"
"crypto/rand" "crypto/rand"
"crypto/rsa" "crypto/rsa"
"crypto/sha256"
"crypto/x509" "crypto/x509"
"encoding/pem" "encoding/pem"
"errors" "errors"
) )
type SigningMethodRS256 struct{} type SigningMethodRSA struct {
Name string
Hash crypto.Hash
}
var (
SigningMethodRS256 *SigningMethodRSA
SigningMethodRS384 *SigningMethodRSA
SigningMethodRS512 *SigningMethodRSA
)
func init() { func init() {
RegisterSigningMethod("RS256", func() SigningMethod { // RS256
return new(SigningMethodRS256) SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256}
RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod {
return SigningMethodRS256
})
// RS384
SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384}
RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod {
return SigningMethodRS384
})
// RS512
SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512}
RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod {
return SigningMethodRS512
}) })
} }
func (m *SigningMethodRS256) Alg() string { func (m *SigningMethodRSA) Alg() string {
return "RS256" return m.Name
} }
func (m *SigningMethodRS256) Verify(signingString, signature string, key []byte) error { func (m *SigningMethodRSA) Verify(signingString, signature string, key []byte) error {
var err error var err error
// Decode the signature // Decode the signature
@ -38,30 +60,30 @@ func (m *SigningMethodRS256) Verify(signingString, signature string, key []byte)
} }
// Create hasher // Create hasher
hasher := sha256.New() hasher := m.Hash.New()
hasher.Write([]byte(signingString)) hasher.Write([]byte(signingString))
// Verify the signature // Verify the signature
return rsa.VerifyPKCS1v15(rsaKey, crypto.SHA256, hasher.Sum(nil), sig) return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
} }
// Implements the Sign method from SigningMethod // Implements the Sign method from SigningMethod
// For this signing method, must be PEM encoded PKCS1 or PKCS8 RSA private key // For this signing method, must be PEM encoded PKCS1 or PKCS8 RSA private key
func (m *SigningMethodRS256) Sign(signingString string, key []byte) (string, error) { func (m *SigningMethodRSA) Sign(signingString string, key []byte) (string, error) {
var err error var err error
// Key // Parse private key
var rsaKey *rsa.PrivateKey var rsaKey *rsa.PrivateKey
if rsaKey, err = m.parsePrivateKey(key); err != nil { if rsaKey, err = m.parsePrivateKey(key); err != nil {
return "", err return "", err
} }
// Create the hasher // Create the hasher
hasher := sha256.New() hasher := m.Hash.New()
hasher.Write([]byte(signingString)) hasher.Write([]byte(signingString))
// Sign the string and return the encoded bytes // Sign the string and return the encoded bytes
if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, crypto.SHA256, hasher.Sum(nil)); err == nil { if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil {
return EncodeSegment(sigBytes), nil return EncodeSegment(sigBytes), nil
} else { } else {
return "", err return "", err
@ -70,7 +92,7 @@ func (m *SigningMethodRS256) Sign(signingString string, key []byte) (string, err
} }
// Parse PEM encoded PKCS1 or PKCS8 public key // Parse PEM encoded PKCS1 or PKCS8 public key
func (m *SigningMethodRS256) parsePublicKey(key []byte) (*rsa.PublicKey, error) { func (m *SigningMethodRSA) parsePublicKey(key []byte) (*rsa.PublicKey, error) {
var err error var err error
// Parse PEM block // Parse PEM block
@ -99,7 +121,7 @@ func (m *SigningMethodRS256) parsePublicKey(key []byte) (*rsa.PublicKey, error)
} }
// Parse PEM encoded PKCS1 or PKCS8 private key // Parse PEM encoded PKCS1 or PKCS8 private key
func (m *SigningMethodRS256) parsePrivateKey(key []byte) (*rsa.PrivateKey, error) { func (m *SigningMethodRSA) parsePrivateKey(key []byte) (*rsa.PrivateKey, error) {
var err error var err error
// Parse PEM block // Parse PEM block

View File

@ -9,30 +9,47 @@ import (
var rsaTestData = []struct { var rsaTestData = []struct {
name string name string
tokenString string tokenString string
alg string
claims map[string]interface{} claims map[string]interface{}
valid bool valid bool
}{ }{
{ {
"basic: foo => bar", "Basic RS256",
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
"RS256",
map[string]interface{}{"foo": "bar"},
true,
},
{
"Basic RS384",
"eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw",
"RS384",
map[string]interface{}{"foo": "bar"},
true,
},
{
"Basic RS512",
"eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.zBlLlmRrUxx4SJPUbV37Q1joRcI9EW13grnKduK3wtYKmDXbgDpF1cZ6B-2Jsm5RB8REmMiLpGms-EjXhgnyh2TSHE-9W2gA_jvshegLWtwRVDX40ODSkTb7OVuaWgiy9y7llvcknFBTIg-FnVPVpXMmeV_pvwQyhaz1SSwSPrDyxEmksz1hq7YONXhXPpGaNbMMeDTNP_1oj8DZaqTIL9TwV8_1wb2Odt_Fy58Ke2RVFijsOLdnyEAjt2n9Mxihu9i3PhNBkkxa2GbnXBfq3kzvZ_xxGGopLdHhJjcGWXO-NiwI9_tiu14NRv4L2xC0ItD9Yz68v2ZIZEp_DuzwRQ",
"RS512",
map[string]interface{}{"foo": "bar"}, map[string]interface{}{"foo": "bar"},
true, true,
}, },
{ {
"basic invalid: foo => bar", "basic invalid: foo => bar",
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
"RS256",
map[string]interface{}{"foo": "bar"}, map[string]interface{}{"foo": "bar"},
false, false,
}, },
} }
func TestRS256Verify(t *testing.T) { func TestRSAVerify(t *testing.T) {
key, _ := ioutil.ReadFile("test/sample_key.pub") key, _ := ioutil.ReadFile("test/sample_key.pub")
for _, data := range rsaTestData { for _, data := range rsaTestData {
parts := strings.Split(data.tokenString, ".") parts := strings.Split(data.tokenString, ".")
method := GetSigningMethod("RS256") method := GetSigningMethod(data.alg)
err := method.Verify(strings.Join(parts[0:2], "."), parts[2], key) err := method.Verify(strings.Join(parts[0:2], "."), parts[2], key)
if data.valid && err != nil { if data.valid && err != nil {
t.Errorf("[%v] Error while verifying key: %v", data.name, err) t.Errorf("[%v] Error while verifying key: %v", data.name, err)
@ -43,13 +60,13 @@ func TestRS256Verify(t *testing.T) {
} }
} }
func TestRS256Sign(t *testing.T) { func TestRSASign(t *testing.T) {
key, _ := ioutil.ReadFile("test/sample_key") key, _ := ioutil.ReadFile("test/sample_key")
for _, data := range rsaTestData { for _, data := range rsaTestData {
if data.valid { if data.valid {
parts := strings.Split(data.tokenString, ".") parts := strings.Split(data.tokenString, ".")
method := GetSigningMethod("RS256") method := GetSigningMethod(data.alg)
sig, err := method.Sign(strings.Join(parts[0:2], "."), key) sig, err := method.Sign(strings.Join(parts[0:2], "."), key)
if err != nil { if err != nil {
t.Errorf("[%v] Error signing token: %v", data.name, err) t.Errorf("[%v] Error signing token: %v", data.name, err)
@ -65,7 +82,7 @@ func TestRSAKeyParsing(t *testing.T) {
key, _ := ioutil.ReadFile("test/sample_key") key, _ := ioutil.ReadFile("test/sample_key")
pubKey, _ := ioutil.ReadFile("test/sample_key.pub") pubKey, _ := ioutil.ReadFile("test/sample_key.pub")
badKey := []byte("All your base are belong to key") badKey := []byte("All your base are belong to key")
method := GetSigningMethod("RS256").(*SigningMethodRS256) method := GetSigningMethod("RS256").(*SigningMethodRSA)
// Test parsePrivateKey // Test parsePrivateKey
if _, e := method.parsePrivateKey(key); e != nil { if _, e := method.parsePrivateKey(key); e != nil {

View File

@ -1,41 +0,0 @@
package jwt
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"errors"
)
type SigningMethodHS256 struct{}
func init() {
RegisterSigningMethod("HS256", func() SigningMethod {
return new(SigningMethodHS256)
})
}
func (m *SigningMethodHS256) Alg() string {
return "HS256"
}
func (m *SigningMethodHS256) Verify(signingString, signature string, key []byte) (err error) {
// Key
var sig []byte
if sig, err = DecodeSegment(signature); err == nil {
hasher := hmac.New(sha256.New, key)
hasher.Write([]byte(signingString))
if !bytes.Equal(sig, hasher.Sum(nil)) {
err = errors.New("Signature is invalid")
}
}
return
}
func (m *SigningMethodHS256) Sign(signingString string, key []byte) (string, error) {
hasher := hmac.New(sha256.New, key)
hasher.Write([]byte(signingString))
return EncodeSegment(hasher.Sum(nil)), nil
}

1
test/hmacTestKey Normal file
View File

@ -0,0 +1 @@
#5K+・シミew{ヲ住ウ(跼Tノ(ゥ┫メP.ソモ燾辻G<>感テwb="=.!r.Oタヘ奎gミ€