• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang sha512.Sum512函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: DecryptV2

/*
对称解密,
	不会修改输入的数据
*/
func DecryptV2(key []byte, data []byte) (output []byte, err error) {
	if len(data) < 16+64 {
		return nil, errors.New("[kmgCipher.Decrypt] input data too small")
	}
	keyHash := sha512.Sum512(key)
	aseKey := keyHash[:32]
	cbcIv := data[:16]
	block, err := aes.NewCipher(aseKey)
	if err != nil {
		return nil, err
	}
	if len(data)%block.BlockSize() != 0 {
		return nil, errors.New("[kmgCipher.Decrypt] input not full blocks")
	}
	output = make([]byte, len(data)-16)
	blockmode := cipher.NewCBCDecrypter(block, cbcIv)
	blockmode.CryptBlocks(output, data[16:])
	paddingSize := int(output[len(output)-1])
	if paddingSize > block.BlockSize() {
		return nil, errors.New("[kmgCipher.Decrypt] paddingSize out of range")
	}
	beforeCbcSize := len(data) - paddingSize - 64 - 16
	hashData := sha512.Sum512(output[:beforeCbcSize])
	if !bytes.Equal(hashData[:], output[beforeCbcSize:beforeCbcSize+64]) {
		return nil, errors.New("[kmgCipher.Decrypt] hash not match")
	}
	return output[:beforeCbcSize], nil
}
开发者ID:keysonZZZ,项目名称:kmg,代码行数:32,代码来源:kmgEncryptV2.go


示例2: CalcVector

func CalcVector(p []byte) InvVector {
	sum := sha512.Sum512(p)
	sum = sha512.Sum512(sum[:])
	var v InvVector
	copy(v[:], sum[:32])
	return v
}
开发者ID:mastercactapus,项目名称:bitmessage,代码行数:7,代码来源:message.go


示例3: EncodePasswd

// EncodePasswd encodes password to safe format.
func (u *User) EncodePasswd() {
	hash := []byte(u.Passwd)
	dig := sha512.Sum512(hash)
	for i := 1; i < 5000; i++ {
		dig = sha512.Sum512(append(dig[:], hash[:]...))
	}
	newPasswd := base64.StdEncoding.EncodeToString(dig[:])
	u.Passwd = fmt.Sprintf("%s", newPasswd)
}
开发者ID:kesyn,项目名称:kanban,代码行数:10,代码来源:user.go


示例4: VerifyRoll

// VerifyRoll verifies an Intus.co roll is fair.
func VerifyRoll(r *Roll) error {
	serverHash, err := hex.DecodeString(r.ServerHash)
	if err != nil {
		return err
	}

	serverRand, err := hex.DecodeString(r.ServerRand)
	if err != nil {
		return err
	}

	// Does serverRand hash match?
	calcServerHash := sha512.Sum512(serverRand)
	if !bytes.Equal(calcServerHash[:], serverHash) {
		return errors.New("serverRand does not match serverHash")
	}
	log.Println("server hashes match")

	// Calculate roll value matches.
	clientRand, err := hex.DecodeString(r.ClientRand)
	if err != nil {
		return err
	}

	// Concatenate serverRand and clientRand.
	combRand := append(serverRand, clientRand...)

	// Hash the result.
	combHash := sha512.Sum512(combRand)

	// Determine the integer value of combHash.
	combValue := new(big.Int).SetBytes(combHash[:])

	// Now mod the winValue and value to get the provably fair rollValue that is
	// of range of [0, r.WinValue).
	rollValue := new(big.Int)
	new(big.Int).DivMod(combValue, big.NewInt(r.WinValue), rollValue)

	// Check roll values match.
	if rollValue.Int64() != r.RollValue {
		return errors.New("roll values do not match")
	}

	log.Printf("roll value calculated at %v", rollValue)

	// Now see if the roll was a winning one.
	if rollValue.Int64() < r.BetValue {
		log.Printf("provably fair win of %v Satoshi", r.WinValue)
	} else {
		log.Printf("provably fair loss of %v Satoshi", r.BetValue)
	}
	return nil
}
开发者ID:intusco,项目名称:fair,代码行数:54,代码来源:dice.go


