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


Golang subtle.ConstantTimeCompare函数代码示例

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


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

示例1: VerifyPKCS1v15

// VerifyPKCS1v15 verifies an RSA PKCS#1 v1.5 signature.
// hashed is the result of hashing the input message using the given hash
// function and sig is the signature. A valid signature is indicated by
// returning a nil error.
func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) (err error) {
	hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
	if err != nil {
		return
	}

	tLen := len(prefix) + hashLen
	k := (pub.N.BitLen() + 7) / 8
	if k < tLen+11 {
		err = VerificationError{}
		return
	}

	c := new(big.Int).SetBytes(sig)
	m := encrypt(new(big.Int), pub, c)
	em := leftPad(m.Bytes(), k)
	// EM = 0x00 || 0x01 || PS || 0x00 || T

	ok := subtle.ConstantTimeByteEq(em[0], 0)
	ok &= subtle.ConstantTimeByteEq(em[1], 1)
	ok &= subtle.ConstantTimeCompare(em[k-hashLen:k], hashed)
	ok &= subtle.ConstantTimeCompare(em[k-tLen:k-hashLen], prefix)
	ok &= subtle.ConstantTimeByteEq(em[k-tLen-1], 0)

	for i := 2; i < k-tLen-1; i++ {
		ok &= subtle.ConstantTimeByteEq(em[i], 0xff)
	}

	if ok != 1 {
		return VerificationError{}
	}

	return nil
}
开发者ID:krasin,项目名称:go-deflate,代码行数:38,代码来源:pkcs1v15.go

示例2: CheckAuth

/*
 Checks the username/password combination from the request. Returns
 either an empty string (authentication failed) or the name of the
 authenticated user.

 Supports MD5 and SHA1 password entries
*/
func (a *BasicAuth) CheckAuth(r *http.Request) string {
	s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
	if len(s) != 2 || s[0] != "Basic" {
		return ""
	}

	b, err := base64.StdEncoding.DecodeString(s[1])
	if err != nil {
		return ""
	}
	pair := strings.SplitN(string(b), ":", 2)
	if len(pair) != 2 {
		return ""
	}
	passwd := a.Secrets(pair[0], a.Realm)
	if passwd == "" {
		return ""
	}
	if strings.HasPrefix(passwd, "{SHA}") {
		d := sha1.New()
		d.Write([]byte(pair[1]))
		if subtle.ConstantTimeCompare([]byte(passwd[5:]), []byte(base64.StdEncoding.EncodeToString(d.Sum(nil)))) != 1 {
			return ""
		}
	} else {
		e := NewMD5Entry(passwd)
		if e == nil {
			return ""
		}
		if subtle.ConstantTimeCompare([]byte(passwd), MD5Crypt([]byte(pair[1]), e.Salt, e.Magic)) != 1 {
			return ""
		}
	}
	return pair[0]
}
开发者ID:vsheffer,项目名称:go-http-auth,代码行数:42,代码来源:basic.go

示例3: secureCompare

func secureCompare(given, actual string) bool {
	if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
		return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
	}
	/* Securely compare actual to itself to keep constant time, but always return false */
	return subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 && false
}
开发者ID:hiproz,项目名称:thinkgo,代码行数:7,代码来源:auth.go

示例4: CheckHashes

// CheckHashes verifies all the checksums specified by the "hashes" of the payload.
func CheckHashes(payload []byte, hashes Hashes) error {
	cnt := 0

	// k, v indicate the hash algorithm and the corresponding value
	for k, v := range hashes {
		switch k {
		case notary.SHA256:
			checksum := sha256.Sum256(payload)
			if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
				return ErrMismatchedChecksum{alg: notary.SHA256}
			}
			cnt++
		case notary.SHA512:
			checksum := sha512.Sum512(payload)
			if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
				return ErrMismatchedChecksum{alg: notary.SHA512}
			}
			cnt++
		}
	}

	if cnt == 0 {
		return fmt.Errorf("at least one supported hash needed")
	}

	return nil
}
开发者ID:beerbubble,项目名称:docker,代码行数:28,代码来源:types.go

示例5: CheckHashes

