当前位置: 首页>>代码示例>>Golang>>正文


Golang hash.Hash类代码示例

本文整理汇总了Golang中hash.Hash的典型用法代码示例。如果您正苦于以下问题:Golang Hash类的具体用法?Golang Hash怎么用?Golang Hash使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Hash类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: verifyChecksum

// verifyChecksum computes the hash of a file and compares it
// to a checksum. If comparison fails, it returns an error.
func verifyChecksum(fd *os.File, checksum string) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("verifyChecksum() -> %v", e)
		}
	}()
	var h hash.Hash
	h = sha256.New()
	buf := make([]byte, 4096)
	var offset int64 = 0
	for {
		block, err := fd.ReadAt(buf, offset)
		if err != nil && err != io.EOF {
			panic(err)
		}
		if block == 0 {
			break
		}
		h.Write(buf[:block])
		offset += int64(block)
	}
	hexhash := fmt.Sprintf("%x", h.Sum(nil))
	if hexhash != checksum {
		return fmt.Errorf("Checksum validation failed. Got '%s', Expected '%s'.",
			hexhash, checksum)
	}
	return
}
开发者ID:tudalex,项目名称:mig,代码行数:30,代码来源:upgrade.go

示例2: Iterated

// Iterated writes to out the result of computing the Iterated and Salted S2K
// function (RFC 4880, section 3.7.1.3) using the given hash, input passphrase,
// salt and iteration count.
func Iterated(out []byte, h hash.Hash, in []byte, salt []byte, count int) {
	combined := make([]byte, len(in)+len(salt))
	copy(combined, salt)
	copy(combined[len(salt):], in)

	if count < len(combined) {
		count = len(combined)
	}

	done := 0
	var digest []byte
	for i := 0; done < len(out); i++ {
		h.Reset()
		for j := 0; j < i; j++ {
			h.Write(zero[:])
		}
		written := 0
		for written < count {
			if written+len(combined) > count {
				todo := count - written
				h.Write(combined[:todo])
				written = count
			} else {
				h.Write(combined)
				written += len(combined)
			}
		}
		digest = h.Sum(digest[:0])
		n := copy(out[done:], digest)
		done += n
	}
}
开发者ID:postfix,项目名称:name_pending,代码行数:35,代码来源:s2k.go

示例3: RefFromHash

// RefFromHash returns a blobref representing the given hash.
// It panics if the hash isn't of a known type.
func RefFromHash(h hash.Hash) Ref {
	meta, ok := metaFromType[reflect.TypeOf(h)]
	if !ok {
		panic(fmt.Sprintf("Currently-unsupported hash type %T", h))
	}
	return Ref{meta.ctor(h.Sum(nil))}
}
开发者ID:JayBlaze420,项目名称:camlistore,代码行数:9,代码来源:ref.go

示例4: authenticateMessage

// Returns true if the provided message is unsigned or has a valid signature
// from one of the provided signers.
func authenticateMessage(signers map[string]Signer, header *Header, msg []byte) bool {
	digest := header.GetHmac()
	if digest != nil {
		var key string
		signer := fmt.Sprintf("%s_%d", header.GetHmacSigner(),
			header.GetHmacKeyVersion())
		if s, ok := signers[signer]; ok {
			key = s.HmacKey
		} else {
			return false
		}

		var hm hash.Hash
		switch header.GetHmacHashFunction() {
		case Header_MD5:
			hm = hmac.New(md5.New, []byte(key))
		case Header_SHA1:
			hm = hmac.New(sha1.New, []byte(key))
		}
		hm.Write(msg)
		expectedDigest := hm.Sum(nil)
		if subtle.ConstantTimeCompare(digest, expectedDigest) != 1 {
			return false
		}
	}
	return true
}
开发者ID:RogerBai,项目名称:heka,代码行数:29,代码来源:net_utils.go

示例5: LoadPost