示例5: shaHash

func shaHash(fl string, a string) {
	if fl == "t" {
		fmt.Print("SHA384 Hash Value:\n")
		fmt.Printf("%x\n", sha512.Sum512([]byte(a)))
	} else if fl == "f" {
		fmt.Print("SHA512 Hash Value:\n")
		fmt.Printf("%x\n", sha512.Sum512([]byte(a)))
	} else {
		fmt.Print("SHA256 Hash Value:\n")
		fmt.Printf("%x\n", sha256.Sum256([]byte(a)))
	}
}
开发者ID:Odd-Tablet,项目名称:GoPL-exercises,代码行数:12,代码来源:sha.go


示例6: SHA512

// SHA512 sum for the given password.  If a SaltConf
// pointer is given as a parameter a salt with the given
// length will be returned with it included in the hash.
func (p *Password) SHA512(saltConf ...*SaltConf) ([64]byte, []byte) {
	if len(saltConf) > 0 {
		var saltLength int

		for _, i := range saltConf[0:] {
			saltLength = i.Length
		}

		salt := getRandomBytes(saltLength)
		return sha512.Sum512([]byte(fmt.Sprintf("%s%x", p.Pass, salt))), salt
	}
	return sha512.Sum512([]byte(p.Pass)), nil
}
开发者ID:briandowns,项目名称:GoPasswordUtilities,代码行数:16,代码来源:password_utility.go


示例7: handle

func handle(w http.ResponseWriter, r *http.Request) {
	currentTime := time.Now().Unix()
	res := response{
		Time:     currentTime,
		Hash:     fmt.Sprintf("%x", sha512.Sum512([]byte(trueRemoteAddr(r)))),
		ClientIP: trueRemoteAddr(r),
	}
	resj, _ := json.Marshal(res)
	etag := fmt.Sprintf("\"%x\"", sha512.Sum512(resj))
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Etag", etag)
	w.Write(resj)
}
开发者ID:aviflax,项目名称:simplebench,代码行数:13,代码来源:main.go


示例8: main

func main() {
	usage := "Usage: echo -n hello | ./ex02 [256|384|512]"
	bytes, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	n := 256
	if len(os.Args) == 2 {
		n, _ = strconv.Atoi(os.Args[1])
	}

	switch n {
	case 256:
		fmt.Printf("%x\n", sha256.Sum256(bytes))
		os.Exit(0)
		return
	case 384:
		fmt.Printf("%x\n", sha512.Sum384(bytes))
		os.Exit(0)
		return
	case 512:
		fmt.Printf("%x\n", sha512.Sum512(bytes))
		os.Exit(0)
		return
	default:
		fmt.Println(usage)
		os.Exit(1)
		return
	}
}
开发者ID:sonedazaurus,项目名称:golang-training,代码行数:31,代码来源:main.go


示例9: cmdAdd

func cmdAdd(args *skel.CmdArgs) error {
	conf := NetConf{}
	if err := json.Unmarshal(args.StdinData, &conf); err != nil {
		return fmt.Errorf("failed to load netconf: %v", err)
	}

	// run the IPAM plugin and get back the config to apply
	result, err := plugin.ExecAdd(conf.IPAM.Type, args.StdinData)
	if err != nil {
		return err
	}
	if result.IP4 == nil {
		return errors.New("IPAM plugin returned missing IPv4 config")
	}

	hostVethName, err := setupContainerVeth(args.Netns, args.IfName, conf.MTU, result)
	if err != nil {
		return err
	}

	if err = setupHostVeth(hostVethName, result.IP4); err != nil {
		return err
	}

	if conf.IPMasq {
		h := sha512.Sum512([]byte(args.Netns))
		chain := fmt.Sprintf("CNI-%s-%x", conf.Name, h[:8])
		if err = ip.SetupIPMasq(&result.IP4.IP, chain); err != nil {
			return err
		}
	}

	return plugin.PrintResult(result)
}
开发者ID:balagopalraj,项目名称:clearlinux,代码行数:34,代码来源:veth.go