// CheckHashes verifies all the checksums specified by the "hashes" of the payload.
func CheckHashes(payload []byte, name string, hashes Hashes) error {
	cnt := 0

	// k, v indicate the hash algorithm and the corresponding value
	for k, v := range hashes {
		switch k {
		case notary.SHA256:
			checksum := sha256.Sum256(payload)
			if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
				return ErrMismatchedChecksum{alg: notary.SHA256, name: name, expected: hex.EncodeToString(v)}
			}
			cnt++
		case notary.SHA512:
			checksum := sha512.Sum512(payload)
			if subtle.ConstantTimeCompare(checksum[:], v) == 0 {
				return ErrMismatchedChecksum{alg: notary.SHA512, name: name, expected: hex.EncodeToString(v)}
			}
			cnt++
		}
	}

	if cnt == 0 {
		return ErrMissingMeta{Role: name}
	}

	return nil
}
开发者ID:mbentley,项目名称:notary,代码行数:28,代码来源:types.go

示例6: TestDecodeHashPayloadReturnsCorrectString

func TestDecodeHashPayloadReturnsCorrectString(t *testing.T) {

	hashPayload := "9:1111:64:bXlzYWx0:bXlwYXNzd29yZA=="

	r, n, l, salt, p, err := decodeHashPaylaod(hashPayload)

	if err != nil {
		t.Errorf("Error encountered, %v", err)
	}

	saltRes := subtle.ConstantTimeCompare(salt, []byte("mysalt"))
	pRes := subtle.ConstantTimeCompare(p, []byte("mypassword"))

	if !(saltRes == 1) {
		t.Error("aggg fucked")
	}

	if !(pRes == 1) {
		t.Errorf("incorrect password hash decoded expected: mypassword but got %s", p)
	}

	if l != 64 {
		t.Errorf("incorrect passwordHash length decoded expected: 64 but got %d", l)
	}

	if r != 9 {
		t.Errorf("incorrect number of rounds decoded expected: 9 but got %d", r)
	}
	if n != 1111 {
		t.Errorf("incorrect cost decoded expected: 1111 but got %d", n)
	}
}
开发者ID:richardbowden,项目名称:passwordHash,代码行数:32,代码来源:scramble_test.go

示例7: NewHtpasswdValidator

func NewHtpasswdValidator(filename string) Validator {
	provider := HtpasswdFileProvider(filename)

	return func(username string, passwd string) bool {
		// realm is ignored
		hashedPw := provider(username, "")

		if strings.HasPrefix(hashedPw, "{SHA}") {
			d := sha1.New()
			d.Write([]byte(passwd))

			if subtle.ConstantTimeCompare([]byte(hashedPw[5:]), []byte(base64.StdEncoding.EncodeToString(d.Sum(nil)))) != 1 {
				return false
			}
		} else {
			e := NewMD5Entry(hashedPw)
			if e == nil {
				return false
			}
			if subtle.ConstantTimeCompare([]byte(hashedPw), MD5Crypt([]byte(passwd), e.Salt, e.Magic)) != 1 {
				return false
			}
		}
		return true
	}
}
开发者ID:mtanlee,项目名称:garita,代码行数:26,代码来源:htpasswd.go

示例8: validateMetadata