func LoadPost(ctx *web.Context, val string) {
	username := ctx.Params["username"]
	password := ctx.Params["password"]

	salt := strconv.Itoa64(time.Nanoseconds()) + username

	var h hash.Hash = sha256.New()
	h.Write([]byte(password + salt))

	s, _err := conn.Prepare("INSERT INTO users VALUES(NULL, ?, ?, ?)")
	utils.ReportErr(_err)

	s.Exec(username, string(h.Sum()), salt)
	s.Finalize()
	conn.Close()
	sidebar := utils.Loadmustache("admin.mustache", &map[string]string{})

	//TESTING, REMOVE LATER
	script := "<script type=\"text/javascript\" src=\"../inc/adminref.js\"></script>"
	content := "Welcome to the admin panel, use the control box on your right to control the site content"
	//ENDTESTING

	mapping := map[string]string{"css": "../inc/site.css",
		"title":   "Proggin: Admin panel",
		"sidebar": sidebar,
		"content": content,
		"script":  script}

	output := utils.Loadmustache("frame.mustache", &mapping)
	ctx.WriteString(output)
}
开发者ID:Chownie,项目名称:Proggin,代码行数:31,代码来源:newuser.go

示例6: PutObject

func (c *Client) PutObject(name, bucket string, md5 hash.Hash, size int64, body io.Reader) error {
	req := newReq("http://" + bucket + ".s3.amazonaws.com/" + name)
	req.Method = "PUT"
	req.ContentLength = size
	if md5 != nil {
		b64 := new(bytes.Buffer)
		encoder := base64.NewEncoder(base64.StdEncoding, b64)
		encoder.Write(md5.Sum(nil))
		encoder.Close()
		req.Header.Set("Content-MD5", b64.String())
	}
	c.Auth.SignRequest(req)
	req.Body = ioutil.NopCloser(body)

	res, err := c.httpClient().Do(req)
	if res != nil && res.Body != nil {
		defer res.Body.Close()
	}
	if err != nil {
		return err
	}
	if res.StatusCode != 200 {
		res.Write(os.Stderr)
		return fmt.Errorf("Got response code %d from s3", res.StatusCode)
	}
	return nil
}
开发者ID:JayBlaze420,项目名称:camlistore,代码行数:27,代码来源:client.go

示例7: finishEAX

func finishEAX(tag []byte, cmac hash.Hash) {
	// Finish CMAC #2 and xor into tag.
	sum := cmac.Sum()
	for i := range tag {
		tag[i] ^= sum[i]
	}
}
开发者ID:rapgamer,项目名称:golang-china,代码行数:7,代码来源:eax.go

示例8: filehash

func filehash(h hash.Hash, r io.Reader) ([]byte, error) {
	defer h.Reset()
	if _, err := io.Copy(h, r); err != nil {
		return nil, err
	}
	return h.Sum(nil), nil
}
开发者ID:dullgiulio,项目名称:empa,代码行数:7,代码来源:main.go

示例9: TestKeccak

func TestKeccak(t *testing.T) {
	for i := range tests {
		var h hash.Hash

		switch tests[i].length {
		case 28:
			h = New224()
		case 32:
			h = New256()
		case 48:
			h = New384()
		case 64:
			h = New512()
		default:
			panic("invalid testcase")
		}

		h.Write(tests[i].input)

		d := h.Sum(nil)
		if !bytes.Equal(d, tests[i].output) {
			t.Errorf("testcase %d: expected %x got %x", i, tests[i].output, d)
		}
	}
}
开发者ID:ebfe,项目名称:keccak,代码行数:25,代码来源:keccak_test.go

示例10: FileMD5

