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

Golang sha256.Sum256函数代码示例

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

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



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

示例1: CreateActivityWithInfo

// CreateActivityWithInfo creates an activity, re-using a previous activity if
// available.
func (s *sqlite) CreateActivityWithInfo(ctx context.Context, filename string, gpsTrack io.Reader, activityInfo *doarama.ActivityInfo) (*doarama.Activity, error) {
	content, err := ioutil.ReadAll(gpsTrack)
	if err != nil {
		return nil, err
	}
	gpsTrackSha256 := sha256.Sum256(content)
	activityInfoSha256 := sha256.Sum256(structhash.Dump(activityInfo, 0))
	var activityID int
	switch err := s.queryStmt.QueryRow(gpsTrackSha256[:], activityInfoSha256[:]).Scan(&activityID); err {
	case nil:
		return &doarama.Activity{
			Client: s.client,
			ID:     activityID,
		}, nil
	case sql.ErrNoRows:
		activity, err := s.client.CreateActivityWithInfo(ctx, filename, bytes.NewBuffer(content), activityInfo)
		if err != nil {
			return activity, err
		}
		_, err = s.insertStmt.Exec(activity.ID, gpsTrackSha256[:], activityInfoSha256[:])
		return activity, err
	default:
		return nil, err
	}
}
开发者ID:twpayne,项目名称:go-doarama,代码行数:27,代码来源:sqlite3.go


示例2: main

func main() {
	length := len(os.Args)
	if length > 2 {
		if os.Args[2] == "-384" {
			c1 := sha512.Sum384([]byte(os.Args[1]))
			fmt.Printf("%s\n%x\n%T\n", os.Args[1], c1, c1)
		} else if os.Args[2] == "-512" {
			c1 := sha512.Sum512([]byte(os.Args[1]))
			fmt.Printf("%s\n%x\n%T\n", os.Args[1], c1, c1)
		} else {
			c1 := sha256.Sum256([]byte(os.Args[1]))
			fmt.Printf("%s\n%x\n%T\n", os.Args[1], c1, c1)
		}
	} else if length == 2 {
		c1 := sha256.Sum256([]byte(os.Args[1]))
		fmt.Printf("%s\n%x\n%T\n", os.Args[1], c1, c1)
	} else {
		fmt.Printf("less arguments")
	}
	// Output:
	// 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881
	// 4b68ab3847feda7d6c62c1fbcbeebfa35eab7351ed5e78f4ddadea5df64b8015
	// false
	// [32]uint8
}
开发者ID:Esper0328,项目名称:Go_training,代码行数:25,代码来源:main.go


示例3: buildMasterKey

func (c *DBCredentials) buildMasterKey(db *Database) ([]byte, error) {
	masterKey, err := c.buildCompositeKey()
	if err != nil {
		return nil, err
	}

	block, err := aes.NewCipher(db.Headers.TransformSeed)
	if err != nil {
		return nil, err
	}

	// http://crypto.stackexchange.com/questions/21048/can-i-simulate-iterated-aes-ecb-with-other-block-cipher-modes
	for i := uint64(0); i < db.Headers.TransformRounds; i++ {
		result := make([]byte, 16)
		crypter := cipher.NewCBCEncrypter(block, result)
		crypter.CryptBlocks(masterKey[:16], masterKey[:16])
		crypter = cipher.NewCBCEncrypter(block, result)
		crypter.CryptBlocks(masterKey[16:], masterKey[16:])
	}

	tmp := sha256.Sum256(masterKey)
	masterKey = tmp[:]

	masterKey = append(db.Headers.MasterSeed, masterKey...)
	masterHash := sha256.Sum256(masterKey)
	masterKey = masterHash[:]

	return masterKey, nil
}
开发者ID:postfix,项目名称:gokeepasslib,代码行数:29,代码来源:credentials.go


示例4: main

