Example #1
0
func (a authCookieSha1) HandleData(data []byte) ([]byte, AuthStatus) {
	challenge := make([]byte, len(data)/2)
	_, err := hex.Decode(challenge, data)
	if err != nil {
		return nil, AuthError
	}
	b := bytes.Split(challenge, []byte{' '})
	if len(b) != 3 {
		return nil, AuthError
	}
	context := b[0]
	id := b[1]
	svchallenge := b[2]
	cookie := a.getCookie(context, id)
	if cookie == nil {
		return nil, AuthError
	}
	clchallenge := a.generateChallenge()
	if clchallenge == nil {
		return nil, AuthError
	}
	hash := sha1.New()
	hash.Write(bytes.Join([][]byte{svchallenge, clchallenge, cookie}, []byte{':'}))
	hexhash := make([]byte, 2*hash.Size())
	hex.Encode(hexhash, hash.Sum(nil))
	data = append(clchallenge, ' ')
	data = append(data, hexhash...)
	resp := make([]byte, 2*len(data))
	hex.Encode(resp, data)
	return resp, AuthOk
}
Example #2
0
// String returns the UUID in it's canonical form, a 32 digit hexadecimal
// number in the form of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
func (u UUID) String() string {
	buf := [36]byte{8: '-', 13: '-', 18: '-', 23: '-'}
	hex.Encode(buf[0:], u[0:4])
	hex.Encode(buf[9:], u[4:6])
	hex.Encode(buf[14:], u[6:8])
	hex.Encode(buf[19:], u[8:10])
	hex.Encode(buf[24:], u[10:])
	return string(buf[:])
}
Example #3
0
// String prints an SID in the form used by MySQL 5.6.
func (sid SID) String() string {
	dst := []byte("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
	hex.Encode(dst, sid[:4])
	hex.Encode(dst[9:], sid[4:6])
	hex.Encode(dst[14:], sid[6:8])
	hex.Encode(dst[19:], sid[8:10])
	hex.Encode(dst[24:], sid[10:16])
	return string(dst)
}
Example #4
0
func (u UUID) Hex() string {
	buf := make([]byte, 32)

	hex.Encode(buf[0:8], u[0:4])
	hex.Encode(buf[8:12], u[4:6])
	hex.Encode(buf[12:16], u[6:8])
	hex.Encode(buf[16:20], u[8:10])
	hex.Encode(buf[20:], u[10:])
	return string(buf)
}
Example #5
0
func encodeHex(dst []byte, uuid UUID) {
	hex.Encode(dst[:], uuid[:4])
	dst[8] = '-'
	hex.Encode(dst[9:13], uuid[4:6])
	dst[13] = '-'
	hex.Encode(dst[14:18], uuid[6:8])
	dst[18] = '-'
	hex.Encode(dst[19:23], uuid[8:10])
	dst[23] = '-'
	hex.Encode(dst[24:], uuid[10:])
}
Example #6
0
// Returns canonical string representation of UUID:
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
func (u UUID) String() string {
	buf := make([]byte, 36)
	hex.Encode(buf[0:8], u[0:4])
	buf[8] = dash
	hex.Encode(buf[9:13], u[4:6])
	buf[13] = dash
	hex.Encode(buf[14:18], u[6:8])
	buf[18] = dash
	hex.Encode(buf[19:23], u[8:10])
	buf[23] = dash
	hex.Encode(buf[24:], u[10:])
	return string(buf)
}
Example #7
0
// Encode encodes UUID to "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" format.
func Encode(uuid UUID) []byte {
	buf := make([]byte, 36)
	hex.Encode(buf[:8], uuid[:4])
	buf[8] = '-'
	hex.Encode(buf[9:13], uuid[4:6])
	buf[13] = '-'
	hex.Encode(buf[14:18], uuid[6:8])
	buf[18] = '-'
	hex.Encode(buf[19:23], uuid[8:10])
	buf[23] = '-'
	hex.Encode(buf[24:], uuid[10:])
	return buf
}
Example #8
0
func Guidv4String() string {
	t := Guidv4()
	tmp := make([]byte, 36)
	hex.Encode(tmp[:8], t[:4])
	tmp[8] = '-'
	hex.Encode(tmp[9:], t[4:6])
	tmp[13] = '-'
	hex.Encode(tmp[14:], t[6:8])
	tmp[18] = '-'
	hex.Encode(tmp[19:], t[8:10])
	tmp[23] = '-'
	hex.Encode(tmp[24:], t[10:])
	return string(tmp)
}
Example #9
0
func toString(uuid []byte) string {
	buf := make([]byte, 36)

	hex.Encode(buf[0:8], uuid[0:4])
	buf[8] = '-'
	hex.Encode(buf[9:13], uuid[4:6])
	buf[13] = '-'
	hex.Encode(buf[14:18], uuid[6:8])
	buf[18] = '-'
	hex.Encode(buf[19:23], uuid[8:10])
	buf[23] = '-'
	hex.Encode(buf[24:], uuid[10:])

	return string(buf)
}
Example #10
0
// decodeUUIDBinary interprets the binary format of a uuid, returning it in text format.
func decodeUUIDBinary(src []byte) ([]byte, error) {
	if len(src) != 16 {
		return nil, fmt.Errorf("pq: unable to decode uuid; bad length: %d", len(src))
	}

	dst := make([]byte, 36)
	dst[8], dst[13], dst[18], dst[23] = '-', '-', '-', '-'
	hex.Encode(dst[0:], src[0:4])
	hex.Encode(dst[9:], src[4:6])
	hex.Encode(dst[14:], src[6:8])
	hex.Encode(dst[19:], src[8:10])
	hex.Encode(dst[24:], src[10:16])

	return dst, nil
}
Example #11
0
func noUnderLine(u uuid.UUID) string {
	buf := make([]byte, 36)

	hex.Encode(buf[0:8], u[0:4])
	//buf[8] = dash
	hex.Encode(buf[8:12], u[4:6])
	//buf[13] = dash
	hex.Encode(buf[12:16], u[6:8])
	//buf[18] = dash
	hex.Encode(buf[16:20], u[8:10])
	//buf[23] = dash
	hex.Encode(buf[20:], u[10:])

	return string(buf)
}
Example #12
0
File: user.go Project: kyf/compass
func (u *User) Check(adminName, adminPwd string) bool {
	sql := "select count(1) as num from `admin` where admin_name = '%s' and admin_pwd = '%s'"
	db, err := initDB()
	if err != nil {
		u.Logger.Fatalf("initDB ERR:%v", err)
	}
	bin := md5.Sum([]byte(adminPwd))
	tmp := make([]byte, 32)
	hex.Encode(tmp, bin[:])
	rows, err := db.Query(fmt.Sprintf(sql, adminName, string(tmp)))
	if err != nil {
		u.Logger.Printf("user check err: sql is %s, err is %v", sql, err)
		return false
	}

	if rows.Next() {
		var num int
		rows.Scan(&num)
		if num > 0 {
			return true
		} else {
			return false
		}
	} else {
		return false
	}
}
Example #13
0
// Generates an HMAC using SHA256
func GenerateMAC(message, key []byte) []byte {
	mac := hmac.New(sha256.New, key)
	mac.Write(message)
	ret := make([]byte, 64)
	hex.Encode(ret, mac.Sum(nil))
	return ret
}
Example #14
0
// trim(url_base64(json(token))) + "." + hex(hmac-sha256(base64_str))
func (token *Token) Decode(tokenBytes []byte) error {
	const signatureLen = 64 // hmac-sha256

	bytesArray := bytes.Split(tokenBytes, tokenBytesSplitSep)
	if len(bytesArray) < 2 {
		return errors.New("invalid token bytes")
	}

	// 验证签名
	signatrue := make([]byte, signatureLen)
	Hash := hmac.New(sha256.New, securitykey.Key)
	Hash.Write(bytesArray[0])
	hex.Encode(signatrue, Hash.Sum(nil))
	if !bytes.Equal(signatrue, bytesArray[1]) {
		return errors.New("invalid token bytes, signature mismatch")
	}

	// 解码
	temp := signatrue[:4]                       // signatrue 不再使用, 利用其空间
	copy(temp, tokenBytes[len(bytesArray[0]):]) // 保护 tokenBytes
	defer func() {
		copy(tokenBytes[len(bytesArray[0]):], temp) // 恢复 tokenBytes
		token.Signatrue = string(bytesArray[1])
	}()

	base64Bytes := base64Pad(bytesArray[0])
	base64Decoder := base64.NewDecoder(base64.URLEncoding, bytes.NewReader(base64Bytes))
	return json.NewDecoder(base64Decoder).Decode(token)
}
Example #15
0
// trim(url_base64(json(token))) + "." + hex(hmac-sha256(base64_str))
func (token *Token) Encode() ([]byte, error) {
	const signatureLen = 64 // hmac-sha256

	jsonBytes, err := json.Marshal(token)
	if err != nil {
		return nil, err
	}

	base64BytesLen := base64.URLEncoding.EncodedLen(len(jsonBytes))
	buf := make([]byte, base64BytesLen+1+signatureLen)

	base64Bytes := buf[:base64BytesLen]
	base64.URLEncoding.Encode(base64Bytes, jsonBytes)

	// 去掉 base64 编码尾部的 '='
	base64Bytes = base64Trim(base64Bytes)
	base64BytesLen = len(base64Bytes)
	signatureOffset := base64BytesLen + 1
	buf = buf[:signatureOffset+signatureLen]

	buf[base64BytesLen] = '.'

	signature := buf[signatureOffset:]
	Hash := hmac.New(sha256.New, securitykey.Key)
	Hash.Write(base64Bytes)
	hex.Encode(signature, Hash.Sum(nil))
	token.Signatrue = string(signature)

	return buf, nil
}
Example #16
0
func main() {
	var err error

	argParse()
	codec := collatejson.NewCodec(100)
	out := make([]byte, 0, len(options.inp)*3+collatejson.MinBufferSize)
	if options.encode {
		out, err = codec.Encode([]byte(options.inp), out)
		if err != nil {
			log.Fatal(err)
		}
		hexout := make([]byte, len(out)*5)
		n := hex.Encode(hexout, out)
		fmt.Printf("in : %q\n", options.inp)
		fmt.Printf("out: %q\n", string(out))
		fmt.Printf("hex: %q\n", string(hexout[:n]))

	} else if options.decode {
		inpbs := make([]byte, len(options.inp)*5)
		n, err := hex.Decode(inpbs, []byte(options.inp))
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(n, inpbs[:n])
		out, err = codec.Decode([]byte(inpbs[:n]), out)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("in : %q\n", options.inp)
		fmt.Printf("out: %q\n", string(out))
	}
}
Example #17
0
// 校验消息是否是从微信服务器发送过来的.
// 使用 buf 能提高一点性能 和 减少一些对 GC 的压力, buf 的长度最好 >=128
func _CheckSignature(signature, timestamp, nonce, token string, buf []byte) bool {
	const hashsumLen = 40 // sha1

	if len(signature) != hashsumLen {
		return false
	}

	bufLen := hashsumLen + len(timestamp) + len(nonce) + len(token)
	if len(buf) < bufLen {
		buf = make([]byte, hashsumLen, bufLen)
	} else {
		buf = buf[:hashsumLen]
	}

	strArray := sort.StringSlice{token, timestamp, nonce}
	strArray.Sort()

	buf = append(buf, strArray[0]...)
	buf = append(buf, strArray[1]...)
	buf = append(buf, strArray[2]...)

	hashsumArray := sha1.Sum(buf[hashsumLen:]) // require go1.2+

	hashsumHexBytes := buf[:hashsumLen]
	hex.Encode(hashsumHexBytes, hashsumArray[:])

	// 采用 subtle.ConstantTimeCompare 是防止 计时攻击!
	if rslt := subtle.ConstantTimeCompare(hashsumHexBytes, []byte(signature)); rslt == 1 {
		return true
	}
	return false
}
Example #18
0
File: time.go Project: bmatsuo/rex
// MarshalJSON implements json.Marshaller.
func (t *Time) MarshalJSON() ([]byte, error) {
	var x [18]byte
	x[0] = '"'
	hex.Encode(x[1:17], t.Bytes())
	x[17] = '"'
	return x[:], nil
}
Example #19
0
func (e *Engine) hex() error {
	b := e.stack.Pop()
	enc := make([]byte, hex.EncodedLen(len(b)))
	hex.Encode(enc, b)
	e.stack.Push(enc)
	return nil
}
Example #20
0
func signature(body string) string {
	dst := make([]byte, 40)
	computed := hmac.New(sha1.New, []byte(testSecret))
	computed.Write([]byte(body))
	hex.Encode(dst, computed.Sum(nil))
	return "sha1=" + string(dst)
}
Example #21
0
// 传统的签名代码, Sign 是优化后的代码, 要提高 35% 的速度
func Sign2(parameters map[string]string, apiKey string, fn func() hash.Hash) string {
	ks := make([]string, 0, len(parameters))
	for k := range parameters {
		if k == "sign" {
			continue
		}
		ks = append(ks, k)
	}
	sort.Strings(ks)

	if fn == nil {
		fn = md5.New
	}
	h := fn()
	signature := make([]byte, h.Size()*2)

	for _, k := range ks {
		v := parameters[k]
		if v == "" {
			continue
		}
		h.Write([]byte(k))
		h.Write([]byte{'='})
		h.Write([]byte(v))
		h.Write([]byte{'&'})
	}
	h.Write([]byte("key="))
	h.Write([]byte(apiKey))

	hex.Encode(signature, h.Sum(nil))
	return string(bytes.ToUpper(signature))
}
Example #22
0
// compareMAC reports whether expectedMAC is a valid HMAC tag for message.
func compareMAC(message, expectedMAC, key []byte) bool {
	mac := hmac.New(sha256.New, key)
	mac.Write(message)
	messageMAC := make([]byte, hex.EncodedLen(mac.Size()))
	hex.Encode(messageMAC, mac.Sum(nil))
	return subtle.ConstantTimeCompare(messageMAC, expectedMAC) == 1
}
Example #23
0
// 生成 native 支付 URL.
//  AppId:      必须, 公众号身份的唯一标识
//  AppKey:     必须, 即 paySignKey, 公众号支付请求中用于加密的密钥 Key
//  NonceStr:   必须, 32个字符以内, 商户生成的随机字符串
//  Timestamp:  必须, unixtime, 商户生成
//  ProductId:  必须, 32个字符以内, 商户需要定义并维护自己的商品id, 这个id与一张订单等价,
//              微信后台凭借该id通过POST商户后台获取交易必须信息;
//
//  NOTE: 该函数没有做 url escape, 因为正常情况下根本不需要做 url escape
func NativeURL(AppId, AppKey, NonceStr, Timestamp, ProductId string) string {
	Hash := sha1.New()
	hashsum := make([]byte, sha1.Size*2)

	// 字典序
	// appid
	// appkey
	// noncestr
	// productid
	// timestamp
	Hash.Write([]byte("appid="))
	Hash.Write([]byte(AppId))
	Hash.Write([]byte("&appkey="))
	Hash.Write([]byte(AppKey))
	Hash.Write([]byte("&noncestr="))
	Hash.Write([]byte(NonceStr))
	Hash.Write([]byte("&productid="))
	Hash.Write([]byte(ProductId))
	Hash.Write([]byte("&timestamp="))
	Hash.Write([]byte(Timestamp))

	hex.Encode(hashsum, Hash.Sum(nil))
	signature := string(hashsum)

	// weixin://wxpay/bizpayurl?sign=XXXXX&appid=XXXXXX&productid=XXXXXX
	// &timestamp=XXXXXX&noncestr=XXXXXX
	return "weixin://wxpay/bizpayurl?sign=" + signature +
		"&appid=" + AppId +
		"&productid=" + ProductId +
		"&timestamp=" + Timestamp +
		"&noncestr=" + NonceStr
}
Example #24
0
func (h *uploadHandler) baseHashes() (hashes string, err error) {
	op := h.op
	op.baseMD5 = make(map[string]string, len(op.patch))
	hash := md5.New()
	buf := make([]byte, 0, hash.Size()*4*len(op.patch))
	hexbuf := make([]byte, hash.Size()*2)
	for i, diff := range op.patch {
		if i > 0 {
			buf = append(buf, '|')
		}
		if diff.Op == Added {
			copy(hexbuf, "d41d8cd98f00b204e9800998ecf8427e")
		} else {
			base, err := op.delta.Base(diff.Path)
			if err != nil {
				return "", err
			}
			hash.Reset()
			_, err = io.Copy(hash, base)
			base.Close()
			if err != nil {
				return "", err
			}
			hex.Encode(hexbuf, hash.Sum(nil))
		}
		buf = append(buf, hexbuf...)
		buf = append(buf, ':')
		buf = append(buf, []byte(diff.Path)...)
		op.baseMD5[diff.Path] = string(hexbuf)
	}
	return string(buf), nil
}
Example #25
0
func (d *UUID) byte_text(t []byte) []byte {
	if len(t) < 36 {
		panic("UUID len too short")
	}
	hex.Encode(t[0:8], d[0:4])
	t[8] = '-'
	hex.Encode(t[9:13], d[4:6])
	t[13] = '-'
	hex.Encode(t[14:18], d[6:8])
	t[18] = '-'
	hex.Encode(t[19:23], d[8:10])
	t[23] = '-'
	hex.Encode(t[24:36], d[10:16])

	return t
}
Example #26
0
// MarshalJSON allows the representation in JSON of hexbytes
func (b HexBytes) MarshalJSON() ([]byte, error) {
	res := make([]byte, hex.EncodedLen(len(b))+2)
	res[0] = '"'
	res[len(res)-1] = '"'
	hex.Encode(res[1:], b)
	return res, nil
}
Example #27
0
// 对 parameters 里的参数做 MD5 签名.
// 签名方法:
// 1. 对参数 parameters 按照 key 的 ASCII 码从小到大排序(字典序)后,使用 URL 键值对的
// 格式(即 key1=value1&key2=value2...)拼接成字符串 string1,
// 注意:值为空的参数不参与签名;
// 2. 在 string1 最后拼接上 key=Key(商户支付密钥) 得到 stringSignTemp 字符串, 并对
// stringSignTemp 进行 md5 运算,再将得到的字符串所有字符转换为大写,得到 sign 值
// signValue。
//
//  parameters:  待签名的参数
//  Key:         支付签名的 Key
func MD5Signature(parameters map[string]string, Key string) (signature string) {
	keys := make([]string, 0, len(parameters))
	for key, value := range parameters {
		if value == "" { // 值为空不参加签名
			continue
		}
		if key == "sign" {
			continue
		}

		keys = append(keys, key)
	}
	sort.Strings(keys)

	Hash := md5.New()
	hashsum := make([]byte, md5.Size*2)

	for _, key := range keys {
		value := parameters[key]

		Hash.Write([]byte(key))
		Hash.Write([]byte{'='})
		Hash.Write([]byte(value))
		Hash.Write([]byte{'&'})
	}
	Hash.Write([]byte("key="))
	Hash.Write([]byte(Key))

	hex.Encode(hashsum, Hash.Sum(nil))
	signature = string(bytes.ToUpper(hashsum))
	return
}
Example #28
0
// ToWireMsg translates a ComposedMsg into a multipart ZMQ message ready to send, and
// signs it. This does not add the return identities or the delimiter.
func (msg ComposedMsg) ToWireMsg(signkey []byte) (msgparts [][]byte) {
	msgparts = make([][]byte, 5)
	header, _ := json.Marshal(msg.Header)
	msgparts[1] = header
	parent_header, _ := json.Marshal(msg.Parent_header)
	msgparts[2] = parent_header
	if msg.Metadata == nil {
		msg.Metadata = make(map[string]interface{})
	}
	metadata, _ := json.Marshal(msg.Metadata)
	msgparts[3] = metadata
	content, _ := json.Marshal(msg.Content)
	msgparts[4] = content

	// Sign the message
	if len(signkey) != 0 {
		mac := hmac.New(sha256.New, signkey)
		for _, msgpart := range msgparts[1:] {
			mac.Write(msgpart)
		}
		msgparts[0] = make([]byte, hex.EncodedLen(mac.Size()))
		hex.Encode(msgparts[0], mac.Sum(nil))
	}
	return
}
Example #29
0
File: token.go Project: thejerf/css
func cssEncodeHex(w io.Writer, b byte) error {
	h := make([]byte, 2)
	hex.Encode(h, []byte{b})
	_, _ = w.Write(h)
	_, err := w.Write([]byte(" "))
	return err
}
Example #30
0
// Value implements the driver.Valuer interface. It uses the "hex" format which
// is only supported on PostgreSQL 9.0 or newer.
func (a ByteaArray) Value() (driver.Value, error) {
	if a == nil {
		return nil, nil
	}

	if n := len(a); n > 0 {
		// There will be at least two curly brackets, 2*N bytes of quotes,
		// 3*N bytes of hex formatting, and N-1 bytes of delimiters.
		size := 1 + 6*n
		for _, x := range a {
			size += hex.EncodedLen(len(x))
		}

		b := make([]byte, size)

		for i, s := 0, b; i < n; i++ {
			o := copy(s, `,"\\x`)
			o += hex.Encode(s[o:], a[i])
			s[o] = '"'
			s = s[o+1:]
		}

		b[0] = '{'
		b[size-1] = '}'

		return string(b), nil
	}

	return "{}", nil
}