Golang crypto-sha256.Sum256类(方法)实例源码

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

作者:twpayn    项目:go-doaram   
// 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
	}
}

作者:Esper032    项目:Go_trainin   
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
}

作者:postfi    项目:gokeepassli   
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
}

作者:chert    项目:authguar   
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))
	}
}

作者:FactomProjec    项目:factom   
// 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
}

作者:dugwil    项目:gopl.i   
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
}

作者:vinceyua    项目:gopl-solution   
func main() {
	hash1 := sha256.Sum256([]byte("hello world"))
	hash2 := sha256.Sum256([]byte("hello worlD"))
	printHash(hash1)
	printHash(hash2)
	fmt.Println(diffBits(hash1, hash2))
}

作者:William-J-Ear    项目:cloudprox   
// 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
}

作者:utamar    项目:gocoi   
//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
}

作者:Cyber-Forensi    项目:certificate-transparenc   
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[:]))
}

作者:rolandshoemake    项目:staple   
// 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
}

作者:go-gopher    项目:gopher   
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
}

作者:abondar2    项目:GoBas   
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)

}

作者:skha    项目:gopl_ol   
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))
}

作者:kevinawals    项目:cloudprox   
// 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
}

作者:sec5    项目:twofacto   
// 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.")
}

作者:alexchowl    项目:tgp   
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))
}

作者:azdagro    项目:pwsaf   
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[:]
}

作者:ysoht    项目:gopl-e   
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)])
}

作者:rolandshoemake    项目:staple   
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
}


问题


面经


文章

微信
公众号

扫码关注公众号