当前位置: 首页>>代码示例>>Golang>>正文


Golang hmac.Equal函数代码示例

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


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

示例1: authKeyIsValid

func authKeyIsValid(key []byte, r *httpRequest, windowBits uint) bool {
	if len(key) == 0 {
		return false
	}

	return hmac.Equal(key, getAuthKey(r, unixTime, windowBits)) ||
		hmac.Equal(key, getAuthKey(r, unixTime-2-uint64(math.Pow(float64(windowBits), 2)), windowBits))
}
开发者ID:Freeaqingme,项目名称:Webjobber,代码行数:8,代码来源:authkey.go

示例2: TestKDF

func TestKDF(t *testing.T) {
	kdf1 := kdf.KDF([]byte("aardvark"), kdf.DefaultSalt, kdf.DefaultReps)
	kdf2 := kdf.KDF([]byte("aardvark"), kdf.DefaultSalt, kdf.DefaultReps)
	if !hmac.Equal(kdf1, kdf2) {
		t.Error("Expected kdf's to be equal")
	}
	if hmac.Equal(kdf1, kdf.KDF([]byte("sailboat"), kdf.DefaultSalt, kdf.DefaultReps)) {
		t.Error("Expected kdf's not to be equal")
	}
	if len(kdf1) != 32 {
		t.Error("Expected key to be 32 bytes")
	}
}
开发者ID:keep94,项目名称:appcommon,代码行数:13,代码来源:kdf_test.go

示例3: ReadMsg

func (rw *rlpxFrameRW) ReadMsg() (msg Msg, err error) {
	// read the header
	headbuf := make([]byte, 32)
	if _, err := io.ReadFull(rw.conn, headbuf); err != nil {
		return msg, err
	}
	// verify header mac
	shouldMAC := updateMAC(rw.ingressMAC, rw.macCipher, headbuf[:16])
	if !hmac.Equal(shouldMAC, headbuf[16:]) {
		return msg, errors.New("bad header MAC")
	}
	rw.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted
	fsize := readInt24(headbuf)
	// ignore protocol type for now

	// read the frame content
	var rsize = fsize // frame size rounded up to 16 byte boundary
	if padding := fsize % 16; padding > 0 {
		rsize += 16 - padding
	}
	framebuf := make([]byte, rsize)
	if _, err := io.ReadFull(rw.conn, framebuf); err != nil {
		return msg, err
	}

	// read and validate frame MAC. we can re-use headbuf for that.
	rw.ingressMAC.Write(framebuf)
	fmacseed := rw.ingressMAC.Sum(nil)
	if _, err := io.ReadFull(rw.conn, headbuf[:16]); err != nil {
		return msg, err
	}
	shouldMAC = updateMAC(rw.ingressMAC, rw.macCipher, fmacseed)
	if !hmac.Equal(shouldMAC, headbuf[:16]) {
		return msg, errors.New("bad frame MAC")
	}

	// decrypt frame content
	rw.dec.XORKeyStream(framebuf, framebuf)

	// decode message code
	content := bytes.NewReader(framebuf[:fsize])
	if err := rlp.Decode(content, &msg.Code); err != nil {
		return msg, err
	}
	msg.Size = uint32(content.Len())
	msg.Payload = content
	return msg, nil
}
开发者ID:ruflin,项目名称:go-ethereum,代码行数:48,代码来源:rlpx.go

示例4: processEncryptionBlock

func (ds *decryptStream) processEncryptionBlock(bl *encryptionBlock) ([]byte, error) {

	blockNum := encryptionBlockNumber(bl.seqno - 1)

	if err := blockNum.check(); err != nil {
		return nil, err
	}

	nonce := nonceForChunkSecretBox(blockNum)
	ciphertext := bl.PayloadCiphertext

	// Check the authenticator.
	hashToAuthenticate := computePayloadHash(ds.headerHash, nonce, ciphertext)
	ourAuthenticator := hmacSHA512256(ds.macKey, hashToAuthenticate)
	if !hmac.Equal(ourAuthenticator, bl.HashAuthenticators[ds.position]) {
		return nil, ErrBadTag(bl.seqno)
	}

	plaintext, ok := secretbox.Open([]byte{}, ciphertext, (*[24]byte)(nonce), (*[32]byte)(ds.payloadKey))
	if !ok {
		return nil, ErrBadCiphertext(bl.seqno)
	}

	// The encoding of the empty buffer implies the EOF.  But otherwise, all mechanisms are the same.
	if len(plaintext) == 0 {
		return nil, nil
	}
	return plaintext, nil
}
开发者ID:qbit,项目名称:client,代码行数:29,代码来源:decrypt.go

示例5: readMessage

