// ParseJSONKey returns a new Credentials with values based on the
// provided JSON key file contents.
519446
func ParseJSONKey(jsonKeyFile io.Reader) (*Credentials, error) {
	jsonKey, err := ioutil.ReadAll(jsonKeyFile)
	if err != nil {
		return nil, errors.Trace(err)
	}
	values, err := parseJSONKey(jsonKey)
	if err != nil {
		return nil, errors.Trace(err)
	}
	creds, err := NewCredentials(values)
	if err != nil {
		return nil, errors.Trace(err)
	}
	creds.JSONKey = jsonKey
	return creds, nil
}
1096414
func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
	if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
		return key, nil
	}
	if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
		switch key := key.(type) {
		case *rsa.PrivateKey, *ecdsa.PrivateKey:
			return key, nil
		default:
			return nil, errors.New("crypto/tls: found unknown private key type in PKCS#8 wrapping")
		}
	}
	if key, err := x509.ParseECPrivateKey(der); err == nil {
		return key, nil
	}

	return nil, errors.New("crypto/tls: failed to parse private key")
}
54797
func ParsePKCS8ToTufKey(der []byte, password []byte) (data.PrivateKey, error) {
	if password == nil {
		return parsePKCS8ToTufKey(der)
	}

	var privKey encryptedPrivateKeyInfo
	if _, err := asn1.Unmarshal(der, &privKey); err != nil {
		return nil, errors.New("pkcs8: only PKCS #5 v2.0 supported")
	}

	if !privKey.EncryptionAlgorithm.IDPBES2.Equal(oidPBES2) {
		return nil, errors.New("pkcs8: only PBES2 supported")
	}

	if !privKey.EncryptionAlgorithm.PBES2Params.KeyDerivationFunc.IDPBKDF2.Equal(oidPKCS5PBKDF2) {
		return nil, errors.New("pkcs8: only PBKDF2 supported")
	}

	encParam := privKey.EncryptionAlgorithm.PBES2Params.EncryptionScheme
	kdfParam := privKey.EncryptionAlgorithm.PBES2Params.KeyDerivationFunc.PBKDF2Params

	switch {
	case encParam.EncryAlgo.Equal(oidAES256CBC):
		iv := encParam.IV
		salt := kdfParam.Salt
		iter := kdfParam.IterationCount

		encryptedKey := privKey.EncryptedData
		symkey := pbkdf2.Key(password, salt, iter, 32, sha1.New)
		block, err := aes.NewCipher(symkey)
		if err != nil {
			return nil, err
		}
		mode := cipher.NewCBCDecrypter(block, iv)
		mode.CryptBlocks(encryptedKey, encryptedKey)

		// no need to explicitly remove padding, as ASN.1 unmarshalling will automatically discard it
		key, err := parsePKCS8ToTufKey(encryptedKey)
		if err != nil {
			return nil, errors.New("pkcs8: incorrect password")
		}

		return key, nil
	default:
		return nil, errors.New("pkcs8: only AES-256-CBC supported")
	}

}
431275
func parseSecurityOpts(securityOpts []string) ([]string, error) {
	for key, opt := range securityOpts {
		con := strings.SplitN(opt, "=", 2)
		if len(con) == 1 && con[0] != "no-new-privileges" {
			if strings.Contains(opt, ":") {
				con = strings.SplitN(opt, ":", 2)
			} else {
				return securityOpts, errors.Errorf("Invalid --security-opt: %q", opt)
			}
		}
		if con[0] == "seccomp" && con[1] != "unconfined" {
			f, err := ioutil.ReadFile(con[1])
			if err != nil {
				return securityOpts, errors.Errorf("opening seccomp profile (%s) failed: %v", con[1], err)
			}
			b := bytes.NewBuffer(nil)
			if err := json.Compact(b, f); err != nil {
				return securityOpts, errors.Errorf("compacting json for seccomp profile (%s) failed: %v", con[1], err)
			}
			securityOpts[key] = fmt.Sprintf("seccomp=%s", b.Bytes())
		}
	}

	return securityOpts, nil
}
70684
func ParsePEMPrivateKey(pemBytes []byte, passphrase string) (data.PrivateKey, error) {
	return parsePEMPrivateKey(pemBytes, passphrase, notary.FIPSEnabled())
}
317112
func ParsePrettySignature(content []byte, signatureKey string) (*JSONSignature, error) {
	var contentMap map[string]json.RawMessage
	err := json.Unmarshal(content, &contentMap)
	if err != nil {
		return nil, fmt.Errorf("error unmarshalling content: %s", err)
	}
	sigMessage, ok := contentMap[signatureKey]
	if !ok {
		return nil, ErrMissingSignatureKey
	}

	var signatureBlocks []jsParsedSignature
	err = json.Unmarshal([]byte(sigMessage), &signatureBlocks)
	if err != nil {
		return nil, fmt.Errorf("error unmarshalling signatures: %s", err)
	}

	js := newJSONSignature()
	js.signatures = make([]jsSignature, len(signatureBlocks))

	for i, signatureBlock := range signatureBlocks {
		protectedBytes, err := joseBase64UrlDecode(signatureBlock.Protected)
		if err != nil {
			return nil, fmt.Errorf("base64 decode error: %s", err)
		}
		var protectedHeader map[string]interface{}
		err = json.Unmarshal(protectedBytes, &protectedHeader)
		if err != nil {
			return nil, fmt.Errorf("error unmarshalling protected header: %s", err)
		}

		formatLength, ok := readIntFromMap("formatLength", protectedHeader)
		if !ok {
			return nil, errors.New("missing formatted length")
		}
		encodedTail, ok := readStringFromMap("formatTail", protectedHeader)
		if !ok {
			return nil, errors.New("missing formatted tail")
		}
		formatTail, err := joseBase64UrlDecode(encodedTail)
		if err != nil {
			return nil, fmt.Errorf("base64 decode error on tail: %s", err)
		}
		if js.formatLength == 0 {
			js.formatLength = formatLength
		} else if js.formatLength != formatLength {
			return nil, errors.New("conflicting format length")
		}
		if len(js.formatTail) == 0 {
			js.formatTail = formatTail
		} else if bytes.Compare(js.formatTail, formatTail) != 0 {
			return nil, errors.New("conflicting format tail")
		}

		header := jsHeader{
			Algorithm: signatureBlock.Header.Algorithm,
			Chain:     signatureBlock.Header.Chain,
		}
		if signatureBlock.Header.JWK != nil {
			publicKey, err := UnmarshalPublicKeyJWK([]byte(signatureBlock.Header.JWK))
			if err != nil {
				return nil, fmt.Errorf("error unmarshalling public key: %s", err)
			}
			header.JWK = publicKey
		}
		js.signatures[i] = jsSignature{
			Header:    header,
			Signature: signatureBlock.Signature,
			Protected: signatureBlock.Protected,
		}
	}
	if js.formatLength > len(content) {
		return nil, errors.New("invalid format length")
	}
	formatted := make([]byte, js.formatLength+len(js.formatTail))
	copy(formatted, content[:js.formatLength])
	copy(formatted[js.formatLength:], js.formatTail)
	js.indent = detectJSONIndent(formatted)
	js.payload = joseBase64UrlEncode(formatted)

	return js, nil
}
63435
func ParseNwkSKey(input string) (key NwkSKey, err error) {
	aes128key, err := ParseAES128Key(input)
	if err != nil {
		return
	}
	key = NwkSKey(aes128key)
	return
}
2328
func ParseCiphers(tlsConfig *config.TLSConfig) ([]uint16, error) {
	suites := []uint16{}

	cipherStr := strings.TrimSpace(tlsConfig.TLSCipherSuites)

	var parsedCiphers []string
	if cipherStr == "" {
		parsedCiphers = defaultTLSCiphers

	} else {
		parsedCiphers = strings.Split(tlsConfig.TLSCipherSuites, ",")
	}
	for _, cipher := range parsedCiphers {
		c, ok := supportedTLSCiphers[cipher]
		if !ok {
			return suites, fmt.Errorf("unsupported TLS cipher %q", cipher)
		}
		suites = append(suites, c)
	}

	// Ensure that the specified cipher suite list is supported by the TLS
	// Certificate signature algorithm. This is a check for user error, where a
	// TLS certificate could support RSA but a user has configured a cipher suite
	// list of ciphers where only ECDSA is supported.
	keyLoader := tlsConfig.GetKeyLoader()

	// Ensure that the keypair has been loaded before continuing
	keyLoader.LoadKeyPair(tlsConfig.CertFile, tlsConfig.KeyFile)

	if keyLoader.GetCertificate() != nil {
		supportedSignatureAlgorithm, err := getSignatureAlgorithm(keyLoader.GetCertificate())
		if err != nil {
			return []uint16{}, err
		}

		for _, cipher := range parsedCiphers {
			if supportedCipherSignatures[cipher] == supportedSignatureAlgorithm {
				// Positive case, return the matched cipher suites as the signature
				// algorithm is also supported
				return suites, nil
			}
		}

		// Negative case, if this is reached it means that none of the specified
		// cipher suites signature algorithms match the signature algorithm
		// for the certificate.
		return []uint16{}, fmt.Errorf("Specified cipher suites don't support the certificate signature algorithm %s, consider adding more cipher suites to match this signature algorithm.", supportedSignatureAlgorithm)
	}

	// Default in case this function is called but TLS is not actually configured
	// This is only reached if the TLS certificate is nil
	return []uint16{}, nil
}
925751
func (a *Client) GetJSONWebKey(params *GetJSONWebKeyParams) (*GetJSONWebKeyOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewGetJSONWebKeyParams()
	}

	result, err := a.transport.Submit(&runtime.ClientOperation{
		ID:                 "getJsonWebKey",
		Method:             "GET",
		PathPattern:        "/keys/{set}/{kid}",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http", "https"},
		Params:             params,
		Reader:             &GetJSONWebKeyReader{formats: a.formats},
		Context:            params.Context,
		Client:             params.HTTPClient,
	})
	if err != nil {
		return nil, err
	}
	return result.(*GetJSONWebKeyOK), nil

}
1255010
func NewJSONWebKeySet(parsed *JSONWebKeySetStruct) (*JSONWebKeySet, error) {
	// Pick keys used to verify RS256 signatures.
	keys := make(map[string]rsa.PublicKey, len(parsed.Keys))
	for _, k := range parsed.Keys {
		if k.Kty != "RSA" || k.Alg != "RS256" || k.Use != "sig" {
			continue // not an RSA public key
		}
		if k.Kid == "" {
			// Per spec 'kid' field is optional, but providers we support return them,
			// so make them required to keep the code simpler.
			return nil, fmt.Errorf("bad JSON web key - missing 'kid' field")
		}
		pub, err := decodeRSAPublicKey(k.N, k.E)
		if err != nil {
			return nil, fmt.Errorf("failed to parse RSA public key in JSON web key - %s", err)
		}
		keys[k.Kid] = pub
	}

	if len(keys) == 0 {
		return nil, fmt.Errorf("the JSON web key doc didn't have any signing keys")
	}

	return &JSONWebKeySet{keys: keys}, nil
}
963115
func credentialsFromEnv(key string) (*auth.Credentials, error) {
	var keyName string
	if key == "" {
		keyName = getUserHome() + "/.ssh/id_rsa"
	} else {
		keyName = key
	}
	privateKey, err := ioutil.ReadFile(keyName)
	if err != nil {
		return nil, err
	}
	authentication, err := auth.NewAuth(getConfig(TritonAccount, SdcAccount, MantaUser), string(privateKey), "rsa-sha256")
	if err != nil {
		return nil, err
	}

	return &auth.Credentials{
		UserAuthentication: authentication,
		SdcKeyId:           getConfig(TritonKeyId, SdcKeyId),
		SdcEndpoint:        auth.Endpoint{URL: getConfig(TritonUrl, SdcUrl)},
		MantaKeyId:         getConfig(MantaKeyId),
		MantaEndpoint:      auth.Endpoint{URL: getConfig(MantaUrl)},
	}, nil
}
444784
func (key *Key) MonaxKeysJSON() string {
	jsonKey := plainKeyJSON{
		Address:    key.Address.String(),
		Type:       "ed25519",
		PrivateKey: PrivateKeyplainKeyJSON{Plain: key.PrivateKey},
	}
	bs, err := json.Marshal(jsonKey)
	if err != nil {
		return errors.Wrap(err, "could not create monax key json").Error()
	}
	return string(bs)
}
837029
func (t *Token) parsePrivateKey() error {
	block, _ := pem.Decode(t.Key)
	if block == nil {
		return ErrInvalidKey
	}
	parsedKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {
		parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
		if err != nil {
			return err
		}
	}
	var ok bool
	t.pKey, ok = parsedKey.(*rsa.PrivateKey)
	if !ok {
		return ErrInvalidKey
	}
	return nil
}
639453
func parseRSAPrivateKey(data []byte) (*rsa.PrivateKey, error) {
	var err error

	// Parse the key
	var parsedKey interface{}
	if parsedKey, err = x509.ParsePKCS1PrivateKey(data); err != nil {
		if parsedKey, err = x509.ParsePKCS8PrivateKey(data); err != nil {
			return nil, err
		}
	}

	// Test if parsed key is an RSA Private Key
	var privKey *rsa.PrivateKey
	var ok bool
	if privKey, ok = parsedKey.(*rsa.PrivateKey); !ok {
		return nil, fmt.Errorf("data doesn't contain valid RSA Private Key")
	}

	return privKey, nil
}
733505
func parseJSON(inputData []byte) (*jsongo.JSONNode, error) {
	root := jsongo.JSONNode{}

	if err := json.Unmarshal(inputData, &root); err != nil {
		return nil, fmt.Errorf("unmarshalling JSON failed: %v", err)
	}

	return &root, nil
}
645043
func (key Key) MarshalJSON() ([]byte, error) {
	if !key.IsValid() {
		return nil, fmt.Errorf("unknown key %v", key)
	}

	return json.Marshal(string(key))
}
286730
func (ch *CredHub) SetJSON(name string, value values.JSON) (credentials.JSON, error) {
	var cred credentials.JSON
	err := ch.setCredential(name, "json", value, &cred)

	return cred, err
}