Example #1
0
func AuthenticateServer(conn net.Conn, secret []byte) os.Error {
	challenge := make([]byte, challengeLength)
	n, err := conn.Read(challenge)
	if err != nil {
		return err
	}
	challenge = challenge[:n]

	h := hmac.NewSHA1(secret)
	h.Write(challenge)
	_, err = conn.Write(h.Sum())
	if err != nil {
		return err
	}

	expectAck := []byte("OK")
	ack := make([]byte, len(expectAck))
	n, err = conn.Read(ack)
	if err != nil {
		return err
	}

	ack = ack[:n]
	if bytes.Compare(expectAck, ack) != 0 {
		fmt.Println(expectAck, ack)
		return os.NewError("Missing ack reply")
	}
	return nil
}
Example #2
0
func HashString(key []byte, hashThis string) string {
	// log.Println( "Hashing this string: ", hashThis )
	// log.Println( "SHA1 Key: ", key )
	sha1 := hmac.NewSHA1(key)
	sha1.Write([]byte(hashThis))
	return base64.StdEncoding.EncodeToString(sha1.Sum())
}
Example #3
0
// Calculates the HMAC-SHA1 signature of a base string, given a consumer and
// token secret.
func (s *HmacSha1Signer) GetSignature(consumerSecret string, tokenSecret string, signatureBase string) string {
	signingKey := consumerSecret + "&" + tokenSecret
	signer := hmac.NewSHA1([]byte(signingKey))
	signer.Write([]byte(signatureBase))
	oauthSignature := base64.StdEncoding.EncodeToString(signer.Sum())
	return oauthSignature
}
Example #4
0
func (y *Yubikey) genSig(params map[string]string) string {
	keys := make([]string, len(params))
	i := 0
	for k, _ := range params {
		keys[i] = k
		i++
	}
	sort.Strings(keys)

	buf := bytes.NewBuffer([]byte{})

	for i, key := range keys {
		buf.WriteString(key + "=" + params[key])
		if i != len(keys)-1 {
			buf.WriteString("&")
		}
	}

	h := hmac.NewSHA1(y.key)

	h.Write(buf.Bytes())

	rawSig := h.Sum()

	sig := make([]byte, base64.StdEncoding.EncodedLen(len(rawSig)))
	base64.StdEncoding.Encode(sig, rawSig)

	return string(sig)
}
Example #5
0
// setupKeys sets the cipher and MAC keys from kex.K, kex.H and sessionId, as
// described in RFC 4253, section 6.4. direction should either be serverKeys
// (to setup server->client keys) or clientKeys (for client->server keys).
func (c *common) setupKeys(d direction, K, H, sessionId []byte, hashFunc crypto.Hash) error {
	cipherMode := cipherModes[c.cipherAlgo]

	macKeySize := 20

	iv := make([]byte, cipherMode.ivSize)
	key := make([]byte, cipherMode.keySize)
	macKey := make([]byte, macKeySize)

	h := hashFunc.New()
	generateKeyMaterial(iv, d.ivTag, K, H, sessionId, h)
	generateKeyMaterial(key, d.keyTag, K, H, sessionId, h)
	generateKeyMaterial(macKey, d.macKeyTag, K, H, sessionId, h)

	c.mac = truncatingMAC{12, hmac.NewSHA1(macKey)}

	cipher, err := cipherMode.createCipher(key, iv)
	if err != nil {
		return err
	}

	c.cipher = cipher

	return nil
}
Example #6
0
func AuthenticateClient(conn net.Conn, secret []byte) os.Error {
	challenge := make([]byte, 0)
	for i := 0; i < challengeLength; i++ {
		challenge = append(challenge, byte(rand.Int31n(256)))
	}

	_, err := conn.Write(challenge)
	if err != nil {
		return err
	}

	h := hmac.NewSHA1(secret)
	_, err = h.Write(challenge)
	expected := h.Sum()
	response := make([]byte, len(expected))
	n, err := conn.Read(response)
	if err != nil {
		return err
	}
	response = response[:n]

	if bytes.Compare(response, expected) != 0 {
		log.Println("Authentication failure from", conn.RemoteAddr())
		return os.NewError("Mismatch in response")
	}
	conn.Write([]byte("OK"))
	return nil
}
Example #7
0
func getCookieSig(key string, val []byte, timestamp string) string {
	hm := hmac.NewSHA1([]byte(key))

	hm.Write(val)

	hex := fmt.Sprintf("%02x", hm.Sum([]byte(timestamp)))
	return hex
}
Example #8
0
func getCookieSig(val []byte, timestamp string) string {
	hm := hmac.NewSHA1([]byte(serverSecret))
	hm.Write(val)
	hm.Write([]byte(timestamp))

	hex := fmt.Sprintf("%02x", hm.Sum())
	return hex
}
Example #9
0
// Returns the signature to be used in the query string or Authorization header
func Signature(secret, toSign string) string {
	// Signature = Base64( HMAC-SHA1( UTF-8-Encoding-Of( YourSecretAccessKeyID, StringToSign ) ) );
	// Need to confirm what encoding go strings are when converted to []byte
	hmac := hmac.NewSHA1([]byte(secret))
	hmac.Write([]byte(toSign))

	return base64.StdEncoding.EncodeToString(hmac.Sum())
}
Example #10
0
// ----------------------------------------------------------------------------
// Mechanical Turk signing (http://goo.gl/wrzfn)
func sign(auth aws.Auth, service, method, timestamp string, params map[string]string) {
	payload := service + method + timestamp
	hash := hmac.NewSHA1([]byte(auth.SecretKey))
	hash.Write([]byte(payload))
	signature := make([]byte, b64.EncodedLen(hash.Size()))
	b64.Encode(signature, hash.Sum())

	params["Signature"] = string(signature)
}
Example #11
0
func signature(secret, key, expiration, value string) string {
	hm := hmac.NewSHA1([]byte(secret))
	io.WriteString(hm, key)
	hm.Write([]byte{0})
	io.WriteString(hm, expiration)
	hm.Write([]byte{0})
	io.WriteString(hm, value)
	return hex.EncodeToString(hm.Sum())
}
Example #12
0
func Digest(key string, m string) string {
	myhash := hmac.NewSHA1(strings.Bytes(key));
	myhash.Write(strings.Bytes(m));
	signature := bytes.TrimSpace(myhash.Sum());
	digest := make([]byte, base64.StdEncoding.EncodedLen(len(signature)));
	base64.StdEncoding.Encode(digest, signature);
	digest_str := strings.TrimSpace(bytes.NewBuffer(digest).String());
	return digest_str;
}
Example #13
0
func createSessionId(username string) string {
	hm := hmac.NewSHA1([]byte(ServerSecret))
	hm.Write([]byte(username))
	hm.Write([]byte(strconv.Itoa64(sessionIdCounter)))
	hm.Write([]byte(strconv.Itoa64(time.Seconds())))
	sessionIdCounter++
	hex := fmt.Sprintf("%02x", hm.Sum())
	return hex
}
Example #14
0
// macSHA1 returns a macFunction for the given protocol version.
func macSHA1(version uint16, key []byte) macFunction {
	if version == versionSSL30 {
		mac := ssl30MAC{
			h:   sha1.New(),
			key: make([]byte, len(key)),
		}
		copy(mac.key, key)
		return mac
	}
	return tls10MAC{hmac.NewSHA1(key)}
}
Example #15
0
func (s *SHA1Signer) Sign(message string, key string) string {
	if s.debug {
		fmt.Println("Signing:" + message)
		fmt.Println("Key:" + key)
	}
	hashfun := hmac.NewSHA1([]byte(key))
	hashfun.Write([]byte(message))
	rawsignature := hashfun.Sum()
	base64signature := make([]byte, base64.StdEncoding.EncodedLen(len(rawsignature)))
	base64.StdEncoding.Encode(base64signature, rawsignature)
	return string(base64signature)
}
Example #16
0
func sign(key string, str string, method string) ([]byte, os.Error) {
	var hash hash.Hash

	if method == "HMAC-SHA1" {
		hash = hmac.NewSHA1([]byte(key))
	} else {
		return nil, os.NewError(fmt.Sprintf("Unsupported signature method: %s", method))
	}

	hash.Write([]byte(str))

	return hash.Sum(), nil
}
Example #17
0
// digest Generates a HMAC-1234 for the signature
func (oc *OAuthConsumer) digest(key string, m string) string {
	h := hmac.NewSHA1([]byte(key))
	h.Write([]byte(m))
	return base64encode(h.Sum())

	/*	s := bytes.TrimSpace(h.Sum())
		d := make([]byte, base64.StdEncoding.EncodedLen(len(s)))
		base64.StdEncoding.Encode(d, s)
		ds := strings.TrimSpace(bytes.NewBuffer(d).String())
	*/
	//	return ds

}
Example #18
0
func sign(conn net.Conn, challenge []byte, secret []byte, local bool) []byte {
	h := hmac.NewSHA1(secret)
	h.Write(challenge)
	l := conn.LocalAddr()
	r := conn.RemoteAddr()
	connSignature := ""
	if local {
		connSignature = fmt.Sprintf("%v-%v", l, r)
	} else {
		connSignature = fmt.Sprintf("%v-%v", r, l)
	}
	h.Write([]byte(connSignature))
	return h.Sum()
}
Example #19
0
func signRequest(base string, consumerSecret string, tokenSecret string) string {
	signingKey := URLEscape(consumerSecret) + "&"
	if tokenSecret != "" {
		signingKey += URLEscape(tokenSecret)
	}
	hash := hmac.NewSHA1([]byte(signingKey))
	hash.Write([]byte(base))
	sum := hash.Sum()
	bb := new(bytes.Buffer)
	encoder := base64.NewEncoder(base64.StdEncoding, bb)
	encoder.Write(sum)
	encoder.Close()
	return bb.String()
}
Example #20
0
// Signs the Content
func signHandler(w http.ResponseWriter, r *http.Request) {
	dec := json.NewDecoder(r.Body)
	var data Signature
	dec.Decode(&data)
	keyBytes := []byte(data.Key)
	content := data.Content
	mac := hmac.NewSHA1(keyBytes)
	mac.Write([]byte(content))

	out := make([]byte, base64.StdEncoding.EncodedLen(len(mac.Sum())))
	base64.StdEncoding.Encode(out, mac.Sum())

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(&Signature{string(out), content, data.Key})
}
Example #21
0
func (a *Auth) SignRequest(req *http.Request) {
	if date := req.Header.Get("Date"); date == "" {
		req.Header.Set("Date", time.UTC().Format(http.TimeFormat))
	}
	hm := hmac.NewSHA1([]byte(a.SecretAccessKey))
	ss := stringToSign(req)
	io.WriteString(hm, ss)

	authHeader := new(bytes.Buffer)
	fmt.Fprintf(authHeader, "AWS %s:", a.AccessKey)
	encoder := base64.NewEncoder(base64.StdEncoding, authHeader)
	encoder.Write(hm.Sum())
	encoder.Close()
	req.Header.Set("Authorization", authHeader.String())
}
Example #22
0
func (o *OAuth) sign(request string) (string, os.Error) {
	key := o.signingKey()
	switch o.SignatureMethod {
	case HMAC_SHA1:
		hash := hmac.NewSHA1([]byte(key))
		hash.Write([]byte(request))
		signature := hash.Sum()
		digest := make([]byte, base64.StdEncoding.EncodedLen(len(signature)))
		base64.StdEncoding.Encode(digest, signature)
		return string(digest), nil
	}
	return "", &implementationError{
		What:  fmt.Sprintf("Unknown signature method (%d)", o.SignatureMethod),
		Where: "OAuth\xb7sign",
	}
}
Example #23
0
// signature returns the OAuth signature as described in section 3.4 of the RFC.
func signature(clientCredentials *Credentials, credentials *Credentials, method, url string, param web.ParamMap) string {
	var key bytes.Buffer

	key.Write(encode(clientCredentials.Secret, false))
	key.WriteByte('&')
	if credentials != nil {
		key.Write(encode(credentials.Secret, false))
	}

	h := hmac.NewSHA1(key.Bytes())
	writeBaseString(h, method, url, param)
	sum := h.Sum()

	encodedSum := make([]byte, base64.StdEncoding.EncodedLen(len(sum)))
	base64.StdEncoding.Encode(encodedSum, sum)
	return string(encodedSum)
}
Example #24
0
func (bucket *Bucket) Sign(req *http.Request) {
	// gather the string to be signed

	// method
	msg := req.Method + "\n"

	// md5sum
	if md5, present := req.Header["Content-MD5"]; present {
		msg += md5
	}
	msg += "\n"

	// content-type
	if contentType, present := req.Header["Content-Type"]; present {
		msg += contentType
	}
	msg += "\n"

	// date
	msg += req.Header["Date"] + "\n"

	// add headers
	for _, key := range AWS_HEADERS {
		if value, present := req.Header[key]; present {
			msg += key + ":" + value + "\n"
		}
	}

	// resource: the path components should be URL-encoded, but not the slashes
	resource := http.URLEscape("/" + bucket.bucket + req.URL.Path)
	resource = strings.Replace(resource, "%2f", "/", -1)
	msg += resource

	// create the signature
	hmac := hmac.NewSHA1([]byte(bucket.secret))
	hmac.Write([]byte(msg))

	// get a base64 encoding of the signature
	encoded := new(bytes.Buffer)
	encoder := base64.NewEncoder(base64.StdEncoding, encoded)
	encoder.Write(hmac.Sum())
	encoder.Close()
	signature := encoded.String()

	req.Header["Authorization"] = "AWS " + bucket.key + ":" + signature
}
Example #25
0
func (bucket *Bucket) sign(req *http.Request) {

	accessKeyId := bucket.Key
	secretAccessKey := bucket.Secret

	hmac := hmac.NewSHA1([]byte(secretAccessKey))

	// method
	msg := req.Method + "\n"

	// md5sum
	if md5, present := req.Header["Content-MD5"]; present {
		msg += md5
	}
	msg += "\n"

	// content-type
	if contentType, present := req.Header["Content-Type"]; present {
		msg += contentType
	}
	msg += "\n"

	// date
	msg += req.Header["Date"] + "\n"

	// write out first four
	hmac.Write([]byte(msg))

	// add headers
	rawpath := req.URL.Path
	path := strings.TrimLeft(rawpath, "/")
	// resource
	resource := "/" + bucket.MainBucket + "/" + path
	hmac.Write([]byte(resource))

	// get a base64 encoding of the signature
	encoded := new(bytes.Buffer)
	encoder := base64.NewEncoder(base64.StdEncoding, encoded)
	encoder.Write(hmac.Sum())
	encoder.Close()
	signature := encoded.String()

	req.Header["Authorization"] = "AWS " + accessKeyId + ":" + signature

}
Example #26
0
func (p *Propolis) SignRequest(req *http.Request) {
	// gather the string to be signed

	// method
	msg := req.Method + "\n"

	// md5sum
	msg += req.Header.Get("Content-MD5") + "\n"

	// content-type
	msg += req.Header.Get("Content-Type") + "\n"

	// date
	msg += req.Header.Get("Date") + "\n"

	// add headers
	for _, key := range AWS_HEADERS {
		if value := req.Header.Get(key); value != "" {
			msg += strings.ToLower(key) + ":" + value + "\n"
		}
	}

	// resource: the path components should be URL-encoded, but not the slashes
	u := new(url.URL)
	u.Path = "/" + p.Bucket + req.URL.Path
	msg += u.String()

	// create the signature
	hmac := hmac.NewSHA1([]byte(p.Secret))
	hmac.Write([]byte(msg))

	// get a base64 encoding of the signature
	var encoded bytes.Buffer
	encoder := base64.NewEncoder(base64.StdEncoding, &encoded)
	encoder.Write(hmac.Sum())
	encoder.Close()
	signature := encoded.String()

	req.Header.Set("Authorization", "AWS "+p.Key+":"+signature)
}
Example #27
0
// setupKeys sets the cipher and MAC keys from K, H and sessionId, as
// described in RFC 4253, section 6.4. direction should either be serverKeys
// (to setup server->client keys) or clientKeys (for client->server keys).
func (c *common) setupKeys(d direction, K, H, sessionId []byte, hashFunc crypto.Hash) os.Error {
	h := hashFunc.New()

	blockSize := 16
	keySize := 16
	macKeySize := 20

	iv := make([]byte, blockSize)
	key := make([]byte, keySize)
	macKey := make([]byte, macKeySize)
	generateKeyMaterial(iv, d.ivTag, K, H, sessionId, h)
	generateKeyMaterial(key, d.keyTag, K, H, sessionId, h)
	generateKeyMaterial(macKey, d.macKeyTag, K, H, sessionId, h)

	c.mac = truncatingMAC{12, hmac.NewSHA1(macKey)}
	aes, err := aes.NewCipher(key)
	if err != nil {
		return err
	}
	c.cipher = cipher.NewCTR(aes, iv)
	return nil
}
// CreateSignature generates a GDS authentication signature
func CreateSignature(verb string, body string, date string, uri string) string {
	var (
		signature string
		bodyHash  hash.Hash
		sigHmac   hash.Hash
	)

	// do an MD5 hash of the body
	bodyHash = md5.New()
	bodyHash.Write([]byte(body))

	// compute the signature value
	signature += verb + "\n"
	signature += string(bodyHash.Sum(nil)) + "\n"
	signature += date + "\n"
	signature += uri + "\n"

	// create the hmac
	sigHmac = hmac.NewSHA1([]byte("password"))
	sigHmac.Write([]byte(signature))

	return base64.StdEncoding.EncodeToString(sigHmac.Sum(nil))
}
Example #29
0
func hashCookie(data, secret string) (sum string) {
	var h hash.Hash = hmac.NewSHA1([]byte(secret))
	h.Write([]byte(data))
	return string(h.Sum())
}
Example #30
0
func hmacSHA1(key []byte) hash.Hash {
	return hmac.NewSHA1(key)
}