// validateMetadata matches the given client nonce and pending time with the
// one cached in the identity whitelist during the previous login. But, if
// reauthentication is disabled, login attempt is failed immediately.
func validateMetadata(clientNonce, pendingTime string, storedIdentity *whitelistIdentity, roleEntry *awsRoleEntry) error {
	// For sanity
	if !storedIdentity.DisallowReauthentication && storedIdentity.ClientNonce == "" {
		return fmt.Errorf("client nonce missing in stored identity")
	}

	// If reauthentication is disabled or if the nonce supplied matches a
	// predefied nonce which indicates reauthentication to be disabled,
	// authentication will not succeed.
	if storedIdentity.DisallowReauthentication ||
		subtle.ConstantTimeCompare([]byte(reauthenticationDisabledNonce), []byte(clientNonce)) == 1 {
		return fmt.Errorf("reauthentication is disabled")
	}

	givenPendingTime, err := time.Parse(time.RFC3339, pendingTime)
	if err != nil {
		return err
	}

	storedPendingTime, err := time.Parse(time.RFC3339, storedIdentity.PendingTime)
	if err != nil {
		return err
	}

	// When the presented client nonce does not match the cached entry, it
	// is either that a rogue client is trying to login or that a valid
	// client suffered a migration. The migration is detected via
	// pendingTime in the instance metadata, which sadly is only updated
	// when an instance is stopped and started but *not* when the instance
	// is rebooted. If reboot survivability is needed, either
	// instrumentation to delete the instance ID from the whitelist is
	// necessary, or the client must durably store the nonce.
	//
	// If the `allow_instance_migration` property of the registered role is
	// enabled, then the client nonce mismatch is ignored, as long as the
	// pending time in the presented instance identity document is newer
	// than the cached pending time. The new pendingTime is stored and used
	// for future checks.
	//
	// This is a weak criterion and hence the `allow_instance_migration`
	// option should be used with caution.
	if subtle.ConstantTimeCompare([]byte(clientNonce), []byte(storedIdentity.ClientNonce)) != 1 {
		if !roleEntry.AllowInstanceMigration {
			return fmt.Errorf("client nonce mismatch")
		}
		if roleEntry.AllowInstanceMigration && !givenPendingTime.After(storedPendingTime) {
			return fmt.Errorf("client nonce mismatch and instance meta-data incorrect")
		}
	}

	// Ensure that the 'pendingTime' on the given identity document is not
	// before the 'pendingTime' that was used for previous login. This
	// disallows old metadata documents from being used to perform login.
	if givenPendingTime.Before(storedPendingTime) {
		return fmt.Errorf("instance meta-data is older than the one used for previous login")
	}
	return nil
}
开发者ID:quixoten,项目名称:vault,代码行数:61,代码来源:path_login.go

示例9: Winnow

// Winnow the data.
func Winnow(authKey *[32]byte, noncePrfx, in []byte) ([]byte, error) {
	if len(in)%EnlargeFactor != 0 {
		return nil, errors.New("Invalid data size")
	}
	out := make([]byte, len(in)/EnlargeFactor)
	keys := make([]byte, 8*64)
	nonce := make([]byte, 24)
	copy(nonce[:8], noncePrfx)
	var i int
	var v byte
	tag := new([16]byte)
	macKey := new([32]byte)
	defer zero(macKey[:])
	var is01 bool
	var is00 bool
	var is11 bool
	var is10 bool
	for n := 0; n < len(out); n++ {
		binary.BigEndian.PutUint64(nonce[16:], uint64(n))
		salsa20.XORKeyStream(keys, keys, nonce, authKey)
		v = 0
		for i = 0; i < 8; i++ {
			copy(macKey[:], keys[64*i:64*i+32])
			poly1305.Sum(tag, []byte("1"), macKey)
			is01 = subtle.ConstantTimeCompare(
				tag[:],
				in[16*(n*16+i*2):16*(n*16+i*2+1)],
			) == 1
			poly1305.Sum(tag, []byte("0"), macKey)
			is00 = subtle.ConstantTimeCompare(
				tag[:],
				in[16*(n*16+i*2):16*(n*16+i*2+1)],
			) == 1
			copy(macKey[:], keys[64*i+32:64*i+64])
			poly1305.Sum(tag, []byte("1"), macKey)
			is11 = subtle.ConstantTimeCompare(
				tag[:],
				in[16*(n*16+i*2+1):16*(n*16+i*2+2)],
			) == 1
			poly1305.Sum(tag, []byte("0"), macKey)
			is10 = subtle.ConstantTimeCompare(
				tag[:],
				in[16*(n*16+i*2+1):16*(n*16+i*2+2)],
			) == 1
			if !((is01 && is10) || (is00 && is11)) {
				zero(keys)
				return nil, errors.New("Invalid authenticator received")
			}
			if is11 {
				v = v | 1<<uint8(i)
			}
		}
		out[n] = v
		zero(keys)
	}
	return out, nil
}
开发者ID:xiaokangwang,项目名称:govpn,代码行数:58,代码来源:cnw.go

示例10: passwordCallback