示例10: init

func init() {
	var filename string
	var err error
	flag.StringVar(&filename, "file", "key.txt",
		"file containing secret key")
	flag.Parse()
	f, err := ioutil.ReadFile(filename)
	if err != nil {
		panic(err)
	}
	b := sha512.Sum512(f)
	key, err = ecdsa.GenerateKey(elliptic.P256(), bytes.NewReader(b[:]))
	if err != nil {
		panic(err)
	}
	err = rs.Open("./test.db", key)
	if err != nil {
		panic(err)
	}
	m = new(mic.Reader)
	go func() {
		for {
			var bits [32]byte
			m.Read(bits[:])
			_, err := rs.New(bits)
			if err != nil {
				fmt.Printf("error making record %s\n", err)
			}
			time.Sleep(60 * time.Second)
		}
	}()
}
开发者ID:tscholl2,项目名称:beacon,代码行数:32,代码来源:main.go


示例11: CalcSharedSecret

// CalcSharedSecret does a triple DH from the keypacks to generate the shared secret. myKeys needs to contain private keys, peerKeys only needs public keys
// Sending determines if one is sender or recipient of a message.
func CalcSharedSecret(myKeys, peerKeys *KeyPack, nonce *[NonceSize]byte, sending bool) (sharedSecret [SharedKeySize]byte) {
	preKey := make([]byte, 3*Curve25519KeySize+NonceSize) // three keys plus nonce
	key1, key2, key3 := new(Curve25519Key), new(Curve25519Key), new(Curve25519Key)
	log.Secretf("TemporaryPrivKey: %x\n", *myKeys.TemporaryPrivKey)
	log.Secretf("ConstantPrivKey: %x\n", *myKeys.ConstantPrivKey)
	log.Secretf("TemporaryPubKey: %x\n", *peerKeys.TemporaryPubKey)
	log.Secretf("ConstantPubKey: %x\n", *peerKeys.ConstantPubKey)
	scalarMult(key1, myKeys.TemporaryPrivKey, peerKeys.TemporaryPubKey)
	log.Secretf("Key1: %x\n", *key1)
	scalarMult(key2, myKeys.ConstantPrivKey, peerKeys.TemporaryPubKey)
	scalarMult(key3, myKeys.TemporaryPrivKey, peerKeys.ConstantPubKey)
	preKey = append(preKey, key1[:]...)
	if sending {
		log.Secretf("Key2: %x\n", *key2)
		log.Secretf("Key3: %x\n", *key3)
		preKey = append(preKey, key2[:]...)
		preKey = append(preKey, key3[:]...)
	} else { // Swap for receiver
		log.Secretf("Key2: %x\n", *key3)
		log.Secretf("Key3: %x\n", *key2)
		preKey = append(preKey, key3[:]...)
		preKey = append(preKey, key2[:]...)

	}
	log.Secretf("Nonce: %x\n", *nonce)
	preKey = append(preKey, nonce[:]...)
	return sha512.Sum512(preKey)
}
开发者ID:carriercomm,项目名称:repbin,代码行数:30,代码来源:keys.go


示例12: _passpharseHash