func (ath *AuthReadWriter) readMessage() ([]byte, error) {
	header := make([]byte, 28+4)

	if _, err := io.ReadFull(ath.rwc, header); err != nil {
		return nil, err
	}

	size := binary.LittleEndian.Uint32(header[28:])
	if size > MaxMessageSize {
		return nil, fmt.Errorf("Message too large (%d/%d)", size, MaxMessageSize)
	}

	buf := make([]byte, size)

	if _, err := io.ReadAtLeast(ath.crypted, buf, int(size)); err != nil {
		return nil, err
	}

	macWriter := hmac.New(sha3.New224, ath.symkey)
	if _, err := macWriter.Write(buf); err != nil {
		return nil, err
	}

	mac := macWriter.Sum(nil)
	if !hmac.Equal(mac, header[:28]) {
		return nil, fmt.Errorf("Mac differs in received metadata message")
	}

	return buf, nil
}
开发者ID:disorganizer,项目名称:brig,代码行数:30,代码来源:authrw.go

示例6: verifySignature

func verifySignature(p7 *PKCS7, signer signerInfo) error {
	if len(signer.AuthenticatedAttributes) > 0 {
		// TODO(fullsailor): First check the content type match
		var digest []byte
		err := unmarshalAttribute(signer.AuthenticatedAttributes, oidAttributeMessageDigest, &digest)
		if err != nil {
			return err
		}
		hash, err := getHashForOID(signer.DigestAlgorithm.Algorithm)
		if err != nil {
			return err
		}
		h := hash.New()
		h.Write(p7.Content)
		computed := h.Sum(nil)
		if !hmac.Equal(digest, computed) {
			return &MessageDigestMismatchError{
				ExpectedDigest: digest,
				ActualDigest:   computed,
			}
		}
	}
	cert := getCertFromCertsByIssuerAndSerial(p7.Certificates, signer.IssuerAndSerialNumber)
	if cert == nil {
		return errors.New("pkcs7: No certificate for signer")
	}
	// TODO(fullsailor): Optionally verify certificate chain
	// TODO(fullsailor): Optionally verify signingTime against certificate NotAfter/NotBefore
	encodedAttributes, err := marshalAttributes(signer.AuthenticatedAttributes)
	if err != nil {
		return err
	}
	algo := x509.SHA1WithRSA
	return cert.CheckSignature(algo, encodedAttributes, signer.EncryptedDigest)
}
开发者ID:GauntletWizard,项目名称:vault,代码行数:35,代码来源:pkcs7.go

示例7: Decode

// Decode decodes the given token and return its data
// and creation time in UTC.
func (tok *T) Decode(token []byte) (data []byte, creation time.Time, err error) {
	raw := make([]byte, base64.RawURLEncoding.DecodedLen(len(token)))
	n, err := base64.RawURLEncoding.Decode(raw, token)
	if err != nil {
		return nil, time.Time{}, err
	}
	raw = raw[:n]
	hash := tok.hmac()
	if len(raw) < aes.BlockSize*2+hash.Size() {
		return nil, time.Time{}, ErrInvalidToken
	}
	soff := len(raw) - hash.Size() // signature offset
	hash.Write(raw[:soff])
	want := hash.Sum(nil)
	have := raw[soff:]
	if !hmac.Equal(want, have) {
		return nil, time.Time{}, ErrInvalidTokenSignature
	}
	iv := raw[:aes.BlockSize]
	body := raw[aes.BlockSize:soff]
	if len(body)%aes.BlockSize != 0 {
		return nil, time.Time{}, ErrInvalidToken
	}
	mode := cipher.NewCBCDecrypter(tok.aes, iv)
	mode.CryptBlocks(body, body)
	ts := time.Unix(int64(binary.BigEndian.Uint32(body)), 0)
	body, err = pkcs7Unpad(body, aes.BlockSize)
	if err != nil {
		return nil, time.Time{}, err
	}
	return body[4:], ts.UTC(), nil
}
开发者ID:go-web,项目名称:tokenizer,代码行数:34,代码来源:token.go

示例8: Decrypt

// Decrypt authentications and recovers the original message from
// its input using the private key and the ephemeral key included in
// the message.
func Decrypt(priv *ecdsa.PrivateKey, in []byte) (out []byte, err error) {
	ephLen := int(in[0])
	ephPub := in[1 : 1+ephLen]
	ct := in[1+ephLen:]
	if len(ct) < (sha1.Size + aes.BlockSize) {
		return nil, errors.New("Invalid ciphertext")
	}

	x, y := elliptic.Unmarshal(Curve(), ephPub)
	if x == nil {
		return nil, errors.New("Invalid public key")
	}

	x, _ = priv.Curve.ScalarMult(x, y, priv.D.Bytes())
	if x == nil {
		return nil, errors.New("Failed to generate encryption key")
	}
	shared := sha256.Sum256(x.Bytes())

	tagStart := len(ct) - sha1.Size
	h := hmac.New(sha1.New, shared[16:])
	h.Write(ct[:tagStart])
	mac := h.Sum(nil)
	if !hmac.Equal(mac, ct[tagStart:]) {
		return nil, errors.New("Invalid MAC")
	}

	paddedOut, err := symcrypt.DecryptCBC(ct[aes.BlockSize:tagStart], ct[:aes.BlockSize], shared[:16])
	if err != nil {
		return
	}
	out, err = padding.RemovePadding(paddedOut)
	return
}
开发者ID:hannson,项目名称:redoctober,代码行数:37,代码来源:ecdh.go