func (sshClient *sshClient) passwordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {

	expectedSessionIDLength := 2 * common.PSIPHON_API_CLIENT_SESSION_ID_LENGTH
	expectedSSHPasswordLength := 2 * SSH_PASSWORD_BYTE_LENGTH

	var sshPasswordPayload struct {
		SessionId   string `json:"SessionId"`
		SshPassword string `json:"SshPassword"`
	}
	err := json.Unmarshal(password, &sshPasswordPayload)
	if err != nil {

		// Backwards compatibility case: instead of a JSON payload, older clients
		// send the hex encoded session ID prepended to the SSH password.
		// Note: there's an even older case where clients don't send any session ID,
		// but that's no longer supported.
		if len(password) == expectedSessionIDLength+expectedSSHPasswordLength {
			sshPasswordPayload.SessionId = string(password[0:expectedSessionIDLength])
			sshPasswordPayload.SshPassword = string(password[expectedSSHPasswordLength:len(password)])
		} else {
			return nil, common.ContextError(fmt.Errorf("invalid password payload for %q", conn.User()))
		}
	}

	if !isHexDigits(sshClient.sshServer.support, sshPasswordPayload.SessionId) ||
		len(sshPasswordPayload.SessionId) != expectedSessionIDLength {
		return nil, common.ContextError(fmt.Errorf("invalid session ID for %q", conn.User()))
	}

	userOk := (subtle.ConstantTimeCompare(
		[]byte(conn.User()), []byte(sshClient.sshServer.support.Config.SSHUserName)) == 1)

	passwordOk := (subtle.ConstantTimeCompare(
		[]byte(sshPasswordPayload.SshPassword), []byte(sshClient.sshServer.support.Config.SSHPassword)) == 1)

	if !userOk || !passwordOk {
		return nil, common.ContextError(fmt.Errorf("invalid password for %q", conn.User()))
	}

	sessionID := sshPasswordPayload.SessionId

	sshClient.Lock()
	sshClient.sessionID = sessionID
	geoIPData := sshClient.geoIPData
	sshClient.Unlock()

	// Store the GeoIP data associated with the session ID. This makes the GeoIP data
	// available to the web server for web transport Psiphon API requests. To allow for
	// post-tunnel final status requests, the lifetime of cached GeoIP records exceeds
	// the lifetime of the sshClient, and that's why this distinct session cache exists.
	sshClient.sshServer.support.GeoIPService.SetSessionCache(sessionID, geoIPData)

	return nil, nil
}
开发者ID:geebee,项目名称:psiphon-tunnel-core,代码行数:54,代码来源:tunnelServer.go

示例11: SecureCompare

func SecureCompare(given, actual []byte) bool {
	if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
		if subtle.ConstantTimeCompare(given, actual) == 1 {
			return true
		}
		return false
	}
	// Securely compare actual to itself to keep constant time, but always return false
	if subtle.ConstantTimeCompare(actual, actual) == 1 {
		return false
	}
	return false
}
开发者ID:sndnvaps,项目名称:util,代码行数:13,代码来源:compare.go

示例12: passwordCallback

