當前位置: 首頁>>代碼示例>>Golang>>正文


Golang sha256.Sum256函數代碼示例

本文整理匯總了Golang中crypto/sha256.Sum256函數的典型用法代碼示例。如果您正苦於以下問題:Golang Sum256函數的具體用法?Golang Sum256怎麽用?Golang Sum256使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Sum256函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的crypto/sha256.Sum256函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。