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

Golang hmac.Equal函数代码示例

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

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



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


示例16: verifyMAC

func (wm *WhisperMessage) verifyMAC(senderIdentity, receiverIdentity *IdentityKey, macKey []byte) bool {
	macpos := len(wm.serialized) - macLength

	ourMAC := getMac(wm.Version, senderIdentity, receiverIdentity, macKey, wm.serialized[:macpos])
	theirMAC := wm.serialized[macpos:]
	return hmac.Equal(ourMAC, theirMAC)
}
开发者ID:elimisteve,项目名称:textsecure,代码行数:7,代码来源:messages.go


示例17: processEncryptionBlock

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

	blockNum := encryptionBlockNumber(bl.seqno - 1)

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

	nonce := ds.nonce.ForPayloadBox(blockNum)
	ciphertext := bl.PayloadCiphertext
	hash := sha512.Sum512(ciphertext)

	hashBox := ds.tagKey.Box(nonce, hash[:])
	ourAuthenticator := hashBox[:secretbox.Overhead]

	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:mark-adams,项目名称:client,代码行数:30,代码来源:decrypt.go


示例18: TestCreateSignature

func TestCreateSignature(t *testing.T) {
	errStr := "Function return different result with the same parameters!"

	a := createSignature(secret, []byte("foo"), []byte("bar"))
	b := a

	if !hmac.Equal(a, b) {
		t.Errorf(errStr)
	}

	c := createSignature(secret, []byte("foo"), []byte("baz"))

	if hmac.Equal(a, c) {
		t.Errorf(errStr)
	}
}
开发者ID:urlist,项目名称:securecookie,代码行数:16,代码来源:securecookie_test.go


示例19: Decrypt

// Decrypt checks the MAC then decrypts ciphertext into plaintext.
func (c *Crypter) Decrypt(ciphertext []byte) ([]byte, error) {
	var ed EncryptedData
	if err := proto.Unmarshal(ciphertext, &ed); err != nil {
		return nil, err
	}

	// TODO(tmroeder): we're currently mostly ignoring the CryptoHeader,
	// since we only have one key.
	if *ed.Header.Version != CryptoVersion_CRYPTO_VERSION_1 {
		return nil, newError("bad version")
	}

	// Check the HMAC before touching the ciphertext.
	fullCiphertext := make([]byte, len(ed.Iv)+len(ed.Ciphertext))
	copy(fullCiphertext, ed.Iv)
	copy(fullCiphertext[len(ed.Iv):], ed.Ciphertext)

	mac := hmac.New(sha256.New, c.hmacKey)
	mac.Write(fullCiphertext)
	m := mac.Sum(nil)
	if !hmac.Equal(m, ed.Mac) {
		return nil, newError("bad HMAC")
	}

	block, err := aes.NewCipher(c.aesKey)
	if err != nil {
		return nil, err
	}

	s := cipher.NewCTR(block, ed.Iv)
	data := make([]byte, len(ed.Ciphertext))
	s.XORKeyStream(data, ed.Ciphertext)
	return data, nil
}
开发者ID:tmroeder,项目名称:cloudproxy,代码行数:35,代码来源:keys.go


示例20: ValidateChallenge

// ValidateAuthorizeCodeSignature returns an AuthorizeCode, if the code argument is a valid authorize code
// and the signature matches the key.
func (c *HMACSHAEnigma) ValidateChallenge(secret []byte, t *Challenge) (err error) {
	if t.Key == "" || t.Signature == "" {
		return errors.New("Key and signature must both be not empty")
	}

	signature, err := b64.DecodeString(t.Signature)
	if err != nil {
		return err
	}

	key, err := b64.DecodeString(t.Key)
	if err != nil {
		return err
	}

	useSecret := append([]byte{}, c.GlobalSecret...)
	mac := hmac.New(sha256.New, append(useSecret, secret...))
	_, err = mac.Write(key)
	if err != nil {
		return errors.New(err)
	}

	if !hmac.Equal(signature, mac.Sum([]byte{})) {
		// Hash is invalid
		return errors.New("Key and signature do not match")
	}

	return nil
}
开发者ID:ajayk,项目名称:fosite,代码行数:31,代码来源:hmacsha.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang hmac.New函数代码示例发布时间:2022-05-24
下一篇:
Golang elliptic.Curve类代码示例发布时间: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