func (sshClient *sshClient) passwordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {

	var sshPasswordPayload struct {
		SessionId   string `json:"SessionId"`
		SshPassword string `json:"SshPassword"`
	}
	err := json.Unmarshal(password, &sshPasswordPayload)
	if err != nil {

		// Backwards compatibility case: instead of a JSON payload, older clients
		// send the hex encoded session ID prepended to the SSH password.
		// Note: there's an even older case where clients don't send any session ID,
		// but that's no longer supported.
		if len(password) == 2*psiphon.PSIPHON_API_CLIENT_SESSION_ID_LENGTH+2*SSH_PASSWORD_BYTE_LENGTH {
			sshPasswordPayload.SessionId = string(password[0 : 2*psiphon.PSIPHON_API_CLIENT_SESSION_ID_LENGTH])
			sshPasswordPayload.SshPassword = string(password[2*psiphon.PSIPHON_API_CLIENT_SESSION_ID_LENGTH : len(password)])
		} else {
			return nil, psiphon.ContextError(fmt.Errorf("invalid password payload for %q", conn.User()))
		}
	}

	if !isHexDigits(sshClient.sshServer.support, sshPasswordPayload.SessionId) {
		return nil, psiphon.ContextError(fmt.Errorf("invalid session ID for %q", conn.User()))
	}

	userOk := (subtle.ConstantTimeCompare(
		[]byte(conn.User()), []byte(sshClient.sshServer.support.Config.SSHUserName)) == 1)

	passwordOk := (subtle.ConstantTimeCompare(
		[]byte(sshPasswordPayload.SshPassword), []byte(sshClient.sshServer.support.Config.SSHPassword)) == 1)

	if !userOk || !passwordOk {
		return nil, psiphon.ContextError(fmt.Errorf("invalid password for %q", conn.User()))
	}

	psiphonSessionID := sshPasswordPayload.SessionId

	sshClient.Lock()
	sshClient.psiphonSessionID = psiphonSessionID
	geoIPData := sshClient.geoIPData
	sshClient.Unlock()

	// Store the GeoIP data associated with the session ID. This makes the GeoIP data
	// available to the web server for web transport Psiphon API requests.
	sshClient.sshServer.support.GeoIPService.SetSessionCache(
		psiphonSessionID, geoIPData)

	return nil, nil
}
开发者ID:code-mx,项目名称:psiphon-tunnel-core,代码行数:49,代码来源:tunnelServer.go

示例13: Match

// Match determines whether this KeyAuthorization matches the given token and key
func (ka KeyAuthorization) Match(token string, key *jose.JsonWebKey) bool {
	if key == nil {
		return false
	}

	thumbprint, err := Thumbprint(key)
	if err != nil {
		return false
	}

	tokensEqual := subtle.ConstantTimeCompare([]byte(token), []byte(ka.Token))
	thumbprintsEqual := subtle.ConstantTimeCompare([]byte(thumbprint), []byte(ka.Thumbprint))

	return tokensEqual == 1 && thumbprintsEqual == 1
}
开发者ID:rf152,项目名称:boulder,代码行数:16,代码来源:objects.go

示例14: authenticateMessage

// Returns true if the provided message is unsigned or has a valid signature
// from one of the provided signers.
func authenticateMessage(signers map[string]Signer, header *Header, msg []byte) bool {
	digest := header.GetHmac()
	if digest != nil {
		var key string
		signer := fmt.Sprintf("%s_%d", header.GetHmacSigner(),
			header.GetHmacKeyVersion())
		if s, ok := signers[signer]; ok {
			key = s.HmacKey
		} else {
			return false
		}

		var hm hash.Hash
		switch header.GetHmacHashFunction() {
		case Header_MD5:
			hm = hmac.New(md5.New, []byte(key))
		case Header_SHA1:
			hm = hmac.New(sha1.New, []byte(key))
		}
		hm.Write(msg)
		expectedDigest := hm.Sum(nil)
		if subtle.ConstantTimeCompare(digest, expectedDigest) != 1 {
			return false
		}
	}
	return true
}
开发者ID:RogerBai,项目名称:heka,代码行数:29,代码来源:net_utils.go

示例15: Validate

func (uh *UsersSharedsecretHandler) Validate(snr *SessionNonceRequest, request *http.Request) (string, error) {

	// Parse UseridCombo.
	useridCombo := strings.SplitN(snr.UseridCombo, ":", 3)
	if len(useridCombo) < 2 {
		return "", errors.New("invalid useridcombo")
	}
	// TODO(longsleep): Add support for third field which provides the username.
	expirationString, userid := useridCombo[0], useridCombo[1]

	expiration, err := strconv.ParseInt(expirationString, 10, 64)
	if err != nil {
		return "", err
	}

	// Check expiration.
	if time.Unix(expiration, 0).Before(time.Now()) {
		return "", errors.New("expired secret")
	}

	secret := uh.createHMAC(snr.UseridCombo)
	if subtle.ConstantTimeCompare([]byte(snr.Secret), []byte(secret)) != 1 {
		return "", errors.New("invalid secret")
	}

	return userid, nil

}
开发者ID:strukturag,项目名称:spreed-webrtc,代码行数:28,代码来源:users.go


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