// Compute md5 for given file
// Test is Test_005
func FileMD5(fname string) (string, error) {
	//fmt.Printf("Computing digest for %s\n",fname)
	const NBUF = 1 << 20 // 20 -> 1 MB
	file, err := os.OpenFile(fname, os.O_RDONLY, 0666)
	if file == nil {
		fmt.Printf("!Err--> mdr.FileMD5() can't open file %s as readonly; err=%v\n", fname, err)
		return "", err
	}
	defer file.Close()
	buf := make([]byte, NBUF)
	var h hash.Hash = md5.New()
	for {
		numRead, err := file.Read(buf)
		if (err == io.EOF) && (numRead == 0) {
			break
		} // end of file reached
		if (err != nil) || (numRead < 0) {
			fmt.Fprintf(os.Stderr, "!Err--> mdr.FileMD5: error reading from %s: %v\n", fname, err)
			return "", err
		}
		//		fmt.Printf("read(%d) bytes\n",numRead)
		h.Write(buf[0:numRead])
	}
	digest := h.Sum(nil)
	rv := DigestToString(digest)
	//fmt.Printf("%s digest ->%s\n",fname,rv)
	return string(rv), nil
}
开发者ID:hotei,项目名称:mdr,代码行数:30,代码来源:mdr_hash.go

示例11: checkMAC

func checkMAC(mac hash.Hash, message, messageMAC []byte) bool {
	if _, err := mac.Write(message); err != nil {
		return false
	}
	expectedMAC := mac.Sum(nil)
	return hmac.Equal(messageMAC, expectedMAC)
}
开发者ID:judwhite,项目名称:ghapi,代码行数:7,代码来源:hooks.go

示例12: BufSHA256

func BufSHA256(buf []byte) string {
	var h hash.Hash = sha256.New()
	h.Write(buf[:])
	digest := h.Sum(nil)
	//fmt.Printf("%s digest ->%s\n",fname,rv)
	return DigestToString(digest)
}
开发者ID:hotei,项目名称:mdr,代码行数:7,代码来源:mdr_hash.go

示例13: ParseBlob

// Initialize manifest from BLOB
func (s *Manifest) ParseBlob(in io.Reader, chunkSize int64) (err error) {
	var chunkHasher hash.Hash
	var w io.Writer
	var chunk Chunk
	hasher := sha3.New256()
	var written int64

	for {
		chunk = Chunk{
			Offset: s.Size,
		}
		chunkHasher = sha3.New256()
		w = io.MultiWriter(hasher, chunkHasher)
		written, err = io.CopyN(w, in, chunkSize)
		s.Size += written
		chunk.Size = written
		chunk.ID = ID(hex.EncodeToString(chunkHasher.Sum(nil)))
		s.Chunks = append(s.Chunks, chunk)

		if err == io.EOF {
			err = nil
			break
		} else if err != nil {
			return
		}
	}
	s.ID = ID(hex.EncodeToString(hasher.Sum(nil)))
	return
}
开发者ID:pombredanne,项目名称:bar,代码行数:30,代码来源:manifest.go

示例14: Fingerprint

// Return the fingerprint of the key in a raw format.
func Fingerprint(pub *SSHPublicKey, hashalgo crypto.Hash) (fpr []byte, err error) {
	var h hash.Hash

	// The default algorithm for OpenSSH appears to be MD5.
	if hashalgo == 0 {
		hashalgo = crypto.MD5
	}

	switch hashalgo {
	case crypto.MD5:
		h = md5.New()
	case crypto.SHA1:
		h = sha1.New()
	case crypto.SHA256:
		h = sha256.New()
	default:
		return nil, ErrInvalidDigest
	}

	blob, err := publicToBlob(pub)
	if err != nil {
		return nil, err
	}
	h.Write(blob)

	return h.Sum(nil), nil
}
开发者ID:postfix,项目名称:sshkey,代码行数:28,代码来源:sshkey.go

示例15: Ripemd

//TODO: test and add to tests
//RIPEMD-160 operation for bitcoin address hashing
func Ripemd(b []byte) []byte {
	//ripemd hashing of the sha hash
	var h hash.Hash = ripemd160.New()
	h.Write(b)

	return h.Sum(nil) //return
}
开发者ID:ThePiachu,项目名称:Split-Vanity-Miner-Golang,代码行数:9,代码来源:hashing.go


注:本文中的hash.Hash类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。