Beispiel #1
0
func getSignature(b []byte, secret []byte) []byte {
	keym := hmac.NewSHA256(secret)
	keym.Write(b)
	m := hmac.NewSHA256(keym.Sum())
	m.Write(b)
	return m.Sum()
}
func TestEncoder(t *testing.T) {
	b, err := aes.NewCipher([]byte("1234567890123456"))
	if err != nil {
		t.Error(err)
	}
	e1 := Encoder{
		Hash:  hmac.NewSHA256([]byte("secret-key1")),
		Block: b,
	}

	b, err = aes.NewCipher([]byte("0123456789012345"))
	if err != nil {
		t.Error(err)
	}
	e2 := Encoder{
		Hash:  hmac.NewSHA256([]byte("secret-key2")),
		Block: b,
	}

	value := make(SessionData)
	value["foo"] = "bar"
	value["baz"] = 128

	var count int
	for i := 0; i < 50; i++ {
		// Running this multiple times to check if any special character
		// breaks encoding/decoding.
		value := make(SessionData)
		value["foo"] = "bar"
		value["baz"] = 128

		encoded, err2 := e1.Encode("sid", value)
		if err2 != nil {
			t.Error(err2)
		}
		decoded, err3 := e1.Decode("sid", encoded)
		if err3 != nil {
			t.Errorf("%v: %v", err3, encoded)
			count++
		}
		if fmt.Sprintf("%v", decoded) != fmt.Sprintf("%v", value) {
			t.Errorf("Expected %v, got %v.", value, decoded)
		}
		_, err4 := e2.Decode("sid", encoded)
		if err4 == nil {
			t.Errorf("Expected failure decoding.")
		}
	}
	if count > 0 {
		t.Errorf("%d errors out of 100.", count)
	}
}
// SetStoreKeys defines authentication and encryption keys for the given store.
//
// This is a convenience to set secret keys for the available stores.
// It sets authentication hashes using HMAC-SHA-256 and encryption blocks
// using AES. For custom hash or encryption methods, call
// SessionStore.SetEncoders() directly.
//
// A store must be registered using the given key before this is called.
//
// Keys are defined in pairs: one for authentication and the other for
// encryption. The encryption key can be set to nil or omitted in the last
// pair, but the authentication key is required in all pairs.
//
// Multiple pairs are accepted to allow key rotation, but the common case is
// to set a single authentication key and optionally an encryption key.
//
// The encryption key, if set, must be either 16, 24, or 32 bytes to select
// AES-128, AES-192, or AES-256 modes.
func (f *SessionFactory) SetStoreKeys(key string,
	pairs ...[]byte) (bool, error) {
	store, err := f.Store(key)
	if err != nil {
		return false, err
	}
	var b cipher.Block
	size := len(pairs)
	encoders := make([]SessionEncoder, size/2+size%2)
	for i := 0; i < size; i += 2 {
		if pairs[i] == nil || len(pairs[i]) == 0 {
			return false, ErrMissingHashKey
		}
		if size <= i+1 || pairs[i+1] == nil {
			b = nil
		} else {
			b, err = aes.NewCipher(pairs[i+1])
			if err != nil {
				return false, err
			}
		}
		encoders[i/2] = &Encoder{
			Hash:      hmac.NewSHA256(pairs[i]),
			Block:     b,
			MaxAge:    86400 * 30,
			MaxLength: 4096,
		}
	}
	// Set the new encoders.
	store.SetEncoders(encoders...)
	return true, nil
}
Beispiel #4
0
func authorizationHeader(date string) []string {
	h := hmac.NewSHA256([]uint8(secretKey))
	h.Write([]uint8(date))
	signature := base64.StdEncoding.EncodeToString(h.Sum())
	auth := fmt.Sprintf("AWS3-HTTPS AWSAccessKeyId=%s, Algorithm=HmacSHA256, Signature=%s", accessKey, signature)
	return []string{auth}
}
func TestAuthentication(t *testing.T) {
	// TODO test too old / too new timestamps
	hash := hmac.NewSHA256([]byte("secret-key"))
	key := "session-key"
	timestamp := time.UTC().Seconds()

	for _, value := range testStringValues {
		signed := createHmac(hash, key, []byte(value), timestamp)
		verified, err := verifyHmac(hash, key, signed, 0, 0, 0)
		if err != nil {
			t.Error(err)
		}
		if string(verified) != value {
			t.Errorf("Expected %v, got %v.", value, string(verified))
		}
	}
}
Beispiel #6
0
Datei: sign.go Projekt: supr/sns
func sign(auth aws.Auth, method, path string, params map[string]string, host string) {
	params["AWSAccessKeyId"] = auth.AccessKey
	params["SignatureVersion"] = "2"
	params["SignatureMethod"] = "HmacSHA256"

	var sarray []string
	for k, v := range params {
		sarray = append(sarray, aws.Encode(k)+"="+aws.Encode(v))
	}
	sort.StringSlice(sarray).Sort()
	joined := strings.Join(sarray, "&")
	payload := method + "\n" + host + "\n" + path + "\n" + joined
	hash := hmac.NewSHA256([]byte(auth.SecretKey))
	hash.Write([]byte(payload))
	signature := make([]byte, b64.EncodedLen(hash.Size()))
	b64.Encode(signature, hash.Sum())

	params["Signature"] = string(signature)
}
Beispiel #7
0
func sesGet(data url.Values) (string, os.Error) {
	data.Add("AWSAccessKeyId", accessKey)
	urlstr := fmt.Sprintf("%s?%s", endpoint, data.Encode())
	endpointURL, _ := url.Parse(urlstr)
	headers := map[string][]string{}

	now := time.UTC()
	date := now.Format("Mon, 02 Jan 2006 15:04:05 -0700")
	headers["Date"] = []string{date}

	h := hmac.NewSHA256([]uint8(secretKey))
	h.Write([]uint8(date))
	signature := base64.StdEncoding.EncodeToString(h.Sum())
	auth := fmt.Sprintf("AWS3-HTTPS AWSAccessKeyId=%s, Algorithm=HmacSHA256, Signature=%s", accessKey, signature)
	headers["X-Amzn-Authorization"] = []string{auth}

	req := http.Request{
		URL:        endpointURL,
		Method:     "GET",
		ProtoMajor: 1,
		ProtoMinor: 1,
		Close:      true,
		Header:     headers,
	}

	r, err := http.DefaultClient.Do(&req)
	if err != nil {
		return "", err
	}

	resultbody, _ := ioutil.ReadAll(r.Body)
	r.Body.Close()

	if r.StatusCode != 200 {
		return "", os.NewError(string(resultbody))
	}

	return string(resultbody), nil
}
Beispiel #8
0
func hash(valueStr string, key []byte) string {
	hasher := hmac.NewSHA256(key)
	hasher.Write([]byte(valueStr))
	return base64.StdEncoding.EncodeToString(hasher.Sum())
}
Beispiel #9
0
func HashPassword(password string) string {
	sha256 := hmac.NewSHA256(passwordHMACKey)
	sha256.Write([]byte(password))
	hmac := sha256.Sum()
	return textify(hmac)
}