示例9: checkMAC

func checkMAC(salt, message, messageMAC, key []byte) bool {
	mac := hmac.New(sha256.New, key)
	mac.Write(message)
	mac.Write(salt)
	expectedMAC := mac.Sum(nil)
	return hmac.Equal(messageMAC, expectedMAC)
}
开发者ID:HeWhoWas,项目名称:mokey,代码行数:7,代码来源:token.go

示例10: Authenticate

func (TokenAuth) Authenticate(token string) (types.Uid, time.Time, int) {
	var zeroTime time.Time
	// [8:UID][4:expires][32:signature] == 44 bytes

	data, err := base64.URLEncoding.DecodeString(token)
	if err != nil {
		return types.ZeroUid, zeroTime, auth.ErrMalformed
	}

	if len(data) != token_len_decoded {
		return types.ZeroUid, zeroTime, auth.ErrMalformed
	}

	var uid types.Uid
	if err := uid.UnmarshalBinary(data[0:8]); err != nil {
		return types.ZeroUid, zeroTime, auth.ErrMalformed
	}

	hasher := hmac.New(sha256.New, hmac_salt)
	hasher.Write(data[:12])
	if !hmac.Equal(data[12:], hasher.Sum(nil)) {
		return types.ZeroUid, zeroTime, auth.ErrFailed
	}

	expires := time.Unix(int64(binary.LittleEndian.Uint32(data[8:12])), 0).UTC()
	if expires.Before(time.Now()) {
		return types.ZeroUid, zeroTime, auth.ErrExpired
	}

	return uid, expires, auth.NoErr
}
开发者ID:ycaihua,项目名称:chat,代码行数:31,代码来源:auth_token.go

示例11: macCheckThenDecrypt

func (r *etmReader) macCheckThenDecrypt(m []byte) (int, error) {
	l := len(m)
	if l < r.mac.size {
		return 0, fmt.Errorf("buffer (%d) shorter than MAC size (%d)", l, r.mac.size)
	}

	mark := l - r.mac.size
	data := m[:mark]
	macd := m[mark:]

	r.mac.Write(data)
	expected := r.mac.Sum(nil)
	r.mac.Reset()

	// check mac. if failed, return error.
	if !hmac.Equal(macd, expected) {
		log.Debug("MAC Invalid:", expected, "!=", macd)
		return 0, ErrMACInvalid
	}

	// ok seems good. decrypt. (can decrypt in place, yay!)
	// log.Debugf("DEC ciphertext (%d): %s %v", len(data), data, data)
	r.str.XORKeyStream(data, data)
	// log.Debugf("DEC plaintext (%d): %s %v", len(data), data, data)

	return mark, nil
}
开发者ID:dignifiedquire,项目名称:go-libp2p,代码行数:27,代码来源:rw.go

示例12: CheckApiSign

// CheckApiSign validates correctness of provided (in HTTP API request) sign
// comparing it with generated one
func CheckApiSign(secret string, data []byte, providedSign string) bool {
	if len(providedSign) != HMACLength {
		return false
	}
	sign := GenerateApiSign(secret, data)
	return hmac.Equal([]byte(sign), []byte(providedSign))
}
开发者ID:sara62,项目名称:centrifugo,代码行数:9,代码来源:auth.go

示例13: CheckChannelSign

// CheckChannelSign validates a correctness of provided (in subscribe client command)
// sign comparing it with generated one
func CheckChannelSign(secret, client, channel, channelData, providedSign string) bool {
	if len(providedSign) != HMACLength {
		return false
	}
	sign := GenerateChannelSign(secret, client, channel, channelData)
	return hmac.Equal([]byte(sign), []byte(providedSign))
}
开发者ID:sara62,项目名称:centrifugo,代码行数:9,代码来源:auth.go

示例14: CheckClientToken

// CheckClientToken validates correctness of provided (by client connection) token
// comparing it with generated one
func CheckClientToken(secret, user, timestamp, info, providedToken string) bool {
	if len(providedToken) != HMACLength {
		return false
	}
	token := GenerateClientToken(secret, user, timestamp, info)
	return hmac.Equal([]byte(token), []byte(providedToken))
}
开发者ID:sara62,项目名称:centrifugo,代码行数:9,代码来源:auth.go

示例15: checkMAC

func checkMAC(mac hash.Hash, message, messageMAC []byte) bool {
	if _, err := mac.Write(message); err != nil {
		return false
	}
	expectedMAC := mac.Sum(nil)
	return hmac.Equal(messageMAC, expectedMAC)
}
开发者ID:judwhite,项目名称:ghapi,代码行数:7,代码来源:hooks.go


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