2019-05-24 17:06:48 +01:00
|
|
|
package encryption
|
2015-06-23 07:23:39 -04:00
|
|
|
|
|
|
|
import (
|
2020-05-05 18:41:48 -07:00
|
|
|
"crypto/sha1"
|
|
|
|
"crypto/sha256"
|
2016-06-20 07:17:39 -04:00
|
|
|
"encoding/base64"
|
2015-06-23 07:23:39 -04:00
|
|
|
"testing"
|
|
|
|
|
2017-10-23 12:23:46 -04:00
|
|
|
"github.com/stretchr/testify/assert"
|
2015-06-23 07:23:39 -04:00
|
|
|
)
|
|
|
|
|
2020-05-05 18:41:48 -07:00
|
|
|
func TestSignAndValidate(t *testing.T) {
|
|
|
|
seed := "0123456789abcdef"
|
|
|
|
key := "cookie-name"
|
|
|
|
value := base64.URLEncoding.EncodeToString([]byte("I am soooo encoded"))
|
|
|
|
epoch := "123456789"
|
|
|
|
|
|
|
|
sha256sig := cookieSignature(sha256.New, seed, key, value, epoch)
|
|
|
|
sha1sig := cookieSignature(sha1.New, seed, key, value, epoch)
|
|
|
|
|
|
|
|
assert.True(t, checkSignature(sha256sig, seed, key, value, epoch))
|
|
|
|
// This should be switched to False after fully deprecating SHA1
|
|
|
|
assert.True(t, checkSignature(sha1sig, seed, key, value, epoch))
|
|
|
|
|
|
|
|
assert.False(t, checkSignature(sha256sig, seed, key, "tampered", epoch))
|
|
|
|
assert.False(t, checkSignature(sha1sig, seed, key, "tampered", epoch))
|
|
|
|
}
|
|
|
|
|
2015-06-23 07:23:39 -04:00
|
|
|
func TestEncodeAndDecodeAccessToken(t *testing.T) {
|
|
|
|
const secret = "0123456789abcdefghijklmnopqrstuv"
|
|
|
|
const token = "my access token"
|
2016-06-20 07:17:39 -04:00
|
|
|
c, err := NewCipher([]byte(secret))
|
|
|
|
assert.Equal(t, nil, err)
|
|
|
|
|
|
|
|
encoded, err := c.Encrypt(token)
|
|
|
|
assert.Equal(t, nil, err)
|
|
|
|
|
|
|
|
decoded, err := c.Decrypt(encoded)
|
|
|
|
assert.Equal(t, nil, err)
|
|
|
|
|
|
|
|
assert.NotEqual(t, token, encoded)
|
|
|
|
assert.Equal(t, token, decoded)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestEncodeAndDecodeAccessTokenB64(t *testing.T) {
|
2018-11-29 14:26:41 +00:00
|
|
|
const secretBase64 = "A3Xbr6fu6Al0HkgrP1ztjb-mYiwmxgNPP-XbNsz1WBk="
|
2016-06-20 07:17:39 -04:00
|
|
|
const token = "my access token"
|
|
|
|
|
2018-11-29 14:26:41 +00:00
|
|
|
secret, err := base64.URLEncoding.DecodeString(secretBase64)
|
|
|
|
assert.Equal(t, nil, err)
|
2016-06-20 07:17:39 -04:00
|
|
|
c, err := NewCipher([]byte(secret))
|
2015-06-23 07:23:39 -04:00
|
|
|
assert.Equal(t, nil, err)
|
|
|
|
|
|
|
|
encoded, err := c.Encrypt(token)
|
|
|
|
assert.Equal(t, nil, err)
|
|
|
|
|
|
|
|
decoded, err := c.Decrypt(encoded)
|
|
|
|
assert.Equal(t, nil, err)
|
|
|
|
|
|
|
|
assert.NotEqual(t, token, encoded)
|
|
|
|
assert.Equal(t, token, decoded)
|
|
|
|
}
|