// Algorithm, Nonce, Realm, Charset and QOP will be set from challenge message
436911
func NewClientFromChallenge(chal []byte, opts *Options) (*Client, error) {
	m := &digest{challenge: &challenge{}, response: newResponse(opts)}

	if err := m.challenge.parseChallenge(chal); err != nil {
		return nil, err
	}
	m.response.nonce = m.challenge.nonce
	m.response.charset = m.challenge.charset
	if len(m.challenge.realms) > 0 {
		m.response.realm = m.challenge.realms[0]
	}
	if len(m.challenge.qop) > 0 {
		m.response.qop = m.challenge.qop[0]
	}

	return (*Client)(m), nil
}
906176
func AddPreCheck(preCheck PreCheckFunc) ChallengeOption {
	// Prevent race condition
	check := preCheck
	return func(chlg *Challenge) error {
		chlg.preCheck.checkFunc = func(_, fqdn, value string, _ PreCheckFunc) (bool, error) {
			if check == nil {
				return false, errors.New("invalid preCheck: preCheck is nil")
			}
			return check(fqdn, value)
		}
		return nil
	}
}
912799
func Message(locale, message string, args ...interface{}) string {
	language, region := parseLocale(locale)
	unknownValueFormat := getUnknownValueFormat()

	messageConfig, knownLanguage := messages[language]
	if !knownLanguage {
		i18nLog.Debugf("Unsupported language for locale '%s' and message '%s', trying default language", locale, message)

		if defaultLanguage, found := Config.String(defaultLanguageOption); found {
			i18nLog.Debugf("Using default language '%s'", defaultLanguage)

			messageConfig, knownLanguage = messages[defaultLanguage]
			if !knownLanguage {
				i18nLog.Debugf("Unsupported default language for locale '%s' and message '%s'", defaultLanguage, message)
				return fmt.Sprintf(unknownValueFormat, message)
			}
		} else {
			i18nLog.Warnf("Unable to find default language option (%s); messages for unsupported locales will never be translated", defaultLanguageOption)
			return fmt.Sprintf(unknownValueFormat, message)
		}
	}

	// This works because unlike the goconfig documentation suggests it will actually
	// try to resolve message in DEFAULT if it did not find it in the given section.
	value, err := messageConfig.String(region, message)
	if err != nil {
		i18nLog.Warnf("Unknown message '%s' for locale '%s'", message, locale)
		return fmt.Sprintf(unknownValueFormat, message)
	}

	if len(args) > 0 {
		i18nLog.Debugf("Arguments detected, formatting '%s' with %v", value, args)
		safeArgs := make([]interface{}, 0, len(args))
		for _, arg := range args {
			switch a := arg.(type) {
			case template.HTML:
				safeArgs = append(safeArgs, a)
			case string:
				safeArgs = append(safeArgs, template.HTML(template.HTMLEscapeString(a)))
			default:
				safeArgs = append(safeArgs, a)
			}
		}
		value = fmt.Sprintf(value, safeArgs...)
	}

	return value
}
1368754
func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) {
	if h, ok := a.t.(tHelper); ok {
		h.Helper()
	}
	JSONEq(a.t, expected, actual, msgAndArgs...)
}
652792
func init() {
	// algorithm taken from https://github.com/zenazn/goji/blob/master/web/middleware/request_id.go#L44-L50
	var buf [12]byte
	var b64 string
	for len(b64) < 10 {
		rand.Read(buf[:])
		b64 = base64.StdEncoding.EncodeToString(buf[:])
		b64 = strings.NewReplacer("+", "", "/", "").Replace(b64)
	}
	reqPrefix = string(b64[0:10])
}
423468
func (t *T) ExpectErrorMessagef(err error, msg string, spec string, args ...interface{}) {
	prefix := fmt.Sprintf(spec, args...) + ": "
	if err == nil {
		t.Fatalf("%sExpected error was not returned.", prefix)
	} else if !strings.Contains(err.Error(), msg) {
		t.Fatalf("%sError message didn't contain the expected message:\n"+
			"Error message=%s\nExpected string=%s", prefix, err.Error(), msg)
	}
}
675383
func (pc PAConfig) CheckChallenges() error {
	if len(pc.Challenges) == 0 {
		return errors.New("empty challenges map in the Policy Authority config is not allowed")
	}
	for name := range pc.Challenges {
		if !core.ValidChallenge(name) {
			return fmt.Errorf("Invalid challenge in PA config: %s", name)
		}
	}
	return nil
}
1080786
func (gm serverMethod) ReqBodyNeedValidation() bool {
	// we can't use t.GetBuiltinType here because
	// the reqBody type is already in Go type
	getBuiltinType := func() string {
		switch {
		case strings.HasPrefix(gm.reqBody, "[][]"): // bidimensional array
			return strings.TrimPrefix(gm.reqBody, "[][]")
		case strings.HasPrefix(gm.reqBody, "[]"): // array
			return strings.TrimPrefix(gm.reqBody, "[]")
		default:
			return gm.reqBody
		}
	}
	t := raml.Type{
		Type: getBuiltinType(),
	}

	return !t.IsBuiltin()
}
585405
func qDecode(s string) ([]byte, error) {
	dec := make([]byte, len(s))
	n := 0
	for i := 0; i < len(s); i++ {
		switch c := s[i]; {
		case c == '_':
			dec[n] = ' '
		case c == '=':
			if i+2 >= len(s) {
				return nil, errInvalidWord
			}
			b, err := readHexByte(s[i+1], s[i+2])
			if err != nil {
				return nil, err
			}
			dec[n] = b
			i += 2
		case (c <= '~' && c >= ' ') || c == '\n' || c == '\r' || c == '\t':
			dec[n] = c
		default:
			return nil, errInvalidWord
		}
		n++
	}

	return dec[:n], nil
}
443871
func NoEmptyStrings(i interface{}, k string) ([]string, []error) {
	v, ok := i.(string)
	if !ok {
		return nil, []error{fmt.Errorf("expected type of %q to be string", k)}
	}

	if strings.TrimSpace(v) == "" {
		return nil, []error{fmt.Errorf("%q must not be empty", k)}
	}

	return nil, nil
}
895249
func (tpm *TPM) GetQuote(aik *Key, pcrs *PCRs, challenge []byte) ([]byte, []byte, error) {
	var validation C.TSS_VALIDATION
	challangeHash := sha1.Sum(challenge[:])

	validation.ulExternalDataLength = sha1.Size
	validation.rgbExternalData = (*C.BYTE)(C.CBytes(challangeHash[:]))
	defer C.free(unsafe.Pointer(validation.rgbExternalData))
	err := tspiError(C.Tspi_TPM_Quote(tpm.handle, aik.handle, pcrs.handle, &validation))

	if err != nil {
		return nil, nil, err
	}

	data := C.GoBytes(unsafe.Pointer(validation.rgbData), (C.int)(validation.ulDataLength))
	validationOutput := C.GoBytes(unsafe.Pointer(validation.rgbValidationData), (C.int)(validation.ulValidationDataLength))

	C.Tspi_Context_FreeMemory(tpm.context, validation.rgbData)
	C.Tspi_Context_FreeMemory(tpm.context, validation.rgbValidationData)

	return data, validationOutput, nil
}
959190
func (s *ValidateService) Q(q string) *ValidateService {
	s.q = q
	return s
}
569489
func (c *ServerContext) DecryptMessage(msg []byte, seqno uint32) (uint32, []byte, error) {
	return decryptMessage(c.sctxt, msg, seqno)
}
684180
func (c *Challenge) PreSolve(authz acme.Authorization) error {
	domain := challenge.GetTargetedDomain(authz)
	log.Infof("[%s] acme: Preparing to solve DNS-01", domain)

	chlng, err := challenge.FindChallenge(challenge.DNS01, authz)
	if err != nil {
		return err
	}

	if c.provider == nil {
		return fmt.Errorf("[%s] acme: no DNS Provider configured", domain)
	}

	// Generate the Key Authorization for the challenge
	keyAuth, err := c.core.GetKeyAuthorization(chlng.Token)
	if err != nil {
		return err
	}

	err = c.provider.Present(authz.Identifier.Value, chlng.Token, keyAuth)
	if err != nil {
		return fmt.Errorf("[%s] acme: error presenting token: %s", domain, err)
	}

	return nil
}
827896
func initAcceptFromNonce(dst, nonce []byte) {
	if len(dst) != acceptSize {
		panic("accept buffer is invalid")
	}
	if len(nonce) != nonceSize {
		panic("nonce is invalid")
	}

	sha := acquireSha1()
	defer releaseSha1(sha)

	sha.Write(nonce)
	sha.Write(webSocketMagic)

	var sb [sha1.Size]byte
	sh := uintptr(unsafe.Pointer(&sb))
	sum := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
		Data: sh,
		Len:  0,
		Cap:  sha1.Size,
	}))
	sum = sha.Sum(sum)

	base64.StdEncoding.Encode(dst, sum)
}
312009
func NewChallenge(appID string, trustedFacets []string) (*Challenge, error) {
	challenge := make([]byte, 32)
	n, err := rand.Read(challenge)
	if err != nil {
		return nil, err
	}
	if n != 32 {
		return nil, errors.New("u2f: unable to generate random bytes")
	}

	var c Challenge
	c.Challenge = challenge
	c.Timestamp = time.Now()
	c.AppID = appID
	c.TrustedFacets = trustedFacets
	return &c, nil
}
379521
func ChallengeBlocks(domain, keyAuth string) ([]byte, []byte, error) {
	// Compute the SHA-256 digest of the key authorization.
	zBytes := sha256.Sum256([]byte(keyAuth))

	value, err := asn1.Marshal(zBytes[:sha256.Size])
	if err != nil {
		return nil, nil, err
	}

	// Add the keyAuth digest as the acmeValidation-v1 extension
	// (marked as critical such that it won't be used by non-ACME software).
	// Reference: https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-05#section-3
	extensions := []pkix.Extension{
		{
			Id:       idPeAcmeIdentifierV1,
			Critical: true,
			Value:    value,
		},
	}

	// Generate a new RSA key for the certificates.
	tempPrivateKey, err := certcrypto.GeneratePrivateKey(certcrypto.RSA2048)
	if err != nil {
		return nil, nil, err
	}

	rsaPrivateKey := tempPrivateKey.(*rsa.PrivateKey)

	// Generate the PEM certificate using the provided private key, domain, and extra extensions.
	tempCertPEM, err := certcrypto.GeneratePemCert(rsaPrivateKey, domain, extensions)
	if err != nil {
		return nil, nil, err
	}

	// Encode the private key into a PEM format. We'll need to use it to generate the x509 keypair.
	rsaPrivatePEM := certcrypto.PEMEncode(rsaPrivateKey)

	return tempCertPEM, rsaPrivatePEM, nil
}