Golang crypto-sha512.Sum512类(方法)实例源码

下面列出了Golang crypto-sha512.Sum512 类(方法)源码代码实例,从而了解它的用法。

作者:keysonZZ    项目:km   
/*
对称解密,
	不会修改输入的数据
*/
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
}

作者:mastercactapu    项目:bitmessag   
func CalcVector(p []byte) InvVector {
	sum := sha512.Sum512(p)
	sum = sha512.Sum512(sum[:])
	var v InvVector
	copy(v[:], sum[:32])
	return v
}

作者:kesy    项目:kanba   
// 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)
}

作者:intusc    项目:fai   
// 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
}

作者:Odd-Table    项目:GoPL-exercise   
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)))
	}
}

作者:briandown    项目:GoPasswordUtilitie   
// 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
}

作者:avifla    项目:simplebenc   
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)
}

作者:sonedazauru    项目:golang-trainin   
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
	}
}

作者:balagopalra    项目:clearlinu   
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)
}

作者:tscholl    项目:beaco   
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)
		}
	}()
}

作者:carriercom    项目:repbi   
// 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)
}

作者:wulinx    项目:KeyAdmin-g   
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
}

作者:klizhenta    项目:acbuil   
// 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
}

作者:4cd    项目:srndv   
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
}

作者:sinfomicie    项目:rk   
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)
}

作者:mark-adam    项目:clien   
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
}

作者:YusukeKanazaw    项目:iotsampl   
// FactoryMethod
func NewUser(userName UserKey, password string) *User {
	return &User{
		UserName: userName,
		Password: sha512.Sum512([]byte(password)),
		clients:  clientList{},
	}
}

作者:bosky10    项目:mini   
// 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
}

作者:Rudlof    项目:platfor   
// 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
}

作者:husi    项目:jin   
// 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()
}


问题


面经


文章

微信
公众号

扫码关注公众号