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

Golang crypto.Hash函数代码示例

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

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



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

示例1: Encode

//you need set packet before encode
func (a *PasswordAVP) Encode() (b []byte, err error) {
	m := crypto.Hash(crypto.MD5).New()
	m.Write(a.packet.Secret)
	m.Write(a.packet.Authenticator[:])
	md := m.Sum(nil)
	if len(a.Value) > 128 {
		return nil, fmt.Errorf("[PasswordAVP.Encode] len(data)[%d]>128", len(a.Value))
	}
	inPassLen := len(a.Value) / 16 * 16
	if len(a.Value)%16 != 0 {
		inPassLen += 16
	}
	pass := make([]byte, inPassLen)
	outPass := make([]byte, inPassLen)
	copy(pass, a.Value)
	blockNum := inPassLen / 16
	for i := 0; i < blockNum; i++ {
		for j := 0; j < 16; j++ {
			outPass[i*16+j] = pass[i*16+j] ^ md[j]
		}
		m := crypto.Hash(crypto.MD5).New()
		m.Write(a.packet.Secret)
		m.Write(outPass[i*16 : i*16+16])
		md = m.Sum(nil)
	}
	return encodeWithByteSlice(AVPTypeUserPassword, outPass)
}
开发者ID:keysonZZZ,项目名称:kmg,代码行数:28,代码来源:avp.go


示例2: avpPassword

func avpPassword(p *Packet, typ AVPType, data []byte) (avp AVP, err error) {
	fmt.Printf("%#v\n", data)
	if len(data) < 16 {
		return nil, fmt.Errorf("[avpPassword] len(data)[%d]<16", len(data))
	}
	if len(data) > 128 {
		return nil, fmt.Errorf("[avpPassword] len(data)[%d]>128", len(data))
	}
	//Decode password. XOR against md5(p.server.secret+Authenticator)
	m := crypto.Hash(crypto.MD5).New()
	m.Write(p.Secret)
	m.Write(p.Authenticator[:])
	md := m.Sum(nil)
	pass := append([]byte(nil), data...)
	blockNum := len(pass) / 16
	if len(pass)%16 != 0 {
		return nil, fmt.Errorf("[avpPassword] blockNum[%d]%%16!=0", blockNum)
	}
	outputPass := make([]byte, len(pass))
	for i := 0; i < blockNum; i++ {
		for j := 0; j < 16; j++ {
			outputPass[i*16+j] = pass[i*16+j] ^ md[j]
		}
		m := crypto.Hash(crypto.MD5).New()
		m.Write(p.Secret)
		m.Write(pass[i*16 : i*16+16])
		md = m.Sum(nil)
	}
	outputPass = bytes.TrimRight(outputPass, string([]rune{0}))
	avpP := &PasswordAVP{
		Value: string(outputPass),
	}
	avpP.SetPacket(p)
	return avpP, nil
}
开发者ID:keysonZZZ,项目名称:kmg,代码行数:35,代码来源:avp.go


示例3: fetchCert

func fetchCert(address string) (*cert, error) {
	//fetch cert over network
	addr, err := net.ResolveTCPAddr("tcp", address)
	if err != nil {
		return nil, err
	}
	netCon, err := net.DialTCP("tcp", nil, addr)
	if err != nil {
		return nil, err
	}
	host := strings.Split(address, ":")[0]

	config := &tls.Config{
		NextProtos:         []string{"http"},
		ServerName:         host,
		InsecureSkipVerify: true,
	}
	log.Println("getting cert for: ", host)
	client := tls.Client(netCon, config)
	err = client.Handshake()
	if err != nil {
		return nil, err
	}
	state := client.ConnectionState()
	if len(state.PeerCertificates) == 0 {
		return nil, errors.New("no cert recieved from host")
	}
	for i := range state.PeerCertificates {

		log.Println(state.PeerCertificates[i].Subject)
		certRaw := state.PeerCertificates[i].Raw
		sha := crypto.Hash(crypto.SHA1).New()
		sha.Write(certRaw)
		myFP := hex.EncodeToString(sha.Sum(nil))
		myFP = fingerPrintStr(myFP).String()

		log.Println(myFP)
		log.Println("---")
	}
	certRaw := state.PeerCertificates[0].Raw

	sha := crypto.Hash(crypto.SHA1).New()
	sha.Write(certRaw)

	client.Close()
	netCon.Close()

	c := &cert{state.PeerCertificates[0], sha.Sum(nil)}
	return c, nil
}
开发者ID:Safe3,项目名称:convergence,代码行数:50,代码来源:networkPerspective.go


示例4: prfAndHashForVersion

func prfAndHashForVersion(version uint16, suite *cipherSuite) (func(result, secret, label, seed []byte), crypto.Hash) {
	switch version {
	case VersionSSL30:
		return prf30, crypto.Hash(0)
	case VersionTLS10, VersionTLS11:
		return prf10, crypto.Hash(0)
	case VersionTLS12:
		if suite.flags&suiteSHA384 != 0 {
			return prf12(sha512.New384), crypto.SHA384
		}
		return prf12(sha256.New), crypto.SHA256
	default:
		panic("unknown version")
	}
}
开发者ID:RajibTheKing,项目名称:gcc,代码行数:15,代码来源:prf.go


示例5: signResponse

func (r NotaryResponse) signResponse(response []byte) ([]byte, error) {
	hash := crypto.Hash(crypto.SHA1).New()
	hash.Write(response)
	hashed := hash.Sum(nil)

	return rsa.SignPKCS1v15(rand.Reader, r.privateKey, crypto.SHA1, hashed)
}
开发者ID:Safe3,项目名称:convergence,代码行数:7,代码来源:common.go


示例6: Sign

// Sign signs the given message with priv.
// Ed25519 performs two passes over messages to be signed and therefore cannot
// handle pre-hashed messages. Thus opts.HashFunc() must return zero to
// indicate the message hasn't been hashed. This can be achieved by passing
// crypto.Hash(0) as the value for opts.
func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) {
	if opts.HashFunc() != crypto.Hash(0) {
		return nil, errors.New("ed25519: cannot sign hashed message")
	}

	return Sign(priv, message), nil
}
开发者ID:Rudloff,项目名称:platform,代码行数:12,代码来源:ed25519.go


示例7: getHashForOID

func getHashForOID(oid asn1.ObjectIdentifier) (crypto.Hash, error) {
	switch {
	case oid.Equal(oidDigestAlgorithmSHA1):
		return crypto.SHA1, nil
	}
	return crypto.Hash(0), ErrUnsupportedAlgorithm
}
开发者ID:GauntletWizard,项目名称:vault,代码行数:7,代码来源:pkcs7.go


示例8: Encode

func (p *Packet) Encode(b []byte) (n int, ret []byte, err error) {
	b[0] = uint8(p.Code)
	b[1] = uint8(p.Identifier)
	copy(b[4:20], p.Authenticator[:])
	written := 20
	bb := b[20:]
	for i, _ := range p.AVPs {
		n, err = p.AVPs[i].Encode(bb)
		written += n
		if err != nil {
			return written, nil, err
		}
		bb = bb[n:]
	}
	//check if written too big.
	binary.BigEndian.PutUint16(b[2:4], uint16(written))

	// fix up the authenticator
	hasher := crypto.Hash(crypto.MD5).New()
	hasher.Write(b[:written])
	hasher.Write([]byte(p.server.secret))
	copy(b[4:20], hasher.Sum(nil))

	return written, b, err
}
开发者ID:karlpilkington,项目名称:radius-1,代码行数:25,代码来源:packet.go


示例9: getHashName

// this is ugly.
func getHashName(h hash.Hash) string {
	hn := reflect.TypeOf(h).String()
	fields := strings.Split(hn, ".")
	var hashName string
	hashName = fields[0]
	if strings.HasPrefix(fields[0], "*") {
		hashName = fields[0][1:]
	}
	elem := reflect.ValueOf(h).Elem()
	switch hashName {
	case "sha256":
		f := elem.FieldByName("is224")
		if f.IsValid() {
			if f.Bool() {
				hashName = "sha224"
			}
		}
		break
	case "sha512":
		f := elem.FieldByName("function")
		if f.IsValid() {
			if crypto.Hash(f.Uint()) == crypto.SHA384 {
				hashName = "sha384"
			}
		}
		break
	}
	return hashName
}
开发者ID:vbatts,项目名称:gossl,代码行数:30,代码来源:hmac.go


示例10: appleResponse

// appleResponse takes an Apple-Challenge header value, and constructs a response for it.
// To derive the response, the IP and MAC of the connection are needed, so the local address
// has to be passed in.
func appleResponse(challenge string, addr net.Addr) (c64 string, err error) {
	// iTunes seems to not pad things. Let's fix that.
	p64 := base64pad(challenge)
	ptext, err := base64.StdEncoding.DecodeString(p64)
	if err != nil {
		return
	}

	ptext = append(ptext, GetIP(addr)...)
	ptext = append(ptext, GetMAC(addr)...)
	for len(ptext) < 0x20 {
		ptext = append(ptext, 0)
	}

	ctext, err := rsa.SignPKCS1v15(nil, rsaPrivKey, crypto.Hash(0), ptext)
	if err != nil {
		return
	}
	c64 = base64.StdEncoding.EncodeToString(ctext)

	// We should respond in kind to iTunes
	if len(p64) != len(challenge) {
		c64 = base64unpad(c64)
	}

	return
}
开发者ID:frodosens,项目名称:go-airplay,代码行数:30,代码来源:auth.go


示例11: ParseRequest

// ParseRequest parses an OCSP request in DER form. It only supports
// requests for a single certificate. Signed requests are not supported.
// If a request includes a signature, it will result in a ParseError.
func ParseRequest(bytes []byte) (*Request, error) {
	var req ocspRequest
	rest, err := asn1.Unmarshal(bytes, &req)
	if err != nil {
		return nil, err
	}
	if len(rest) > 0 {
		return nil, ParseError("trailing data in OCSP request")
	}

	if len(req.TBSRequest.RequestList) == 0 {
		return nil, ParseError("OCSP request contains no request body")
	}
	innerRequest := req.TBSRequest.RequestList[0]

	hashFunc := getHashAlgorithmFromOID(innerRequest.Cert.HashAlgorithm.Algorithm)
	if hashFunc == crypto.Hash(0) {
		return nil, ParseError("OCSP request uses unknown hash function")
	}

	return &Request{
		HashAlgorithm:  hashFunc,
		IssuerNameHash: innerRequest.Cert.NameHash,
		IssuerKeyHash:  innerRequest.Cert.IssuerKeyHash,
		SerialNumber:   innerRequest.Cert.SerialNumber,
	}, nil
}
开发者ID:spazbite187,项目名称:snatchtls,代码行数:30,代码来源:ocsp.go


示例12: Restore

// Restore resets the digest to the given state.
func (d *digest) Restore(state []byte) error {
	decoder := gob.NewDecoder(bytes.NewReader(state))

	var function uint

	// We decode this way so that we do not have
	// to export these fields of the digest struct.
	vals := []interface{}{
		&d.h, &d.x, &d.nx, &d.len, &function,
	}

	for _, val := range vals {
		if err := decoder.Decode(val); err != nil {
			return err
		}
	}

	switch crypto.Hash(function) {
	case crypto.SHA224:
		d.is224 = true
	case crypto.SHA256:
		d.is224 = false
	default:
		return resumable.ErrBadState
	}

	return nil
}
开发者ID:digitalfishpond,项目名称:dashboard,代码行数:29,代码来源:resume.go


示例13: getHashAlgorithmFromOID

// TODO(rlb): This is not taken from crypto/x509, but it's of the same general form.
func getHashAlgorithmFromOID(target asn1.ObjectIdentifier) crypto.Hash {
	for hash, oid := range hashOIDs {
		if oid.Equal(target) {
			return hash
		}
	}
	return crypto.Hash(0)
}
开发者ID:spazbite187,项目名称:snatchtls,代码行数:9,代码来源:ocsp.go


示例14: TestResultUnsupportedAlgorithmWillCauseNewHmacAuthToPanic

func TestResultUnsupportedAlgorithmWillCauseNewHmacAuthToPanic(t *testing.T) {
	defer func() {
		err := recover()
		assert.Equal(t, err,
			"hmacauth: hash algorithm #0 is unavailable")
	}()
	NewHmacAuth(crypto.Hash(0), nil, "", nil)
}
开发者ID:18F,项目名称:hmacauth,代码行数:8,代码来源:hmacauth_test.go


示例15: TestUnsupportedHashAlgorithm

func TestUnsupportedHashAlgorithm(t *testing.T) {
	algorithm, err := DigestNameToCryptoHash("unsupported")
	assert.NotEqual(t, err, nil)
	assert.Equal(t, err.Error(),
		"hmacauth: hash algorithm not supported: unsupported")
	assert.Equal(t, algorithm, crypto.Hash(0))
	assert.Equal(t, algorithm.Available(), false)
}
开发者ID:18F,项目名称:hmacauth,代码行数:8,代码来源:hmacauth_test.go


示例16: hashForServerKeyExchange

// hashForServerKeyExchange hashes the given slices and returns their digest
// and the identifier of the hash function used. The sigAndHash argument is
// only used for >= TLS 1.2 and precisely identifies the hash function to use.
func hashForServerKeyExchange(sigAndHash signatureAndHash, version uint16, slices ...[]byte) ([]byte, crypto.Hash, error) {
	if version >= VersionTLS12 {
		if !isSupportedSignatureAndHash(sigAndHash, supportedSignatureAlgorithms) {
			return nil, crypto.Hash(0), errors.New("tls: unsupported hash function used by peer")
		}
		hashFunc, err := lookupTLSHash(sigAndHash.hash)
		if err != nil {
			return nil, crypto.Hash(0), err
		}
		h := hashFunc.New()
		for _, slice := range slices {
			h.Write(slice)
		}
		digest := h.Sum(nil)
		return digest, hashFunc, nil
	}
	if sigAndHash.signature == signatureECDSA {
		return sha1Hash(slices), crypto.SHA1, nil
	}
	return md5SHA1Hash(slices), crypto.MD5SHA1, nil
}
开发者ID:josharian,项目名称:go.ssa,代码行数:24,代码来源:key_agreement.go


示例17: TestUnpaddedSignature

func TestUnpaddedSignature(t *testing.T) {
	msg := []byte("Thu Dec 19 18:06:16 EST 2013\n")
	// This base64 value was generated with:
	// % echo Thu Dec 19 18:06:16 EST 2013 > /tmp/msg
	// % openssl rsautl -sign -inkey key -out /tmp/sig -in /tmp/msg
	//
	// Where "key" contains the RSA private key given at the bottom of this
	// file.
	expectedSig := decodeBase64("pX4DR8azytjdQ1rtUiC040FjkepuQut5q2ZFX1pTjBrOVKNjgsCDyiJDGZTCNoh9qpXYbhl7iEym30BWWwuiZg==")

	sig, err := SignPKCS1v15(nil, rsaPrivateKey, crypto.Hash(0), msg)
	if err != nil {
		t.Fatalf("SignPKCS1v15 failed: %s", err)
	}
	if !bytes.Equal(sig, expectedSig) {
		t.Fatalf("signature is not expected value: got %x, want %x", sig, expectedSig)
	}
	if err := VerifyPKCS1v15(&rsaPrivateKey.PublicKey, crypto.Hash(0), msg, sig); err != nil {
		t.Fatalf("signature failed to verify: %s", err)
	}
}
开发者ID:h8liu,项目名称:golang,代码行数:21,代码来源:pkcs1v15_test.go


示例18: IssueToken

// IssueToken creates a new Token for the authenticated user. Callers should
// prefill the Token with whatever values they like and leave zero values
// to be set.
// The generated token will also be persisted and can be handed to the client
// with no more handling.
func (p *Passenger) IssueToken(ctx context.Context, token *model.Token) (string, error) {
	now := time.Now()

	token.Creation = now

	if token.Expiry == (time.Time{}) {
		token.Expiry = now.Add(defaultValidity)
	} else {
		if token.Expiry.Before(now.Add(minValidity)) {
			return "", fmt.Errorf("passenger: token must be valid at least %s", minValidity)
		}

		if token.Expiry.After(now.Add(maxValidity)) {
			return "", fmt.Errorf("passenger: token must be valid at most %s", maxValidity)
		}
	}

	// TODO(flowlo): This will reject all scopes for now, as we are not using them.
	// As soon as we introduce scopes, this check must be rewritten accordingly.
	if len(token.Scopes) > 0 {
		return "", fmt.Errorf("passenger: unknown scopes: %s", strings.Join(token.Scopes, ", "))
	}

	if len(token.Description) > 512 || len(token.Description) < 4 {
		return "", fmt.Errorf("passenger: description has bad len %d", len(token.Description))
	}

	var raw [tokenLength]byte

	if _, err := rand.Read(raw[:]); err != nil {
		return "", err
	}

	if token.Hash == 0 {
		token.Hash = int(defaultHash)
	}
	token.Digest = crypto.Hash(token.Hash).New().Sum(raw[:])

	// TODO(flowlo): Set token.RemoteAddr.

	clone := Passenger{
		User:  p.User,
		Token: token,
	}

	key, err := clone.Save(ctx)
	if err != nil {
		return "", err
	}

	return encodeToken(key, &raw)
}
开发者ID:flowlo,项目名称:coduno-api,代码行数:57,代码来源:passenger.go


示例19: check

func (p *Passenger) check(raw []byte) error {
	digest := crypto.Hash(p.Token.Hash).New().Sum(raw)

	if subtle.ConstantTimeCompare(digest, p.Token.Digest) != 1 {
		return ErrDigestMismatch
	}

	if p.Token.Expiry.Before(time.Now()) {
		return ErrTokenExpired
	}

	return nil
}
开发者ID:flowlo,项目名称:coduno-api,代码行数:13,代码来源:passenger.go


示例20: check

func (p *Passenger) check(raw []byte) error {
	digest := crypto.Hash(p.AccessToken.Hash).New().Sum(raw)

	if !bytes.Equal(digest, p.AccessToken.Digest) {
		return ErrDigestMismatch
	}

	if p.AccessToken.Expiry.Before(time.Now()) {
		return ErrTokenExpired
	}

	return nil
}
开发者ID:tudorgergely,项目名称:api,代码行数:13,代码来源:passenger.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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