func main() {
	flag.Parse()
	if *logTimestamps {
		logInfo.SetFlags(3)
		logError.SetFlags(3)
	}

	userhash = sha256.Sum256([]byte(*user))
	passhash = sha256.Sum256([]byte(*pass))

	logInfo.Println("starting redirector from", *outerAddress, "to", *innerAddress)

	if *useAuth {
		logInfo.Println("HTTP Basic Auth enabled")
		http.HandleFunc("/", redirectAfterAuthCheck)
	} else {
		logInfo.Println("HTTP Basic Auth disabled")
		http.HandleFunc("/", performRedirect)
	}

	useTLS := *crt != "" && *key != ""
	if useTLS {
		logInfo.Println("TLS enabled")
		logError.Fatal(http.ListenAndServeTLS(*outerAddress, *crt, *key, nil))
	} else {
		logInfo.Println("TLS disabled")
		logError.Fatal(http.ListenAndServe(*outerAddress, nil))
	}
}
开发者ID:cherti,项目名称:authguard,代码行数:29,代码来源:authguard.go


示例5: Shad

// Shad Double Sha256 Hash; sha256(sha256(data))
func Shad(data []byte) interfaces.IHash {
	h1 := sha256.Sum256(data)
	h2 := sha256.Sum256(h1[:])
	h := new(Hash)
	h.SetBytes(h2[:])
	return h
}
开发者ID:FactomProject,项目名称:factomd,代码行数:8,代码来源:hash.go


示例6: main

func main() {
	c1 := sha256.Sum256([]byte("now is the time"))
	c2 := sha256.Sum256([]byte("Bobs your uncle"))
	fmt.Printf("%x\n%x\n%t\n%T\n", c1, c2, c1 == c2, c1)

	c3 := [32]uint8{}

	for i := 0; i < len(c1); i++ {
		c3[i] = c1[i] ^ c2[i]
	}

	fmt.Printf("%x\n", c3)

	var count int

	for i := 0; i < len(c3); i++ {
		count = count + popcount.PopCountByte(c3[i])
		fmt.Printf("Popcount of byte %d is (%b) is %d\n", i, c3[i], popcount.PopCountByte(c3[i]))
	}

	fmt.Printf("Population count is %d\n", count)

	// Output:
	// 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881
	// 4b68ab3847feda7d6c62c1fbcbeebfa35eab7351ed5e78f4ddadea5df64b8015
	// false
	// [32]uint8
}
开发者ID:dugwill,项目名称:gopl.io,代码行数:28,代码来源:main.go


示例7: main

func main() {
	hash1 := sha256.Sum256([]byte("hello world"))
	hash2 := sha256.Sum256([]byte("hello worlD"))
	printHash(hash1)
	printHash(hash2)
	fmt.Println(diffBits(hash1, hash2))
}
开发者ID:vinceyuan,项目名称:gopl-solutions,代码行数:7,代码来源:ex4.1.go


示例8: NewHostedProgram

// MakeSubprin computes the hash of a QEMU/KVM CoreOS image to get a
// subprincipal for authorization purposes.
func (lkcf *LinuxKVMCoreOSFactory) NewHostedProgram(spec HostedProgramSpec) (child HostedProgram, err error) {
	// (id uint, image string, uid, gid int) (auth.SubPrin, string, error) {
	// TODO(tmroeder): the combination of TeeReader and ReadAll doesn't seem
	// to copy the entire image, so we're going to hash in place for now.
	// This needs to be fixed to copy the image so we can avoid a TOCTTOU
	// attack.
	// TODO(kwalsh) why is this recomputed for each hosted program?
	b, err := ioutil.ReadFile(lkcf.Cfg.ImageFile)
	if err != nil {
		return
	}
	h := sha256.Sum256(b)

	bb, err := ioutil.ReadFile(spec.Path)
	if err != nil {
		return
	}
	hh := sha256.Sum256(bb)

	// vet things

	child = &KvmCoreOSContainer{
		spec:        spec,
		FactoryHash: h[:],
		Hash:        hh[:],
		Factory:     lkcf,
		Done:        make(chan bool, 1),
	}
	return
}
开发者ID:William-J-Earl,项目名称:cloudproxy,代码行数:32,代码来源:kvm_coreos_factory.go


示例9: GetAddress

