util

package
v0.0.0-...-3b69051 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 18, 2020 License: Apache-2.0 Imports: 50 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// TagDefault is the tag name for a default value of a field as recognized
	// by RegisterFlags.
	TagDefault = "def"
	// TagHelp is the tag name for a help message of a field as recognized
	// by RegisterFlags.
	TagHelp = "help"
	// TagOpt is the tag name for a one character option of a field as recognized
	// by RegisterFlags.  For example, a value of "d" reserves "-d" for the
	// command line argument.
	TagOpt = "opt"
	// TagSkip is the tag name which causes the field to be skipped by
	// RegisterFlags.
	TagSkip = "skip"
	// TagHide is the tag name which causes the field to be hidden
	TagHide = "hide"
)
View Source
const SecretTag = "mask"

SecretTag to tag a field as secret as in password, token

Variables

View Source
var (

	// ErrNotImplemented used to return errors for functions not implemented
	ErrNotImplemented = errors.New("NOT YET IMPLEMENTED")
)
View Source
var RevocationReasonCodes = map[string]int{
	"unspecified":          ocsp.Unspecified,
	"keycompromise":        ocsp.KeyCompromise,
	"cacompromise":         ocsp.CACompromise,
	"affiliationchanged":   ocsp.AffiliationChanged,
	"superseded":           ocsp.Superseded,
	"cessationofoperation": ocsp.CessationOfOperation,
	"certificatehold":      ocsp.CertificateHold,
	"removefromcrl":        ocsp.RemoveFromCRL,
	"privilegewithdrawn":   ocsp.PrivilegeWithdrawn,
	"aacompromise":         ocsp.AACompromise,
}

RevocationReasonCodes is a map between string reason codes to integers as defined in RFC 5280

View Source
var URLRegex = regexp.MustCompile("(ldap|http)s*://(\\S+):(\\S+)@")

URLRegex is the regular expression to check if a value is an URL

Functions

func B64Decode

func B64Decode(str string) (buf []byte, err error)

B64Decode base64 decodes a string

func B64Encode

func B64Encode(buf []byte) string

B64Encode base64 encodes bytes

func BCCSPKeyRequestGenerate

func BCCSPKeyRequestGenerate(req *csr.CertificateRequest, myCSP bccsp.BCCSP) (bccsp.Key, crypto.Signer, error)

TODO: remove first param BCCSPKeyRequestGenerate generates keys through BCCSP somewhat mirroring to cfssl/req.KeyRequest.Generate()

func BccspBackedSigner

func BccspBackedSigner(caFile, keyFile string, policy *config.Signing, csp bccsp.BCCSP) (signer.Signer, error)

BccspBackedSigner attempts to create a signer using csp bccsp.BCCSP. This csp could be SW (golang crypto) PKCS11 or whatever BCCSP-conformant library is configured

func CheckHostsInCert

func CheckHostsInCert(certFile string, hosts ...string) error

CheckHostsInCert checks to see if host correctly inserted into certificate

func CmdRunBegin

func CmdRunBegin(v *viper.Viper)

CmdRunBegin is called at the beginning of each cobra run function

func ConfigureBCCSP

func ConfigureBCCSP(optsPtr **factory.FactoryOpts, mspDir, homeDir string) error

ConfigureBCCSP configures BCCSP, using

func CopyMissingValues

func CopyMissingValues(src, dst interface{})

CopyMissingValues checks the dst interface for missing values and replaces them with value from src config struct. This does a deep copy of pointers.

func CreateClientHome

func CreateClientHome() (string, error)

CreateClientHome will create a home directory if it does not exist

func CreateToken

func CreateToken(csp bccsp.BCCSP, cert []byte, key bccsp.Key, method, uri string, body []byte) (string, error)

CreateToken creates a JWT-like token. In a normal JWT token, the format of the token created is:

<algorithm,claims,signature>

where each part is base64-encoded string separated by a period. In this JWT-like token, there are two differences:

  1. the claims section is a certificate, so the format is: <certificate,signature>
  2. the signature uses the private key associated with the certificate, and the signature is across both the certificate and the "body" argument, which is the body of an HTTP request, though could be any arbitrary bytes.

@param cert The pem-encoded certificate @param key The pem-encoded key @param method http method of the request @param uri URI of the request @param body The body of an HTTP request

func DecodeToken

func DecodeToken(token string) (*x509.Certificate, string, string, error)

DecodeToken extracts an X509 certificate and base64 encoded signature from a token

func ErrorContains

func ErrorContains(t *testing.T, err error, contains, msg string, args ...interface{})

ErrorContains will check to see if an error occurred, if so it will check that it contains the appropriate error message

func Fatal

func Fatal(format string, v ...interface{})

Fatal logs a fatal message and exits

func FatalError

func FatalError(t *testing.T, err error, msg string, args ...interface{})

FatalError will check to see if an error occured if so it will cause the test cases exit

func FileExists

func FileExists(name string) bool

FileExists checks to see if a file exists

func FlagString

func FlagString(v *viper.Viper, flags *pflag.FlagSet, name, short string, def string, desc string)

FlagString sets up a flag for a string, binding it to its name

func GenECDSAToken

func GenECDSAToken(csp bccsp.BCCSP, cert []byte, key bccsp.Key, method, uri string, body []byte) (string, error)

GenECDSAToken signs the http body and cert with ECDSA using EC private key

func GetBCCSP

func GetBCCSP(opts *factory.FactoryOpts, homeDir string) (bccsp.BCCSP, error)

GetBCCSP returns BCCSP

func GetCertificateDuration

func GetCertificateDuration(cert *x509.Certificate) time.Duration

GetCertificateDuration returns the validity duration for a certificate

func GetCertificateDurationFromFile

func GetCertificateDurationFromFile(file string) (time.Duration, error)

GetCertificateDurationFromFile returns the validity duration for a certificate in a file.

func GetCommandLineOptValue

func GetCommandLineOptValue(optName string, remove bool) string

GetCommandLineOptValue searches the command line arguments for the specified option and returns the following value if found; otherwise it returns "". If **remove** is true and it is found, the option and its value are removed from os.Args. For example, if command line is:

fabric-ca client enroll -config myconfig.json

GetCommandLineOptValue("-config",true) returns "myconfig.json" and changes os.Args to

fabric-ca client enroll

func GetDefaultBCCSP

func GetDefaultBCCSP() bccsp.BCCSP

GetDefaultBCCSP returns the default BCCSP

func GetDefaultConfigFile

func GetDefaultConfigFile(cmdName string) string

GetDefaultConfigFile gets the default path for the config file to display in usage message

func GetECPrivateKey

func GetECPrivateKey(raw []byte) (*ecdsa.PrivateKey, error)

GetECPrivateKey get *ecdsa.PrivateKey from key pem

func GetEnrollmentIDFromPEM

func GetEnrollmentIDFromPEM(cert []byte) (string, error)

GetEnrollmentIDFromPEM returns the EnrollmentID from a PEM buffer

func GetEnrollmentIDFromX509Certificate

func GetEnrollmentIDFromX509Certificate(cert *x509.Certificate) string

GetEnrollmentIDFromX509Certificate returns the EnrollmentID from the X509 certificate

func GetMaskedURL

func GetMaskedURL(url string) string

GetMaskedURL returns masked URL. It masks username and password from the URL if present

func GetRSAPrivateKey

func GetRSAPrivateKey(raw []byte) (*rsa.PrivateKey, error)

GetRSAPrivateKey get *rsa.PrivateKey from key pem

func GetSM2PrivateKey

func GetSM2PrivateKey(raw []byte) (*sm2.PrivateKey, error)

GetSM2PrivateKey get *sm2.PrivateKey from key pem

func GetSerialAsHex

func GetSerialAsHex(serial *big.Int) string

GetSerialAsHex returns the serial number from certificate as hex format

func GetServerAddr

func GetServerAddr() string

GetServerAddr returns the server's address

func GetServerPort

func GetServerPort() string

GetServerPort returns the server's listening port

func GetServerProtocol

func GetServerProtocol() string

GetServerProtocol returns the server's protocol

func GetServerURL

func GetServerURL() string

GetServerURL returns the server's URL

func GetSignerFromCert

func GetSignerFromCert(cert *x509.Certificate, csp bccsp.BCCSP) (bccsp.Key, crypto.Signer, error)

GetSignerFromCert load private key represented by ski and return bccsp signer that conforms to crypto.Signer

func GetSignerFromCertFile

func GetSignerFromCertFile(certFile string, csp bccsp.BCCSP) (bccsp.Key, crypto.Signer, *x509.Certificate, error)

GetSignerFromCertFile load skiFile and load private key represented by ski and return bccsp signer that conforms to crypto.Signer

func GetSignerFromSM2Cert

func GetSignerFromSM2Cert(cert *x509GM.Certificate, csp bccsp.BCCSP) (bccsp.Key, crypto.Signer, error)

GetSignerFromSM2Cert load private key represented by ski and return bccsp signer that conforms to crypto.Signer

func GetSliceFromList

func GetSliceFromList(split string, delim string) []string

GetSliceFromList will return a slice from a list

func GetUser

func GetUser(v *viper.Viper) (string, string, error)

GetUser returns username and password from CLI input

func GetX509CertificateFromPEM

func GetX509CertificateFromPEM(cert []byte) (*x509.Certificate, error)

GetX509CertificateFromPEM get an X509 certificate from bytes in PEM format

func GetX509CertificateFromPEMFile

func GetX509CertificateFromPEMFile(file string) (*x509.Certificate, error)

GetX509CertificateFromPEMFile gets an X509 certificate from a file

func GetX509CertificatesFromPEM

func GetX509CertificatesFromPEM(pemBytes []byte) ([]*x509.Certificate, error)

GetX509CertificatesFromPEM returns X509 certificates from bytes in PEM format

func HTTPRequestToString

func HTTPRequestToString(req *http.Request) string

HTTPRequestToString returns a string for an HTTP request for debuggging

func HTTPResponseToString

func HTTPResponseToString(resp *http.Response) string

HTTPResponseToString returns a string for an HTTP response for debuggging

func Hostname

func Hostname() string

Hostname name returns the hostname of the machine

func ImportBCCSPKeyFromPEM

func ImportBCCSPKeyFromPEM(keyFile string, myCSP bccsp.BCCSP, temporary bool) (bccsp.Key, error)

ImportBCCSPKeyFromPEM attempts to create a private BCCSP key from a pem file keyFile

func InitBCCSP

func InitBCCSP(optsPtr **factory.FactoryOpts, mspDir, homeDir string) (bccsp.BCCSP, error)

InitBCCSP initializes BCCSP

func IsGMConfig

func IsGMConfig() bool

func IsSubsetOf

func IsSubsetOf(small, big string) error

IsSubsetOf returns an error if there is something in 'small' that is not in 'big'. Both small and big are assumed to be comma-separated strings. All string comparisons are case-insensitive. Examples: 1) IsSubsetOf('a,B', 'A,B,C') returns nil 2) IsSubsetOf('A,B,C', 'B,C') returns an error because A is not in the 2nd set.

func ListContains

func ListContains(list, find string) bool

ListContains looks through a comma separated list to see if a string exists

func LoadX509KeyPair

func LoadX509KeyPair(certFile, keyFile string, csp bccsp.BCCSP) (*tls.Certificate, error)

LoadX509KeyPair reads and parses a public/private key pair from a pair of files. The files must contain PEM encoded data. The certificate file may contain intermediate certificates following the leaf certificate to form a certificate chain. On successful return, Certificate.Leaf will be nil because the parsed form of the certificate is not retained.

This function originated from crypto/tls/tls.go and was adapted to use a BCCSP Signer

func LoadX509KeyPairSM2

func LoadX509KeyPairSM2(certFile, keyFile string, csp bccsp.BCCSP) (bccsp.Key, *gtls.Certificate, error)

func MakeFileAbs

func MakeFileAbs(file, dir string) (string, error)

MakeFileAbs makes 'file' absolute relative to 'dir' if not already absolute

func MakeFileNamesAbsolute

func MakeFileNamesAbsolute(files []*string, home string) error

MakeFileNamesAbsolute makes all file names in the list absolute, relative to home

func Marshal

func Marshal(from interface{}, what string) ([]byte, error)

Marshal to bytes

func NormalizeFileList

func NormalizeFileList(files []string, homeDir string) ([]string, error)

NormalizeFileList provides absolute pathing for the list of files

func NormalizeStringSlice

func NormalizeStringSlice(slice []string) []string

NormalizeStringSlice checks for seperators

func ParseObj

func ParseObj(obj interface{}, cb func(*Field) error, tags map[string]string) error

ParseObj parses an object structure, calling back with field info for each field

func ParseSm2Certificate2X509

func ParseSm2Certificate2X509(sm2Cert *x509GM.Certificate) *x509.Certificate

sm2 证书转换 x509 证书

func ParseX509Certificate2Sm2

func ParseX509Certificate2Sm2(x509Cert *x509.Certificate) *x509GM.Certificate

X509证书格式转换为 SM2证书格式

func RandomString

func RandomString(n int) string

RandomString returns a random string

func Read

func Read(r io.Reader, data []byte) ([]byte, error)

Read reads from Reader into a byte array

func ReadFile

func ReadFile(file string) ([]byte, error)

ReadFile reads a file

func RegisterFlags

func RegisterFlags(v *viper.Viper, flags *pflag.FlagSet, config interface{},
	tags map[string]string) error

RegisterFlags registers flags for all fields in an arbitrary 'config' object. This method recognizes the following field tags: "def" - the default value of the field; "opt" - the optional one character short name to use on the command line; "help" - the help message to display on the command line; "skip" - to skip the field.

func RemoveQuotes

func RemoveQuotes(str string) string

RemoveQuotes removes outer quotes from a string if necessary

func SetDefaultServerPort

func SetDefaultServerPort()

SetDefaultServerPort overrides the default CFSSL server port by adding the "-port" option to the command line if it was not already present.

func SetProviderName

func SetProviderName(name string)

func StrContained

func StrContained(str string, strs []string) bool

StrContained returns true if 'str' is in 'strs'; otherwise return false

func StructToString

func StructToString(si interface{}) string

StructToString converts a struct to a string. If a field has a 'secret' tag, it is masked in the returned string

func Unmarshal

func Unmarshal(from []byte, to interface{}, what string) error

Unmarshal from bytes

func ValidateAndReturnAbsConf

func ValidateAndReturnAbsConf(configFilePath, homeDir, cmdName string) (string, string, error)

ValidateAndReturnAbsConf checks to see that there are no conflicts between the configuration file path and home directory. If no conflicts, returns back the absolute path for the configuration file and home directory.

func VerifyToken

func VerifyToken(csp bccsp.BCCSP, token string, method, uri string, body []byte, compMode1_3 bool) (*x509.Certificate, error)

VerifyToken verifies token signed by either ECDSA or RSA and returns the associated user ID

func ViperUnmarshal

func ViperUnmarshal(cfg interface{}, stringSliceFields []string, vp *viper.Viper) error

ViperUnmarshal is a work around for a bug in viper.Unmarshal This can be removed once https://github.com/spf13/viper/issues/327 is fixed and vendored.

func WriteFile

func WriteFile(file string, buf []byte, perm os.FileMode) error

WriteFile writes a file

Types

type ECDSASignature

type ECDSASignature struct {
	R, S *big.Int
}

ECDSASignature forms the structure for R and S value for ECDSA

type Field

type Field struct {
	Name  string
	Path  string
	Type  reflect.Type
	Kind  reflect.Kind
	Leaf  bool
	Depth int
	Tag   reflect.StructTag
	Value interface{}
	Addr  interface{}
	Hide  string
}

Field is a field of an arbitrary struct

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL