Esempio n. 1
0
func (c *conn) packRequest(r *http.Request) (*http.Request, error) {
	buf := &bytes.Buffer{}
	zbuf, err := zlib.NewWriterLevel(buf, zlib.BestCompression)
	if err != nil {
		return nil, fmt.Errorf("conn.packRequest(zlib.NewWriterLevel)>%s", err)
	}
	url := c.url + r.URL.String()
	urlhex := make([]byte, hex.EncodedLen(len(url)))
	hex.Encode(urlhex, []byte(url))
	fmt.Fprintf(zbuf, "url=%s", urlhex)
	fmt.Fprintf(zbuf, "&method=%s", hex.EncodeToString([]byte(r.Method)))
	if c.ps.password != "" {
		fmt.Fprintf(zbuf, "&password=%s", c.ps.password)
	}
	fmt.Fprint(zbuf, "&headers=")
	for k, v := range r.Header {
		fmt.Fprint(zbuf, hex.EncodeToString([]byte(fmt.Sprintf("%s:%s\r\n", k, v[0]))))
	}
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return nil, fmt.Errorf("conn.packRequest(ioutil.ReadAll(r.Body))>%s", err)
	}
	payload := hex.EncodeToString(body)
	fmt.Fprintf(zbuf, "&payload=%s", payload)
	zbuf.Close()
	req, err := http.NewRequest("POST", c.ps.path, buf)
	if err != nil {
		return nil, fmt.Errorf("conn.packRequest(http.NewRequest)>%s", err)
	}
	req.Host = c.ps.appid[rand.Intn(len(c.ps.appid))] + ".appspot.com"
	req.URL.Scheme = "http"
	return req, nil
}
Esempio n. 2
0
// Get the corresponding ID, which is the (hex encoded) SHA256 of the (base64 encoded) public key.
func (pk PublicKey) GetSHA256() []byte {
	h := sha256.New()
	h.Write([]byte(pk.String()))
	sha256hex := make([]byte, hex.EncodedLen(sha256.Size))
	hex.Encode(sha256hex, h.Sum(nil))
	return sha256hex
}
Esempio n. 3
0
func newSID() string {
	b := make([]byte, 8)
	rand.Read(b)
	d := make([]byte, hex.EncodedLen(len(b)))
	hex.Encode(d, b)
	return string(d)
}
Esempio n. 4
0
// Get the (hex-encoded) SHA256 of the String value of the ballot.
func (ballot *Ballot) GetSHA256() []byte {
	h := sha256.New()
	h.Write([]byte(ballot.String()))
	sha256hex := make([]byte, hex.EncodedLen(sha256.Size))
	hex.Encode(sha256hex, h.Sum(nil))
	return sha256hex
}
Esempio n. 5
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
}
Esempio n. 6
0
// Sign 微信支付签名.
//  params: 待签名的参数集合
//  apiKey: api密钥
//  fn:     func() hash.Hash, 如果为 nil 则默认用 md5.New
func Sign(params map[string]string, apiKey string, fn func() hash.Hash) string {
	if fn == nil {
		fn = md5.New
	}
	h := fn()
	bufw := bufio.NewWriterSize(h, 128)

	keys := make([]string, 0, len(params))
	for k := range params {
		if k == "sign" {
			continue
		}
		keys = append(keys, k)
	}
	sort.Strings(keys)

	for _, k := range keys {
		v := params[k]
		if v == "" {
			continue
		}
		bufw.WriteString(k)
		bufw.WriteByte('=')
		bufw.WriteString(v)
		bufw.WriteByte('&')
	}
	bufw.WriteString("key=")
	bufw.WriteString(apiKey)

	bufw.Flush()
	signature := make([]byte, hex.EncodedLen(h.Size()))
	hex.Encode(signature, h.Sum(nil))
	return string(bytes.ToUpper(signature))
}
Esempio n. 7
0
// 传统的签名代码, Sign 是优化后的代码, 要提高 30% 的速度
func Sign2(params map[string]string, apiKey string, fn func() hash.Hash) string {
	if fn == nil {
		fn = md5.New
	}
	h := fn()

	keys := make([]string, 0, len(params))
	for k := range params {
		if k == "sign" {
			continue
		}
		keys = append(keys, k)
	}
	sort.Strings(keys)

	for _, k := range keys {
		v := params[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))

	signature := make([]byte, hex.EncodedLen(h.Size()))
	hex.Encode(signature, h.Sum(nil))
	return string(bytes.ToUpper(signature))
}
Esempio n. 8
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
}
Esempio n. 9
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
}
Esempio n. 10
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
}
Esempio n. 11
0
File: ref.go Progetto: dchest/hesfic
func (ref *Ref) UnmarshalJSON(data []byte) error {
	if len(data) != hex.EncodedLen(RefLen)+2 {
		return errors.New("Ref of wrong length")
	}
	_, err := hex.Decode(ref[:], data[1:len(data)-1])
	return err
}
Esempio n. 12
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
}
Esempio n. 13
0
func TestEncodeConcatenatedHashes(t *testing.T) {
	// Input Hash slice. Data taken from Decred's first three mainnet blocks.
	hashSlice := []chainhash.Hash{
		decodeHash("298e5cc3d985bfe7f81dc135f360abe089edd4396b86d2de66b0cef42b21d980"),
		decodeHash("000000000000437482b6d47f82f374cde539440ddb108b0a76886f0d87d126b9"),
		decodeHash("000000000000c41019872ff7db8fd2e9bfa05f42d3f8fee8e895e8c1e5b8dcba"),
	}
	hashLen := hex.EncodedLen(len(hashSlice[0]))

	// Expected output. The string representations of the underlying byte arrays
	// in the input []chainhash.Hash
	blockHashes := []string{
		"80d9212bf4ceb066ded2866b39d4ed89e0ab60f335c11df8e7bf85d9c35c8e29",
		"b926d1870d6f88760a8b10db0d4439e5cd74f3827fd4b6827443000000000000",
		"badcb8e5c1e895e8e8fef8d3425fa0bfe9d28fdbf72f871910c4000000000000",
	}
	concatenatedHashes := strings.Join(blockHashes, "")

	// Test from 0 to N of the hashes
	for j := 0; j < len(hashSlice)+1; j++ {
		// Expected output string
		concatRef := concatenatedHashes[:j*hashLen]

		// Encode to string
		concatenated := dcrjson.EncodeConcatenatedHashes(hashSlice[:j])
		// Verify output
		if concatenated != concatRef {
			t.Fatalf("EncodeConcatenatedHashes failed (%v!=%v)",
				concatenated, concatRef)
		}
	}
}
Esempio n. 14
0
// jssdk 支付签名, signType 只支持 "MD5", "SHA1", 传入其他的值会 panic.
func JsapiSign(appId, timeStamp, nonceStr, packageStr, signType string, apiKey string) string {
	var h hash.Hash
	switch signType {
	case "MD5":
		h = md5.New()
	case "SHA1":
		h = sha1.New()
	default:
		panic("unsupported signType")
	}
	bufw := bufio.NewWriterSize(h, 128)

	// appId
	// nonceStr
	// package
	// signType
	// timeStamp
	bufw.WriteString("appId=")
	bufw.WriteString(appId)
	bufw.WriteString("&nonceStr=")
	bufw.WriteString(nonceStr)
	bufw.WriteString("&package=")
	bufw.WriteString(packageStr)
	bufw.WriteString("&signType=")
	bufw.WriteString(signType)
	bufw.WriteString("&timeStamp=")
	bufw.WriteString(timeStamp)
	bufw.WriteString("&key=")
	bufw.WriteString(apiKey)

	bufw.Flush()
	signature := make([]byte, hex.EncodedLen(h.Size()))
	hex.Encode(signature, h.Sum(nil))
	return string(bytes.ToUpper(signature))
}
Esempio n. 15
0
func getMd5(token, offset string) []byte {
	d5.Reset()
	d5.Write([]byte(token))
	src := d5.Sum([]byte(offset))
	dst := make([]byte, hex.EncodedLen(len(src)))
	hex.Encode(dst, src)
	return dst
}
Esempio n. 16
0
File: api.go Progetto: andrebq/exp
// String return the string representation of the value
func (kp KeyPrinter) PrintString(k Key) string {
	if k == nil {
		return ""
	}
	out := make([]byte, hex.EncodedLen(len(k.Bytes())))
	out = kp.Print(out, k)
	return string(out)
}
Esempio n. 17
0
func appendBytes(dst []byte, v []byte) []byte {
	tmp := make([]byte, hex.EncodedLen(len(v)))
	hex.Encode(tmp, v)

	dst = append(dst, "\\x"...)
	dst = append(dst, tmp...)
	return dst
}
Esempio n. 18
0
func appendBytes(dst []byte, src []byte) []byte {
	tmp := make([]byte, hex.EncodedLen(len(src)))
	hex.Encode(tmp, src)

	dst = append(dst, "'\\x"...)
	dst = append(dst, tmp...)
	dst = append(dst, '\'')
	return dst
}
Esempio n. 19
0
// Hex encode bytes
func (c *SCrypto) Hex(src []byte, maxLen int) []byte {
	dst := make([]byte, hex.EncodedLen(len(src)))
	hex.Encode(dst, src)
	if len(dst) > maxLen {
		// avoid extraneous padding
		dst = dst[:maxLen]
	}
	return dst
}
Esempio n. 20
0
// Generates a random, hex-encoded salt.
func generateSalt(saltBits int) (salt []byte, err error) {
	saltBytes, err := randomBits(saltBits)
	if err != nil {
		return
	}
	salt = make([]byte, hex.EncodedLen(len(saltBytes)))
	hex.Encode(salt, saltBytes)
	return
}
Esempio n. 21
0
func UIDFromString(s string) (UID, error) {
	if len(s) != hex.EncodedLen(UID_LEN) {
		return "", fmt.Errorf("Bad UID '%s'; must be %d bytes long", s, UID_LEN)
	}
	suffix := s[len(s)-2:]
	if suffix != UID_SUFFIX_HEX && suffix != UID_SUFFIX_2_HEX {
		return "", fmt.Errorf("Bad UID '%s': must end in 0x%x or 0x%x", s, UID_SUFFIX, UID_SUFFIX_2)
	}
	return UID(s), nil
}
Esempio n. 22
0
func DeviceIDFromString(s string) (DeviceID, error) {
	if len(s) != hex.EncodedLen(DeviceIDLen) {
		return "", fmt.Errorf("Bad Device ID length: %d", len(s))
	}
	suffix := s[len(s)-2:]
	if suffix != DeviceIDSuffixHex {
		return "", fmt.Errorf("Bad suffix byte: %s", suffix)
	}
	return DeviceID(s), nil
}
Esempio n. 23
0
File: flatfs.go Progetto: rht/bssim
func New(path string, prefixLen int) (*Datastore, error) {
	if prefixLen <= 0 || prefixLen > maxPrefixLen {
		return nil, ErrBadPrefixLen
	}
	fs := &Datastore{
		path: path,
		// convert from binary bytes to bytes of hex encoding
		hexPrefixLen: prefixLen * hex.EncodedLen(1),
	}
	return fs, nil
}
Esempio n. 24
0
func (p *AuthDbusCookieSha1) ProcessData(mesg []byte) ([]byte, error) {
	decodedLen, err := hex.Decode(mesg, mesg)
	if err != nil {
		return nil, err
	}
	mesgTokens := bytes.SplitN(mesg[:decodedLen], []byte(" "), 3)

	file, err := os.Open(os.Getenv("HOME") + "/.dbus-keyrings/" + string(mesgTokens[0]))
	if err != nil {
		return nil, err
	}
	defer file.Close()
	fileStream := bufio.NewReader(file)

	var cookie []byte
	for {
		line, _, err := fileStream.ReadLine()
		if err == io.EOF {
			return nil, errors.New("SHA1 Cookie not found")
		} else if err != nil {
			return nil, err
		}
		cookieTokens := bytes.SplitN(line, []byte(" "), 3)
		if bytes.Compare(cookieTokens[0], mesgTokens[1]) == 0 {
			cookie = cookieTokens[2]
			break
		}
	}

	challenge := make([]byte, len(mesgTokens[2]))
	if _, err = rand.Read(challenge); err != nil {
		return nil, err
	}

	for temp := challenge; ; {
		if index := bytes.IndexAny(temp, " \t"); index == -1 {
			break
		} else if _, err := rand.Read(temp[index : index+1]); err != nil {
			return nil, err
		} else {
			temp = temp[index:]
		}
	}

	hash := sha1.New()
	if _, err := hash.Write(bytes.Join([][]byte{mesgTokens[2], challenge, cookie}, []byte(":"))); err != nil {
		return nil, err
	}

	resp := bytes.Join([][]byte{challenge, []byte(hex.EncodeToString(hash.Sum(nil)))}, []byte(" "))
	respHex := make([]byte, hex.EncodedLen(len(resp)))
	hex.Encode(respHex, resp)
	return append([]byte("DATA "), respHex...), nil
}
Esempio n. 25
0
func ExampleEncode() {
	src := []byte("Hello Gopher!")

	dst := make([]byte, hex.EncodedLen(len(src)))
	hex.Encode(dst, src)

	fmt.Printf("%s\n", dst)

	// Output:
	// 48656c6c6f20476f7068657221
}
Esempio n. 26
0
File: ref.go Progetto: dchest/hesfic
func RefFromHex(b []byte) *Ref {
	if len(b) != hex.EncodedLen(RefLen) {
		return nil
	}
	var r Ref
	_, err := hex.Decode(r[:], b)
	if err != nil {
		return nil
	}
	return &r
}
Esempio n. 27
0
func DigestPublicModulus(pub *rsa.PublicKey) [32]byte {
	dst := make([]byte, hex.EncodedLen(len(pub.N.Bytes())))
	hex.Encode(dst, pub.N.Bytes())
	// need the digest in uppercase
	for i, c := range dst {
		if c >= 'a' /* && c <= 'f' */ {
			dst[i] = c - 'a' + 'A'
		}
	}
	sum := sha256.Sum256(dst)
	return sum
}
Esempio n. 28
0
func (e encoder) Encode(v interface{}) error {
	slice, ok := v.([]byte)
	if !ok {
		return base.ErrExpectedByteSlice
	}

	buf := make([]byte, hex.EncodedLen(len(slice)))
	hex.Encode(buf, slice)

	_, err := e.w.Write(buf)
	return err
}
Esempio n. 29
0
func SigIDFromString(s string, suffix bool) (SigID, error) {
	blen := SIG_ID_LEN
	if suffix {
		blen++
	}
	if len(s) != hex.EncodedLen(blen) {
		return "", fmt.Errorf("Invalid SigID string length: %d, expected %d (suffix = %v)", len(s), hex.EncodedLen(blen), suffix)
	}
	if suffix {
		return SigID(s), nil
	}
	return SigID(fmt.Sprintf("%s%02x", s, SIG_ID_SUFFIX)), nil
}
Esempio n. 30
0
func (g *generator) Next() []byte {
	var result = make([]byte, 5)
	_, err := rand.Read(result)
	if err != nil {
		panic(err)
	}

	var dst = make([]byte, hex.EncodedLen(len(result)))

	hex.Encode(dst, result)

	return dst
}