//GetAddress returns bitcoin address from PublicKey
func (pub *PublicKey) GetAddress() (string, []byte) {
	var publicKeyPrefix byte

	if pub.isTestnet {
		publicKeyPrefix = 0x6F
	} else {
		publicKeyPrefix = 0x00
	}

	//Next we get a sha256 hash of the public key generated
	//via ECDSA, and then get a ripemd160 hash of the sha256 hash.
	var shadPublicKeyBytes [32]byte
	if pub.isCompressed {
		shadPublicKeyBytes = sha256.Sum256(pub.key.SerializeCompressed())

	} else {
		shadPublicKeyBytes = sha256.Sum256(pub.key.SerializeUncompressed())
	}

	ripeHash := ripemd160.New()
	ripeHash.Write(shadPublicKeyBytes[:])
	ripeHashedBytes := ripeHash.Sum(nil)

	publicKeyEncoded := base58check.Encode(publicKeyPrefix, ripeHashedBytes)
	return publicKeyEncoded, ripeHashedBytes
}
开发者ID:utamaro,项目名称:gocoin,代码行数:27,代码来源:keys.go


示例10: CalcRootHash

func CalcRootHash() {
	e0, err := base64.StdEncoding.DecodeString(Entry0)
	if err != nil {
		log.Fatal(err)
	}
	h0 := sha256.Sum256(e0)
	e1, err := base64.StdEncoding.DecodeString(Entry1)
	if err != nil {
		log.Fatal(err)
	}
	h1 := sha256.Sum256(e1)
	e2, err := base64.StdEncoding.DecodeString(Entry2)
	if err != nil {
		log.Fatal(err)
	}
	h2 := sha256.Sum256(e2)
	e3, err := base64.StdEncoding.DecodeString(Entry3)
	if err != nil {
		log.Fatal(err)
	}
	h3 := sha256.Sum256(e3)

	hash01 := makeParent(h0[:], h1[:])
	hash23 := makeParent(h2[:], h3[:])
	root := makeParent(hash01[:], hash23[:])
	log.Println(base64.StdEncoding.EncodeToString(root[:]))
}
开发者ID:Cyber-Forensic,项目名称:certificate-transparency,代码行数:27,代码来源:scanner_test_data.go


示例11: AddFromRequest

// AddFromRequest creates an entry from a OCSP request and adds it to
// the cache, a set of upstream OCSP responders can be provided
func (c *EntryCache) AddFromRequest(req *ocsp.Request, upstream []string) ([]byte, error) {
	e := NewEntry(c.log, c.clk)
	e.serial = req.SerialNumber
	var err error
	e.request, err = req.Marshal()
	if err != nil {
		return nil, err
	}
	e.responders = upstream
	serialHash := sha256.Sum256(e.serial.Bytes())
	key := sha256.Sum256(append(append(req.IssuerNameHash, req.IssuerKeyHash...), serialHash[:]...))
	e.name = fmt.Sprintf("%X", key)
	e.issuer = c.issuers.getFromRequest(req.IssuerNameHash, req.IssuerKeyHash)
	if e.issuer == nil {
		return nil, errors.New("No issuer in cache for request")
	}
	ctx, cancel := context.WithTimeout(context.Background(), c.requestTimeout)
	defer cancel()
	err = e.init(ctx, c.StableBackings, c.client)
	if err != nil {
		return nil, err
	}
	c.addSingle(e, key)
	return e.response, nil
}
开发者ID:rolandshoemaker,项目名称:stapled,代码行数:27,代码来源:entryCache.go


示例12: encodeBase58Check

func encodeBase58Check(val []byte) []byte {
	const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

	// payload
	p := make([]byte, 1+len(val)) // version byte (0x00) + val
	copy(p[1:], val)
	h1 := sha256.Sum256(p)
	h2 := sha256.Sum256(h1[:])

	// value as []byte
	v := make([]byte, len(p)+4) // payload + first 4 bytes of h2
	copy(v, p)
	copy(v[len(p):], h2[:4])

	var res []byte
	x := new(big.Int).SetBytes(v)
	y := big.NewInt(58)
	m, zero := new(big.Int), new(big.Int)

	// convert to base58
	for x.Cmp(zero) > 0 {
		x, m = x.DivMod(x, y, m)
		res = append(res, alphabet[m.Int64()])
	}
	// append '1' for each leading zero byte in value
	for i := 0; v[i] == 0; i++ {
		res = append(res, alphabet[0])
	}
	// reverse
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}

	return res
}
开发者ID:go-gophers,项目名称:gophers,代码行数:35,代码来源:bitcoin.go


示例13: CountSha

func CountSha() {
	c1 := sha256.Sum256([]byte("x"))
	c2 := sha256.Sum256([]byte("X"))

	fmt.Printf("%x\n%x\n%t\n%T\n", c1, c2, c1 == c2, c1)

}
开发者ID:abondar24,项目名称:GoBase,代码行数:7,代码来源:utils.go


示例14: main

func main() {
	sha1 := sha256.Sum256([]byte(s1))
	sha2 := sha256.Sum256([]byte(s2))
	fmt.Println("sha1:", sha1)
	fmt.Println("sha2:", sha2)
	fmt.Println("bits:", countBits(&sha1, &sha2))
}
开发者ID:skhal,项目名称:gopl_old,代码行数:7,代码来源:shadiff.go


示例15: NewHostedProgram

// MakeSubprin computes the hash of a QEMU/KVM CoreOS image to get a
// subprincipal for authorization purposes.
func (lkcf *LinuxKVMCoreOSHostFactory) NewHostedProgram(spec HostedProgramSpec) (child HostedProgram, err error) {
	// (id uint, image string, uid, gid int) (auth.SubPrin, string, error)

	// The args must contain the directory to write the linux_host into, as
	// well as the port to use for SSH.
	if len(spec.Args) != 3 {
		glog.Errorf("Expected %d args, but got %d", 3, len(spec.Args))
		for i, a := range spec.Args {
			glog.Errorf("Arg %d: %s", i, a)
		}
		err = errors.New("KVM/CoreOS guest Tao requires args: <linux_host image> <temp directory for linux_host> <SSH port>")
		return
	}

	// TODO(tmroeder): the combination of TeeReader and ReadAll doesn't seem
	// to copy the entire image, so we're going to hash in place for now.
	// This needs to be fixed to copy the image so we can avoid a TOCTTOU
	// attack.
	// TODO(kwalsh) why is this recomputed for each hosted program?
	// TODO(kwalsh) Move this hash to LinuxKVMCoreOSHostFactory?
	b, err := ioutil.ReadFile(lkcf.Cfg.ImageFile)
	if err != nil {
		return
	}
	h := sha256.Sum256(b)

	bb, err := ioutil.ReadFile(spec.Path)
	if err != nil {
		return
	}
	hh := sha256.Sum256(bb)

	sockName := randName() + ".sock"
	sockPath := path.Join(lkcf.SocketPath, sockName)
	sshCfg := lkcf.Cfg.SSHKeysCfg + "\n - " + string(lkcf.PublicKey)

	cfg := &CoreOSLinuxhostConfig{
		Name:       randName(),
		ImageFile:  lkcf.Cfg.ImageFile, // the VM image
		Memory:     lkcf.Cfg.Memory,
		RulesPath:  lkcf.Cfg.RulesPath,
		SSHKeysCfg: sshCfg,
		SocketPath: sockPath,
	}

	child = &KvmCoreOSHostContainer{
		HostedProgramInfo: HostedProgramInfo{
			spec: spec,
			// TODO(kwalsh) why does Id appear twice in subprin?
			subprin: append(FormatCoreOSLinuxhostSubprin(spec.Id, h[:]), FormatLinuxHostSubprin(spec.Id, hh[:])...),
			Done:    make(chan bool, 1),
		},
		Cfg:        cfg,
		CoreOSHash: h[:],
		LHHash:     hh[:],
		Factory:    lkcf,
	}

	return
}
开发者ID:kevinawalsh,项目名称:cloudproxy,代码行数:62,代码来源:kvm_coreos_linuxhost_factory.go


示例16: Validate

// This function validates the user privided token
// It calculates 3 different tokens. The current one, one before now and one after now.
// The difference is driven by the TOTP step size
// Based on which of the 3 steps it succeeds to validates, the client offset is updated.
// It also updates the total amount of verification failures and the last time a verification happened in UTC time
// Returns an error in case of verification failure, with the reason
// There is a very basic method which protects from timing attacks, although if the step time used is low it should not be necessary
// An attacker can still learn the synchronization offset. This is however irrelevant because the attacker has then 30 seconds to
// guess the code and after 3 failures the function returns an error for the following 5 minutes
func (otp *Totp) Validate(userCode string) error {

	// check Totp initialization
	if err := totpHasBeenInitialized(otp); err != nil {
		return err
	}

	// verify that the token is valid
	if userCode == "" {
		return errors.New("User provided token is empty")
	}

	// check against the total amount of failures
	if otp.totalVerificationFailures >= max_failures && !validBackoffTime(otp.lastVerificationTime) {
		return LockDownError
	}

	if otp.totalVerificationFailures >= max_failures && validBackoffTime(otp.lastVerificationTime) {
		// reset the total verification failures counter
		otp.totalVerificationFailures = 0
	}

	// calculate the sha256 of the user code
	userTokenHash := sha256.Sum256([]byte(userCode))
	userToken := hex.EncodeToString(userTokenHash[:])

	// 1 calculate the 3 tokens
	tokens := make([]string, 3)
	token0Hash := sha256.Sum256([]byte(calculateTOTP(otp, -1)))
	token1Hash := sha256.Sum256([]byte(calculateTOTP(otp, 0)))
	token2Hash := sha256.Sum256([]byte(calculateTOTP(otp, 1)))

	tokens[0] = hex.EncodeToString(token0Hash[:]) // 30 seconds ago token
	tokens[1] = hex.EncodeToString(token1Hash[:]) // current token
	tokens[2] = hex.EncodeToString(token2Hash[:]) // next 30 seconds token

	// if the current time token is valid then, no need to re-sync and return nil
	if tokens[1] == userToken {
		return nil
	}

	// if the 30 seconds ago token is valid then return nil, but re-synchronize
	if tokens[0] == userToken {
		otp.synchronizeCounter(-1)
		return nil
	}

	// if the let's say 30 seconds ago token is valid then return nil, but re-synchronize
	if tokens[2] == userToken {
		otp.synchronizeCounter(1)
		return nil
	}

	otp.totalVerificationFailures++
	otp.lastVerificationTime = time.Now().UTC() // important to have it in UTC

	// if we got here everything is good
	return errors.New("Tokens mismatch.")
}
开发者ID:sec51,项目名称:twofactor,代码行数:68,代码来源:totp.go


示例17: main

func main() {
	c1 := sha256.Sum256([]byte("x"))
	c2 := sha256.Sum256([]byte("X"))

	fmt.Printf("c1==%v\nc2==%v\n", c1, c2)

	fmt.Printf("Different bit count: %v\n", diffCount(c1, c2))
}
开发者ID:alexchowle,项目名称:tgpl,代码行数:8,代码来源:bitdiffcounter.go


示例18: makeKey

func makeKey(passphrase string, salt []byte, iter uint32) ([]byte, []byte) {
	h := sha256.Sum256(append([]byte(passphrase), salt...))
	for i := uint32(0); i < iter; i++ {
		h = sha256.Sum256(h[:])
	}
	phash := sha256.Sum256(h[:])
	return h[:], phash[:]
}
开发者ID:azdagron,项目名称:pwsafe,代码行数:8,代码来源:common.go


示例19: diffBitSha256

func diffBitSha256(data1, data2 string) int {
	c1 := sha256.Sum256([]byte(data1))
	c2 := sha256.Sum256([]byte(data2))

	diff := xor(c1, c2)

	return PopCount(diff[0:len(diff)])
}
开发者ID:ysohta,项目名称:gopl-ex,代码行数:8,代码来源:main.go


示例20: hashEntry

func hashEntry(h hash.Hash, name, pkiBytes []byte, serial *big.Int) ([32]byte, error) {
	issuerNameHash, issuerKeyHash, err := common.HashNameAndPKI(h, name, pkiBytes)
	if err != nil {
		return [32]byte{}, err
	}
	serialHash := sha256.Sum256(serial.Bytes())
	return sha256.Sum256(append(append(issuerNameHash, issuerKeyHash...), serialHash[:]...)), nil
}
开发者ID:rolandshoemaker,项目名称:stapled,代码行数:8,代码来源:entryCache.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang sha512.New函数代码示例发布时间:2022-05-24
下一篇:
Golang sha256.Sum函数代码示例发布时间: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