//createNewPKCS11Ctx creates new mPkcs11.Ctx
962309
func (handle *ContextHandle) createNewPKCS11Ctx() *mPkcs11.Ctx {
	newCtx := mPkcs11.New(handle.lib)
	if newCtx == nil {
		logger.Warn("Failed to recreate new context for given library")
		return nil
	}

	//initialize new context
	err := newCtx.Initialize()
	if err != nil {
		if err != mPkcs11.Error(mPkcs11.CKR_CRYPTOKI_ALREADY_INITIALIZED) {
			logger.Warn("Failed to initialize context:", err)
			return nil
		}
	}

	return newCtx
}
493358
func CreateNewTokens(client clientset.Interface, tokens []kubeadmapi.BootstrapToken) error {
	return UpdateOrCreateTokens(client, true, tokens)
}
670037
func newCtxtCacheKey(ctx fab.ClientContext) (*ctxtCacheKey, error) {
	identity, err := ctx.Serialize()
	if err != nil {
		return nil, err
	}

	h := sha256.New()
	if _, err := h.Write(identity); err != nil {
		return nil, err
	}

	hash := h.Sum(nil)

	return &ctxtCacheKey{
		key:     string(hash),
		context: ctx,
	}, nil
}
931652
func CreateVhdx(path string, maxSizeInGb, blockSizeInMb uint32) error {
	var (
		defaultType virtualStorageType
		handle      syscall.Handle
	)

	parameters := createVirtualDiskParameters{
		Version: 2,
		Version2: createVersion2{
			MaximumSize:      uint64(maxSizeInGb) * 1024 * 1024 * 1024,
			BlockSizeInBytes: blockSizeInMb * 1024 * 1024,
		},
	}

	if err := createVirtualDisk(
		&defaultType,
		path,
		uint32(VirtualDiskAccessNone),
		nil,
		uint32(createVirtualDiskFlagNone),
		0,
		&parameters,
		nil,
		&handle); err != nil {
		return err
	}

	if err := syscall.CloseHandle(handle); err != nil {
		return err
	}

	return nil
}
883800
func NewPSTMTPlanCacheKey(sessionVars *variable.SessionVars, pstmtID uint32, schemaVersion int64) kvcache.Key {
	timezoneOffset := 0
	if sessionVars.TimeZone != nil {
		_, timezoneOffset = time.Now().In(sessionVars.TimeZone).Zone()
	}
	return &pstmtPlanCacheKey{
		database:       sessionVars.CurrentDB,
		connID:         sessionVars.ConnectionID,
		pstmtID:        pstmtID,
		snapshot:       sessionVars.SnapshotTS,
		schemaVersion:  schemaVersion,
		sqlMode:        sessionVars.SQLMode,
		timezoneOffset: timezoneOffset,
	}
}
500771
func New(opts NewOpts) (MSP, error) {
	switch opts.(type) {
	case *BCCSPNewOpts:
		switch opts.GetVersion() {
		case MSPv1_0:
			return newBccspMsp(MSPv1_0)
		case MSPv1_1:
			return newBccspMsp(MSPv1_1)
		case MSPv1_3:
			return newBccspMsp(MSPv1_3)
		default:
			return nil, errors.Errorf("Invalid *BCCSPNewOpts. Version not recognized [%v]", opts.GetVersion())
		}
	case *IdemixNewOpts:
		switch opts.GetVersion() {
		case MSPv1_3:
			return newIdemixMsp(MSPv1_3)
		case MSPv1_1:
			return newIdemixMsp(MSPv1_1)
		default:
			return nil, errors.Errorf("Invalid *IdemixNewOpts. Version not recognized [%v]", opts.GetVersion())
		}
	default:
		return nil, errors.Errorf("Invalid msp.NewOpts instance. It must be either *BCCSPNewOpts or *IdemixNewOpts. It was [%v]", opts)
	}
}
690296
func newWktDecoder() *wktDecoder {
	r := cGEOSWKTReader_create()
	if r == nil {
		return nil
	}
	d := &wktDecoder{r}
	runtime.SetFinalizer(d, (*wktDecoder).destroy)
	return d
}
359466
func publishNewUserEK(mctx libkb.MetaContext, merkleRoot libkb.MerkleRoot) (
	metadata keybase1.UserEkMetadata, err error) {
	defer mctx.TraceTimed("publishNewUserEK", func() error { return err })()

	// Sign the statement blob with the latest PUK.
	pukKeyring, err := mctx.G().GetPerUserKeyring(mctx.Ctx())
	if err != nil {
		return metadata, err
	}
	if err := pukKeyring.Sync(mctx); err != nil {
		return metadata, err
	}
	if !pukKeyring.HasAnyKeys() {
		return metadata, fmt.Errorf("A PUK is needed to generate ephemeral keys. Aborting.")
	}
	pukSigning, err := pukKeyring.GetLatestSigningKey(mctx)
	if err != nil {
		return metadata, err
	}

	sig, boxes, newMetadata, myBox, err := prepareNewUserEK(mctx, merkleRoot, pukSigning)
	if err != nil {
		return metadata, err
	}

	if err = postNewUserEK(mctx, sig, boxes); err != nil {
		return metadata, err
	}

	// Cache the new box after we see the post succeeded.
	if myBox == nil {
		mctx.Debug("No box made for own deviceEK")
	} else {
		storage := mctx.G().GetUserEKBoxStorage()
		err = storage.Put(mctx, newMetadata.Generation, *myBox)
	}
	return newMetadata, err
}
424833
func CreateCAExtension() (pkix.Extension, error) {
	type basicConstraints struct {
		IsCA       bool `asn1:"optional"`
		MaxPathLen int  `asn1:"optional"`
	}
	basicCon := basicConstraints{IsCA: true, MaxPathLen: 0}
	bitstr, err := asn1.Marshal(basicCon)
	if err != nil {
		return pkix.Extension{}, err
	}

	return pkix.Extension{
		Id:       []int{2, 5, 29, 19}, // from x509 package
		Critical: true,
		Value:    bitstr,
	}, nil
}
1035830
func createNewAccount(icmd interface{}, w *wallet.Wallet) (interface{}, error) {
	cmd := icmd.(*btcjson.CreateNewAccountCmd)

	// The wildcard * is reserved by the rpc server with the special meaning
	// of "all accounts", so disallow naming accounts to this string.
	if cmd.Account == "*" {
		return nil, &ErrReservedAccountName
	}

	_, err := w.NextAccount(waddrmgr.KeyScopeBIP0044, cmd.Account)
	if waddrmgr.IsError(err, waddrmgr.ErrLocked) {
		return nil, &btcjson.RPCError{
			Code: btcjson.ErrRPCWalletUnlockNeeded,
			Message: "Creating an account requires the wallet to be unlocked. " +
				"Enter the wallet passphrase with walletpassphrase to unlock",
		}
	}
	return nil, err
}
1013953
func (w *bufferedWriter) createNewWriter(file *os.File) io.Writer {
	w.buf = bufio.NewWriterSize(file, w.bufSize)
	return w.buf
}
33020
func (ctx *certContext) initPKAndCert(host string, commonName string) (err error) {
	if ctx.PK, err = LoadPKFromFile(ctx.PKFile); err != nil {
		if os.IsNotExist(err) {
			fmt.Printf("Creating new PK at: %s\n", ctx.PKFile)
			if ctx.PK, err = GeneratePK(2048); err != nil {
				return
			}
			if err = ctx.PK.WriteToFile(ctx.PKFile); err != nil {
				return fmt.Errorf("Unable to save private key: %s\n", err)
			}
		} else {
			return fmt.Errorf("Unable to read private key, even though it exists: %s\n", err)
		}
	}

	fmt.Printf("Creating new cert for host %v at: %s\n", host, ctx.ServerCertFile)
	ctx.ServerCert, err = ctx.PK.TLSCertificateFor(tenYearsFromToday, true, nil, "Lantern", commonName, host)
	if err != nil {
		return
	}
	err = ctx.ServerCert.WriteToFile(ctx.ServerCertFile)
	if err != nil {
		return
	}
	return nil
}
1102821
func (api OrganizationsAPI) CreateNewAPIKey(w http.ResponseWriter, r *http.Request) {
	globalID := mux.Vars(r)["globalid"]

	apiKey := APIKey{}

	if err := json.NewDecoder(r.Body).Decode(&apiKey); err != nil {
		log.Debug("Error decoding apikey: ", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	apiKey.Secret = "dummysecret" // else the validator complains
	if !apiKey.Validate() {
		log.Debug("Invalid api key: ", apiKey)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	log.Debug("Creating apikey:", apiKey)
	c := oauthservice.NewOauth2Client(globalID, apiKey.Label, apiKey.CallbackURL, apiKey.ClientCredentialsGrantType)

	mgr := oauthservice.NewManager(r)
	err := mgr.CreateClient(c)
	if db.IsDup(err) {
		log.Debug("Duplicate label")
		http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
		return
	}
	if err != nil {
		log.Error("Error creating api secret label", err.Error())
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	apiKey.Secret = c.Secret

	w.Header().Set("Content-Type", "application/json")

	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(apiKey)

}
590189
func (o *Enterprise) CreateIKEPSK(child *IKEPSK) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
751678
func kbfsLibdokanCreateFile(
	fname C.LPCWSTR,
	psec C.PDOKAN_IO_SECURITY_CONTEXT,
	DesiredAccess C.ACCESS_MASK,
	FileAttributes C.ULONG,
	ShareAccess C.ULONG,
	cCreateDisposition C.ULONG,
	CreateOptions C.ULONG,
	pfi C.PDOKAN_FILE_INFO) C.NTSTATUS {
	var cd = CreateData{
		DesiredAccess:     uint32(DesiredAccess),
		FileAttributes:    FileAttribute(FileAttributes),
		ShareAccess:       uint32(ShareAccess),
		CreateDisposition: CreateDisposition(cCreateDisposition),
		CreateOptions:     uint32(CreateOptions),
	}
	debugf("CreateFile '%v' %#v pid: %v\n",
		d16{fname}, cd, pfi.ProcessId)
	fs := getfs(pfi)
	ctx, cancel := fs.WithContext(globalContext())
	if cancel != nil {
		defer cancel()
	}
	fi, status, err := fs.CreateFile(ctx, makeFI(fname, pfi), &cd)
	if isDebug {
		checkFileDirectoryFile(err, status.IsDir(), uint32(CreateOptions))
		debugf("CreateFile result: %v new-entry: %v raw %v", status.IsDir(), status.IsNew(), status)
		if err == nil && status&isValid == 0 {
			debugf("CreateFile invalid status for successful operation!")
		}
	}
	if status.IsDir() {
		pfi.IsDirectory = 1
	}
	if err == nil && !status.IsNew() && cd.CreateDisposition.isSignalExisting() {
		debugf("CreateFile adding ErrObjectNameCollision")
		err = ErrObjectNameCollision
	}
	return fiStore(pfi, fi, err)
}
734708
func CreateNewAccount(bundle *stellar1.Bundle, name string, makePrimary bool) (pub stellar1.AccountID, err error) {
	accountID, masterKey, err := randomStellarKeypair()
	if err != nil {
		return pub, err
	}
	if err := AddAccount(bundle, masterKey, name, makePrimary); err != nil {
		return pub, err
	}
	return accountID, nil
}
595353
func CreateCACertAndKeyFiles(certSpec *KubeadmCert, cfg *kubeadmapi.InitConfiguration) error {
	if certSpec.CAName != "" {
		return errors.Errorf("this function should only be used for CAs, but cert %s has CA %s", certSpec.Name, certSpec.CAName)
	}
	klog.V(1).Infof("creating a new certificate authority for %s", certSpec.Name)

	certConfig, err := certSpec.GetConfig(cfg)
	if err != nil {
		return err
	}

	caCert, caKey, err := pkiutil.NewCertificateAuthority(certConfig)
	if err != nil {
		return err
	}

	return writeCertificateAuthorithyFilesIfNotExist(
		cfg.CertificatesDir,
		certSpec.BaseName,
		caCert,
		caKey,
	)
}