func _passpharseHash(passpharse []byte, encodingWay []string) (encodedpasspharse []byte) {
	encodepasspharse := passpharse
	for _, hashalgor := range encodingWay {
		switch hashalgor {
		case "md5":
			sum := md5.Sum(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha1":
			sum := sha1.Sum(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha224":
			sum := sha256.Sum224(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha256":
			sum := sha256.Sum256(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha384":
			sum := sha512.Sum384(encodepasspharse)
			encodepasspharse = sum[:]
		case "sha512":
			sum := sha512.Sum512(encodepasspharse)
			encodepasspharse = sum[:]
		}
	}
	//issue if return with not args,the return value will be null
	return encodepasspharse
}
开发者ID:wulinxu,项目名称:KeyAdmin-go,代码行数:27,代码来源:passwordadmin.go


示例13: Hash

// Hash takes an array of strings and returns their hash.
func Hash(strings ...string) (string, error) {
	var bytes []byte
	for _, s := range strings {
		bytes = append(bytes, []byte(s)...)
	}
	return fmt.Sprintf("%s%x", "sha512-", sha512.Sum512(bytes)), nil
}
开发者ID:klizhentas,项目名称:acbuild,代码行数:8,代码来源:util.go


示例14: createAttachment

func createAttachment(content_type, fname string, body io.Reader) NNTPAttachment {

	media_type, _, err := mime.ParseMediaType(content_type)
	if err == nil {
		a := nntpAttachment{}
		_, err = io.Copy(&a.body, body)
		if err == nil {
			a.header = make(textproto.MIMEHeader)
			a.mime = media_type + "; charset=UTF-8"
			idx := strings.LastIndex(fname, ".")
			a.ext = ".txt"
			if idx > 0 {
				a.ext = fname[idx:]
			}
			a.header.Set("Content-Disposition", `form-data; filename="`+fname+`"; name="attachment"`)
			a.header.Set("Content-Type", a.mime)
			a.header.Set("Content-Transfer-Encoding", "base64")
			h := sha512.Sum512(a.body.Bytes())
			hashstr := base32.StdEncoding.EncodeToString(h[:])
			a.hash = h[:]
			a.filepath = hashstr + a.ext
			a.filename = fname
			return a
		}
	}
	return nil
}
开发者ID:4cdn,项目名称:srndv2,代码行数:27,代码来源:attachment.go


示例15: cmdDel

func cmdDel(args *skel.CmdArgs) error {
	conf := NetConf{}
	if err := json.Unmarshal(args.StdinData, &conf); err != nil {
		return fmt.Errorf("failed to load netconf: %v", err)
	}

	var ipn *net.IPNet
	err := ns.WithNetNSPath(args.Netns, false, func(hostNS *os.File) error {
		var err error
		ipn, err = ip.DelLinkByNameAddr(args.IfName, netlink.FAMILY_V4)
		return err
	})
	if err != nil {
		return err
	}

	if conf.IPMasq {
		h := sha512.Sum512([]byte(args.ContainerID))
		chain := fmt.Sprintf("CNI-%s-%x", conf.Name, h[:8])
		if err = ip.TeardownIPMasq(ipn, chain); err != nil {
			return err
		}
	}

	return ipam.ExecDel(conf.IPAM.Type, args.StdinData)
}
开发者ID:sinfomicien,项目名称:rkt,代码行数:26,代码来源:ptp.go


示例16: processEncryptionBlock

func (ds *decryptStream) processEncryptionBlock(bl *EncryptionBlock) ([]byte, error) {

	blockNum := encryptionBlockNumber(bl.seqno - 1)

	if err := blockNum.check(); err != nil {
		return nil, err
	}

	nonce := ds.nonce.ForPayloadBox(blockNum)
	ciphertext := bl.PayloadCiphertext
	hash := sha512.Sum512(ciphertext)

	hashBox := ds.tagKey.Box(nonce, hash[:])
	ourAuthenticator := hashBox[:secretbox.Overhead]

	if !hmac.Equal(ourAuthenticator, bl.HashAuthenticators[ds.position]) {
		return nil, ErrBadTag(bl.seqno)
	}

	plaintext, ok := secretbox.Open([]byte{}, ciphertext, (*[24]byte)(nonce), (*[32]byte)(ds.payloadKey))
	if !ok {
		return nil, ErrBadCiphertext(bl.seqno)
	}

	// The encoding of the empty buffer implies the EOF.  But otherwise, all mechanisms are the same.
	if len(plaintext) == 0 {
		return nil, nil
	}
	return plaintext, nil
}
开发者ID:mark-adams,项目名称:client,代码行数:30,代码来源:decrypt.go


示例17: NewUser

// FactoryMethod
func NewUser(userName UserKey, password string) *User {
	return &User{
		UserName: userName,
		Password: sha512.Sum512([]byte(password)),
		clients:  clientList{},
	}
}
开发者ID:YusukeKanazawa,项目名称:iotsample,代码行数:8,代码来源:user.go


示例18: NewMultipartUpload

// NewMultipartUpload - initiate a new multipart session
func (donut API) NewMultipartUpload(bucket, key, contentType string) (string, error) {
	donut.lock.Lock()
	defer donut.lock.Unlock()

	if !IsValidBucket(bucket) {
		return "", iodine.New(BucketNameInvalid{Bucket: bucket}, nil)
	}
	if !IsValidObjectName(key) {
		return "", iodine.New(ObjectNameInvalid{Object: key}, nil)
	}
	if !donut.storedBuckets.Exists(bucket) {
		return "", iodine.New(BucketNotFound{Bucket: bucket}, nil)
	}
	storedBucket := donut.storedBuckets.Get(bucket).(storedBucket)
	objectKey := bucket + "/" + key
	if _, ok := storedBucket.objectMetadata[objectKey]; ok == true {
		return "", iodine.New(ObjectExists{Object: key}, nil)
	}
	id := []byte(strconv.FormatInt(rand.Int63(), 10) + bucket + key + time.Now().String())
	uploadIDSum := sha512.Sum512(id)
	uploadID := base64.URLEncoding.EncodeToString(uploadIDSum[:])[:47]

	storedBucket.multiPartSession[key] = MultiPartSession{
		uploadID:   uploadID,
		initiated:  time.Now(),
		totalParts: 0,
	}
	multiPartCache := data.NewCache(0)
	multiPartCache.OnEvicted = donut.evictedPart
	donut.multiPartObjects[uploadID] = multiPartCache
	donut.storedBuckets.Set(bucket, storedBucket)
	return uploadID, nil
}
开发者ID:bosky101,项目名称:minio,代码行数:34,代码来源:multipart.go


示例19: GenerateKey

// GenerateKey generates a public/private key pair using entropy from rand.
// If rand is nil, crypto/rand.Reader will be used.
func GenerateKey(rand io.Reader) (publicKey PublicKey, privateKey PrivateKey, err error) {
	if rand == nil {
		rand = cryptorand.Reader
	}

	privateKey = make([]byte, PrivateKeySize)
	publicKey = make([]byte, PublicKeySize)
	_, err = io.ReadFull(rand, privateKey[:32])
	if err != nil {
		return nil, nil, err
	}

	digest := sha512.Sum512(privateKey[:32])
	digest[0] &= 248
	digest[31] &= 127
	digest[31] |= 64

	var A edwards25519.ExtendedGroupElement
	var hBytes [32]byte
	copy(hBytes[:], digest[:])
	edwards25519.GeScalarMultBase(&A, &hBytes)
	var publicKeyBytes [32]byte
	A.ToBytes(&publicKeyBytes)

	copy(privateKey[32:], publicKeyBytes[:])
	copy(publicKey, publicKeyBytes[:])

	return publicKey, privateKey, nil
}
开发者ID:Rudloff,项目名称:platform,代码行数:31,代码来源:ed25519.go


示例20: Valid

// Valid return true if given password is valid user password.
func (p PasswordField) Valid(password string) bool {
	salt := p.Salt()
	raw := sha512.Sum512([]byte(salt + password))
	hash := base64.StdEncoding.EncodeToString(raw[:])
	passHash := fmt.Sprintf("%s$$%s", salt, hash)
	return passHash == p.String()
}
开发者ID:husio,项目名称:jinx,代码行数:8,代码来源:store.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang subtle.ConstantTimeByteEq函数代码示例发布时间:2022-05-24
下一篇:
Golang sha512.Sum384函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap