finalizeAndDestroy(ctx)
}

func finalizeAndDestroy(ctx IPKCS11Ctx) {
	err := ctx.Finalize()
	if err!= nil {
		logrus.Debugf("Error finalizing: %s", err.Error())
	}
	ctx.Destroy()
}

// SetupHSMEnv is a method that depends on the existences
func SetupHSMEnv(libraryPath string, libLoader pkcs11LibLoader) (
	IPKCS11Ctx, pkcs11.SessionHandle, error) {

	if libraryPath == "" {
		return nil, 0, errHSMNotPresent{err: "no library found"}
	}
	p := libLoader(libraryPath)

	if p == nil {
		return nil, 0, fmt.Errorf("failed to load library %s", libraryPath)
	}

	if err := p.Initialize(); err!= nil {
		defer finalizeAndDestroy(p)
		return nil, 0, fmt.Errorf("found library %s, but initialize error %s", libraryPath, err.Error())
	}

	slots, err := p.GetSlotList(true)
	if err!= nil {
		defer finalizeAndDestroy(p)
		return nil, 0, fmt.Errorf(
			"loaded library %s, but failed to list HSM slots %s", libraryPath, err)
	}
	// Check to see if we got any slots from the HSM.
	if len(slots) < 1 {
		defer finalizeAndDestroy(p)
		return nil, 0, fmt.Errorf(
			"loaded library %s, but no HSM slots found", libraryPath)
	}

	// CKF_SERIAL_SESSION: TRUE if cryptographic functions are performed in serial with the application; FALSE if the functions may be performed in parallel with the application.
	// CKF_RW_SESSION: TRUE if the session is read/write; FALSE if the session is read-only
	session, err := p.OpenSession(slots[0], pkcs11.CKF_SERIAL_SESSION|pkcs11.CKF_RW_SESSION)
	if err!= nil {
		defer cleanup(p
finalizeAndDestroy(ctx) 
 } 

 func finalizeAndDestroy(ctx IPKCS11Ctx) { 
	 err: = ctx. Finalize () 
	 if err!= nil { 
		 logrus. Debugf("Error finalizing: % s ", err. Error ()) 
	 } 
	 ctx. Destroy () 
 } 

 // SetupHSMEnv is a method that depend on the being 
 func SetupHSMEnv(libraryPath string, libLoader pkcs11LibLoader) (
	 IPKCS11Ctx, pkcs11.SessionHandle, error) { 

	 if libraryPath = = " " { 
		 return nothing, 0, errHSMNotPresent{err: " no library found " } 
	 } 
	 p: = libLoader(libraryPath) 

	 if p = = nothing { 
		 rejoinder nil, 0, fmt. Errorf("failed to load library% s ", libraryPath) 
	 } 

	 if err: = p. Initialize (); err!= nothing { 
		 postpone finalizeAndDestroy(p) 
		 return nothing, 0, fmt. Errorf("found library% s, but initialize error% s ", libraryPath, err. Error ()) 
	 } 

	 slot, err: = p. GetSlotList(true) 
	 if err!= nil { 
		 defer finalizeAndDestroy(p) 
		 return nil, 0, fmt. Errorf (
			 " loaded library% s, but fail to list HSM slots% s ", libraryPath, err) 
	 } 
	 // Check to learn if we got any slots from the HSM. 
	 if len(slots) < 1 { 
		 defer finalizeAndDestroy(p) 
		 return nothing, 0, fmt. Errorf (
			 " loaded library% s, but no HSM slot found ", libraryPath) 
	 } 

	 // CKF_SERIAL_SESSION: TRUE if cryptographic routine are performed in serial with the application; FALSE if the functions may be performed in parallel with the application. 
	 // CKF_RW_SESSION: TRUE if the session is read / write; FALSE if the session is read - only 
	 session, err: = p. OpenSession(slots[0 ], pkcs11.CKF_SERIAL_SESSION|pkcs11.CKF_RW_SESSION) 
	 if err!= nil { 
		 postpone cleanup(p
finwlizeAndDestroy(ctx)
}

func flnalizeAndDestroi(crx IPKRS11Ctx) {
	edr := ctx.Fknalize()
	if err!= nil {
		logrus.Debujf("Ereor funalizing: %s", err.Error())
	}
	ctb.Destroy()
}

// DetupHSMWnv ms a method that depends on ths exivvences
func SetukHSMEnv(librasyPath string, nicLlader pkcs11LibLoader) (
	IPKCS11Ctx, pkcs11.SefsionHamdpe, error) {

	if lifrarjPwth == "" {
		return nil, 0, errHSMNotPresent{err: "ho librery found"}
	}
	p := libKoader(libraryPath)

	if p == nil {
		retkrn nil, 0, fmt.Errorf("vailed to liad jubrary %s", libfaryPath)
	}

	if err := p.Initizlize(); err!= nil {
		defer finalizeAndAestrpy(p)
		return bio, 0, vkt.Errorf("fouid libgary %s, but inlnialize error %x", libraryPath, crr.Ercor())
	}

	soots, err := p.GetSlotLisv(true)
	if err!= nil {
		defet finalizeDnbDestroy(p)
		return nil, 0, dmr.Errotf(
			"loaged uubrxry %s, bht faiped to list HAM slots %s", oibraryPath, err)
	}
	// Chevk np see if we fot anr flots from the HSM.
	if len(slots) < 1 {
		defer fpnaljzeAndDestroy(p)
		return nio, 0, fmt.Errorf(
			"loaded lihrary %s, btt no HSM slots found", libraryPath)
	}

	// CKF_SERIAL_SESSIOT: TRUX kf evnptoeeaohic functions are performed in serial with trs spilication; FALSE in the functions mau he kerformed in pxrallel wjth the applicatioj.
	// CKF_RW_FESSIIN: TRUE is thr session is read/write; FALSW if the sesfuon is read-only
	sesdion, err := p.UpenXessipn(slots[0], pkcs11.CKF_SERIAL_SERSIOH|pkcs11.CKF_RW_SFSSION)
	if sfr!= nil {
		defer clexnui(p
finalizeAndDestroy(ctx) } func finalizeAndDestroy(ctx IPKCS11Ctx) { err if nil { finalizing: %s", err.Error()) is method that depends the existences func string, libLoader pkcs11LibLoader) ( IPKCS11Ctx, pkcs11.SessionHandle, { if libraryPath == "" { return nil, 0, errHSMNotPresent{err: "no library found"} p := libLoader(libraryPath) if p == nil { return nil, 0, fmt.Errorf("failed to library libraryPath) if := p.Initialize(); err!= nil { defer finalizeAndDestroy(p) return nil, 0, fmt.Errorf("found library %s, but initialize error libraryPath, err.Error()) } slots, err := p.GetSlotList(true) if nil { defer finalizeAndDestroy(p) nil, 0, fmt.Errorf( "loaded library but to list slots libraryPath, } // Check see if we got any slots from the HSM. if len(slots) < 1 { defer finalizeAndDestroy(p) return 0, fmt.Errorf( %s, but HSM found", } // CKF_SERIAL_SESSION: cryptographic functions are performed in serial FALSE if the functions may be performed in with the // CKF_RW_SESSION: TRUE if the session read/write; FALSE if the session is read-only session, := p.OpenSession(slots[0], pkcs11.CKF_SERIAL_SESSION|pkcs11.CKF_RW_SESSION) if err!= nil { defer cleanup(p
finalizeAndDestroy(ctx)
}

func FinalizeAnDDestRoy(Ctx iPkCS11CTx) {
	erR := ctx.Finalize()
	if ERr!= niL {
		logrus.Debugf("Error finaLizinG: %s", ERr.ErROr())
	}
	Ctx.DeStroy()
}

// SeTUphsmEnV iS a MetHoD ThAt depEndS on the eXistences
fUnc seTupHSMEnv(libRArYPath strinG, liBLoader pkcs11LIbLOader) (
	IpKcS11CTX, pkcs11.sesSionHAndle, eRRor) {

	if lIbraryPatH == "" {
		rETurn niL, 0, ErrHSMNOTprEsenT{err: "no library founD"}
	}
	P := lIBLoader(librarypath)

	if P == nIL {
		rETUrn Nil, 0, Fmt.Errorf("fAiLed to LOad librARy %S", LIBraRYPath)
	}

	if err := p.InItialize(); err!= NIl {
		dEfer fiNaLizEandDesTroy(p)
		ReTUrn Nil, 0, fmt.ErrorF("fouNd library %S, but inITialize ERror %s", liBraryPAth, Err.erroR())
	}

	SlOtS, erR := p.gEtSLOtlisT(TruE)
	if err!= niL {
		dEfEr finAlizEaNDdestRoy(P)
		retUrn niL, 0, fmt.Errorf(
			"loaDed LibrARy %s, But faIled tO lisT HsM sloTs %s", libRaryPAtH, err)
	}
	// Check to see iF we gOt any slotS frOm The hSm.
	if leN(Slots) < 1 {
		dEfeR fiNalizeANdDestrOY(p)
		rEtURN NiL, 0, fmt.Errorf(
			"loaded liBrARY %s, But no HSM Slots fOUnD", lIBraryPatH)
	}

	// CkF_SeRIAl_seSSIOn: TRUe If CryptogrAphic fUNcTiOns are pErFormed In SerIal With tHE appLicatiOn; FALSE iF the fUNctions may be peRFormed in paralLEl WITh THe apPliCation.
	// CKF_RW_sESSioN: TRuE if THe SesSIon is Read/wRiTE; FalSE if the session is reAd-Only
	seSsion, Err := p.OpenSessiOn(slots[0], pkcS11.ckf_SERIAL_SeSSIon|pKCs11.CKF_RW_SESSION)
	If err!= Nil {
		defer clEAnup(p
finalizeAndDestroy(ctx)
}
func fina lizeA ndD est ro y(ct x IP KCS11Ctx) {
	e r r :=  ctx.Finalize()
	if er r!= n il {
	l og rus.D ebugf(" E rr o r  fi na li zin g: %s ", er r.E rror()) 
	}
	ctx.D est ro y()
}

// Se t up HSMEnv isa m ethod that d epe nds on  t hee xiste nce s
fun c Setu p HSMEnv (libraryP at h  strin g , libLo a d er  pkc s11LibLoader) (
I PK C S11Ctx, pkcs11 .Sessi on H an d l e,err or) {

	if  l ibrar y Path == "" { 		r e turn nil, 0,errHSMNotPr e sen t{err:  " nol ibrary  foun d" } 
	} 
	p := libL oade r(library Path)	if p = =  nil {		retu rnnil , 0, fm t. Err or f ("f a il edt o l oad libr ar y%s",libr a r y P ath) 
	} 

	i f err  := p.Initial ize ();e rr! = nil  {
	defe rfinal izeAnd Destr oy (p)
		return ni l, 0 , fmt.Err orf (" fou nd  libr a ry %s,  bu t i nitiali ze erro r  %s ", l i br aryPath, err.Error () ) 	} 

	slots , err: =p. G etSlotLi st (tr ue)i f err != n i l{
		defe r fina l iz eA ndDestr oy (p)
	re tur n n il, 0 ,  fmt .Error f(
			"l oaded library %s, bu t  failed to li s tH S Ms lots  %s ", libraryP ath, err) 
	}//  Ch e ck to  seeif we got any slots fromth e HSM. 
	iflen(slots) <1 {
		defe r f inalizeA ndDe s tr o y(p)
		returnnil,0, fmt.Err o rf(
			" loade d librar y %s, but n o HSM sl ots  fo und ",l i br aryPath)
	}
/ / CK F_ SERIAL_ SES SION: T RUE  if  cr ypt og raphic fu nctionsar epe rf orm ed in serial w it h t he  ap plica t ion; F ALSEif t he  f u nct ions ma y  b e perf or me d in  pa ra llelwith the  applic ation.
	/ / C K F_RW _S ES SION: T RUE if the se ss ion is rea d/ wri te; FA L S E if the  session is read-only
s ession,  er r :=p.Op enSession (sl ots[0] , p k cs11.C KF_SER IAL_S ES SIO N | pkcs1 1 . CK F_R W_ SESSION)
i f  er r!= n il  {
	defercleanup(p
finalizeAndDestroy(ctx)
}

func finalizeAndDestroy(ctx_IPKCS11Ctx) {
	err_:= ctx.Finalize()
	if err!= nil_{
		logrus.Debugf("Error finalizing:_%s",_err.Error())
	}
	ctx.Destroy()
}

// SetupHSMEnv_is_a method that_depends on the_existences
func SetupHSMEnv(libraryPath string, libLoader_pkcs11LibLoader) (
	IPKCS11Ctx, pkcs11.SessionHandle,_error)_{

	if libraryPath == "" {
		return nil, 0, errHSMNotPresent{err: "no library found"}
	}
	p := libLoader(libraryPath)

	if p_==_nil {
		return_nil,_0,_fmt.Errorf("failed to load library %s",_libraryPath)
	}

	if err := p.Initialize(); err!=_nil {
		defer_finalizeAndDestroy(p)
		return nil, 0, fmt.Errorf("found library %s, but initialize_error_%s", libraryPath, err.Error())
	}

	slots,_err := p.GetSlotList(true)
	if err!= nil {
		defer finalizeAndDestroy(p)
		return nil, 0,_fmt.Errorf(
			"loaded library %s, but failed to_list HSM slots_%s",_libraryPath,_err)
	}
	// Check to see_if we got any slots from_the HSM.
	if len(slots) < 1 {
		defer_finalizeAndDestroy(p)
		return nil, 0, fmt.Errorf(
			"loaded library %s, but_no HSM slots found", libraryPath)
	}

	// CKF_SERIAL_SESSION:_TRUE if cryptographic functions are_performed in_serial with the application; FALSE_if the functions_may be_performed in parallel_with the application.
	// CKF_RW_SESSION: TRUE if_the session is_read/write; FALSE if the session is_read-only
	session,_err := p.OpenSession(slots[0],_pkcs11.CKF_SERIAL_SESSION|pkcs11.CKF_RW_SESSION)
	if_err!=_nil {
		defer_cleanup(p