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


Golang crypto.Hash函數代碼示例

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


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


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