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


Golang hash.Sum函数代码示例

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


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

示例1: calcAes30Params

// Calculates the key and iv for AES decryption given a password and salt.
func calcAes30Params(pass []uint16, salt []byte) (key, iv []byte) {
	p := make([]byte, 0, len(pass)*2+len(salt))
	for _, v := range pass {
		p = append(p, byte(v), byte(v>>8))
	}
	p = append(p, salt...)

	hash := sha1.New()
	iv = make([]byte, 16)
	s := make([]byte, 0, hash.Size())
	for i := 0; i < hashRounds; i++ {
		hash.Write(p)
		hash.Write([]byte{byte(i), byte(i >> 8), byte(i >> 16)})
		if i%(hashRounds/16) == 0 {
			s = hash.Sum(s[:0])
			iv[i/(hashRounds/16)] = s[4*4+3]
		}
	}
	key = hash.Sum(s[:0])
	key = key[:16]

	for k := key; len(k) >= 4; k = k[4:] {
		k[0], k[1], k[2], k[3] = k[3], k[2], k[1], k[0]
	}
	return key, iv
}
开发者ID:shazow,项目名称:mog,代码行数:27,代码来源:archive15.go

示例2: PBKDF2

// An implementation of PBKDF2 (Password-Based Key Derivation Function 2) as
// specified in PKCS #5 v2.0 from RSA Laboratorie and in `RFC 2898
// <http://www.ietf.org/rfc/rfc2898.txt>`.
func PBKDF2(hashfunc func([]byte) hash.Hash, password, salt []byte, iterations, keylen int) (key []byte) {

	var (
		digest          []byte
		i, j, k, length int
	)

	key = make([]byte, keylen)
	slice := key

	hash := hashfunc(password)
	hashlen := hash.Size()
	scratch := make([]byte, 4)

	for keylen > 0 {

		if hashlen > keylen {
			length = keylen
		} else {
			length = hashlen
		}

		i += 1

		scratch[0] = byte(i >> 24)
		scratch[1] = byte(i >> 16)
		scratch[2] = byte(i >> 8)
		scratch[3] = byte(i)

		hash.Write(salt)
		hash.Write(scratch)

		digest = hash.Sum()
		hash.Reset()

		for j = 0; j < length; j++ {
			slice[j] = digest[j]
		}

		for k = 1; k < iterations; k++ {
			hash.Write(digest)
			digest = hash.Sum()
			for j = 0; j < length; j++ {
				slice[j] ^= digest[j]
			}
			hash.Reset()
		}

		keylen -= length
		slice = slice[length:]

	}

	return

}
开发者ID:gitreview,项目名称:ampify,代码行数:59,代码来源:crypto.go

示例3: Encode

// Encode encodes the given byte slice and returns a token.
func (tok *T) Encode(data []byte) (token []byte, err error) {
	if data == nil {
		data = []byte{}
	}
	body := make([]byte, 4+len(data))
	now := uint32(time.Now().UTC().Unix())
	binary.BigEndian.PutUint32(body, now)
	copy(body[4:], data)
	body, err = pkcs7Pad(body, aes.BlockSize)
	if err != nil {
		return nil, err
	}
	iv := NewKey(aes.BlockSize)
	mode := cipher.NewCBCEncrypter(tok.aes, iv)
	mode.CryptBlocks(body, body)
	hash := tok.hmac()
	// size = len(iv + aesblocks + signature)
	token = make([]byte, len(iv)+len(body)+hash.Size())
	copy(token, iv)
	offset := len(iv)
	copy(token[offset:], body)
	offset += len(body)
	hash.Write(token[:offset])
	copy(token[offset:], hash.Sum(nil))
	b := make([]byte, base64.RawURLEncoding.EncodedLen(len(token)))
	base64.RawURLEncoding.Encode(b, token)
	return b, nil
}
开发者ID:go-web,项目名称:tokenizer,代码行数:29,代码来源:token.go

示例4: Hash

func Hash(fileName string, newHash func() hash.Hash) ([]byte, error) {
	hash := newHash()

	file, err := os.Open(fileName)
	if err != nil {
		return nil, common.TraceError(err)
	}
	defer file.Close()

	temp := make([]byte, 4096)

	for {
		nn, err := file.Read(temp)
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, common.TraceError(err)
		}

		hash.Write(temp[0:nn])
	}

	return hash.Sum(nil), nil
}
开发者ID:NatTuck,项目名称:defunct-fogsync,代码行数:25,代码来源:crypto.go

示例5: ObjectPut

// ObjectPut creates or updates the path in the container from
// contents.  contents should be an open io.Reader which will have all
// its contents read.
//
// This is a low level interface.
//
// If checkHash is True then it will calculate the MD5 Hash of the
// file as it is being uploaded and check it against that returned
// from the server.  If it is wrong then it will return
// ObjectCorrupted.
//
// If you know the MD5 hash of the object ahead of time then set the
// Hash parameter and it will be sent to the server (as an Etag
// header) and the server will check the MD5 itself after the upload,
// and this will return ObjectCorrupted if it is incorrect.
//
// If you don't want any error protection (not recommended) then set
// checkHash to false and Hash to "".
//
// If contentType is set it will be used, otherwise one will be
// guessed from objectName using mime.TypeByExtension
func (c *Connection) ObjectPut(container string, objectName string, contents io.Reader, checkHash bool, Hash string, contentType string, h Headers) (headers Headers, err error) {
	extraHeaders := objectPutHeaders(objectName, &checkHash, Hash, contentType, h)
	hash := md5.New()
	var body io.Reader = contents
	if checkHash {
		body = io.TeeReader(contents, hash)
	}
	_, headers, err = c.storage(RequestOpts{
		Container:  container,
		ObjectName: objectName,
		Operation:  "PUT",
		Headers:    extraHeaders,
		Body:       body,
		NoResponse: true,
		ErrorMap:   objectErrorMap,
	})
	if err != nil {
		return
	}
	if checkHash {
		receivedMd5 := strings.ToLower(headers["Etag"])
		calculatedMd5 := fmt.Sprintf("%x", hash.Sum(nil))
		if receivedMd5 != calculatedMd5 {
			err = ObjectCorrupted
			return
		}
	}
	return
}
开发者ID:joeshaw,项目名称:swift,代码行数:50,代码来源:swift.go

示例6: calculateHashes

func calculateHashes(filename string, pkg *types.Package) {
	var (
		writers []io.Writer
		hashes  []hash.Hash
	)

	push := func(h hash.Hash) {
		writers = append(writers, h)
		hashes = append(hashes, h)
	}

	push(sha256.New())
	push(sha1.New())

	in, err := os.Open(filename)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	io.Copy(io.MultiWriter(writers...), in)

	formatHash := func(hash hash.Hash) string {
		return base64.StdEncoding.EncodeToString(hash.Sum(nil))
	}

	pkg.Sha256Sum = formatHash(hashes[0])
	pkg.Sha1Sum = formatHash(hashes[1])
}
开发者ID:philips,项目名称:core-admin,代码行数:29,代码来源:new-version.go

示例7: calculateHash

func calculateHash(values url.Values, path string) string {
	hash := sha1.New()
	hash.Write([]byte(path))
	hash.Write([]byte{0x00})
	if len(values) > 0 {
		if len(values) == 1 {
			for key, value := range values {
				hash.Write([]byte(key))
				hash.Write([]byte{0x00})
				addSortedKeys(value, hash)
			}
		} else {
			urlValues := make(UrlValueSlice, 0, len(values))
			for key, value := range values {
				urlValue := new(UrlValue)
				urlValue.Key = key
				urlValue.Values = value
				urlValues = append(urlValues, urlValue)
			}
			sort.Sort(urlValues)
			for _, sortedUrlValue := range urlValues {
				hash.Write([]byte(sortedUrlValue.Key))
				hash.Write([]byte{0x00})
				addSortedKeys(sortedUrlValue.Values, hash)
			}
		}
	}
	return string(hash.Sum([]byte{0x00}))
}
开发者ID:davidwilliamson,项目名称:mocker,代码行数:29,代码来源:endpoint.go

示例8: Md5sum

// Md5sum calculates the Md5sum of a file returning a lowercase hex string
func (o *FsObjectLocal) Md5sum() (string, error) {
	if o.md5sum != "" {
		return o.md5sum, nil
	}
	in, err := os.Open(o.path)
	if err != nil {
		fs.Stats.Error()
		fs.ErrorLog(o, "Failed to open: %s", err)
		return "", err
	}
	hash := md5.New()
	_, err = io.Copy(hash, in)
	closeErr := in.Close()
	if err != nil {
		fs.Stats.Error()
		fs.ErrorLog(o, "Failed to read: %s", err)
		return "", err
	}
	if closeErr != nil {
		fs.Stats.Error()
		fs.ErrorLog(o, "Failed to close: %s", closeErr)
		return "", closeErr
	}
	o.md5sum = hex.EncodeToString(hash.Sum(nil))
	return o.md5sum, nil
}
开发者ID:X1011,项目名称:rclone,代码行数:27,代码来源:local.go

示例9: signPayload

func signPayload(payload, secret string, hashFunc func() hash.Hash) string {
	hash := hmac.New(hashFunc, []byte(secret))
	hash.Write([]byte(payload))
	signature := make([]byte, b64.EncodedLen(hash.Size()))
	b64.Encode(signature, hash.Sum(nil))
	return string(signature)
}
开发者ID:ibmendoza,项目名称:dgtk,代码行数:7,代码来源:s3.go

示例10: Digest

// Compute an SHA256 digest for a string.
func Digest(data string) string {
	hash := crypto.SHA256.New()
	if _, err := hash.Write([]byte(data)); err != nil {
		panic("Writing to a hash should never fail")
	}
	return hex.EncodeToString(hash.Sum())
}
开发者ID:emk,项目名称:cstore,代码行数:8,代码来源:digest.go

示例11: Verify

func (cri *checksummedReaderImpl) Verify() (bool, error) {
	originalOffset, err := cri.delegate.Seek(0, 1)
	if err != nil {
		return false, err
	}
	if cri.checksumOffset > 0 {
		_, err = cri.delegate.Seek(-int64(cri.checksumOffset), 1)
		if err != nil {
			return false, err
		}
	}
	block := make([]byte, cri.checksumInterval+4)
	checksum := block[cri.checksumInterval:]
	_, err = io.ReadFull(cri.delegate, block)
	if err != nil {
		return false, err
	}
	block = block[:cri.checksumInterval]
	hash := cri.newHash()
	hash.Write(block)
	verified := bytes.Equal(checksum, hash.Sum(cri.checksum[:0]))
	_, err = cri.delegate.Seek(originalOffset, 0)
	if err != nil {
		return verified, err
	}
	return verified, nil
}
开发者ID:getcfs,项目名称:cfs-binary-release,代码行数:27,代码来源:checksummedio.go

示例12: hashForClientCertificate

// hashForClientCertificate returns a digest, hash function, and TLS 1.2 hash
// id suitable for signing by a TLS client certificate.
func (h finishedHash) hashForClientCertificate(signatureAndHash signatureAndHash, masterSecret []byte) ([]byte, crypto.Hash, error) {
	if (h.version == VersionSSL30 || h.version >= VersionTLS12) && h.buffer == nil {
		panic("a handshake hash for a client-certificate was requested after discarding the handshake buffer")
	}

	if h.version == VersionSSL30 {
		if signatureAndHash.signature != signatureRSA {
			return nil, 0, errors.New("ssltvd: unsupported signature type for client certificate")
		}

		md5Hash := md5.New()
		md5Hash.Write(h.buffer)
		sha1Hash := sha1.New()
		sha1Hash.Write(h.buffer)
		return finishedSum30(md5Hash, sha1Hash, masterSecret, nil), crypto.MD5SHA1, nil
	}
	if h.version >= VersionTLS12 {
		hashAlg, err := lookupTLSHash(signatureAndHash.hash)
		if err != nil {
			return nil, 0, err
		}
		hash := hashAlg.New()
		hash.Write(h.buffer)
		return hash.Sum(nil), hashAlg, nil
	}

	if signatureAndHash.signature == signatureECDSA {
		return h.server.Sum(nil), crypto.SHA1, nil
	}

	return h.Sum(), crypto.MD5SHA1, nil
}
开发者ID:thijzert,项目名称:sslprobe,代码行数:34,代码来源:prf.go

示例13: Update

// Update the object from in with modTime and size
func (o *FsObjectLocal) Update(in io.Reader, modTime time.Time, size int64) error {
	dir := path.Dir(o.path)
	err := os.MkdirAll(dir, 0777)
	if err != nil {
		return err
	}

	out, err := os.Create(o.path)
	if err != nil {
		return err
	}

	// Calculate the md5sum of the object we are reading as we go along
	hash := md5.New()
	in = io.TeeReader(in, hash)

	_, err = io.Copy(out, in)
	outErr := out.Close()
	if err != nil {
		return err
	}
	if outErr != nil {
		return outErr
	}

	// All successful so update the md5sum
	o.md5sum = hex.EncodeToString(hash.Sum(nil))

	// Set the mtime
	o.SetModTime(modTime)

	// ReRead info now that we have finished
	return o.lstat()
}
开发者ID:X1011,项目名称:rclone,代码行数:35,代码来源:local.go

示例14: hashForClientCertificate

// hashForClientCertificate returns a digest, hash function, and TLS 1.2 hash
// id suitable for signing by a TLS client certificate.
func (h finishedHash) hashForClientCertificate(signatureAndHash signatureAndHash, masterSecret []byte) ([]byte, crypto.Hash, error) {
	if h.version == VersionSSL30 {
		if signatureAndHash.signature != signatureRSA {
			return nil, 0, errors.New("tls: unsupported signature type for client certificate")
		}

		md5Hash := md5.New()
		md5Hash.Write(h.buffer)
		sha1Hash := sha1.New()
		sha1Hash.Write(h.buffer)
		return finishedSum30(md5Hash, sha1Hash, masterSecret, nil), crypto.MD5SHA1, nil
	}
	if h.version >= VersionTLS12 {
		hashAlg, err := lookupTLSHash(signatureAndHash.hash)
		if err != nil {
			return nil, 0, err
		}
		hash := hashAlg.New()
		hash.Write(h.buffer)
		return hash.Sum(nil), hashAlg, nil
	}
	if signatureAndHash.signature == signatureECDSA {
		return h.server.Sum(nil), crypto.SHA1, nil
	}

	return h.Sum(), crypto.MD5SHA1, nil
}
开发者ID:endlessm,项目名称:chromium-browser,代码行数:29,代码来源:prf.go

示例15: GetIronValue

func GetIronValue(name, value string, key []byte, timestamped bool) (val string, ok bool) {
	split := strings.SplitN(value, ":", 2)
	if len(split) != 2 {
		return
	}
	expected, value := []byte(split[0]), split[1]
	message := fmt.Sprintf("%s|%s", strings.Replace(name, "|", `\|`, -1), value)
	hash := hmac.New(ironHMAC, key)
	hash.Write([]byte(message))
	digest := hash.Sum(nil)
	mac := make([]byte, base64.URLEncoding.EncodedLen(len(digest)))
	base64.URLEncoding.Encode(mac, digest)
	if subtle.ConstantTimeCompare(mac, expected) != 1 {
		return
	}
	if timestamped {
		split = strings.SplitN(value, ":", 2)
		if len(split) != 2 {
			return
		}
		timestring, value := split[0], split[1]
		timestamp, err := strconv.ParseInt(timestring, 10, 64)
		if err != nil {
			return
		}
		if time.Now().UnixNano() > timestamp {
			return
		}
		return value, true
	}
	return value, true
}
开发者ID:runique,项目名称:golly,代码行数:32,代码来源:crypto.go


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