auth.go 1.11 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
package security

import (
	"crypto/rsa"
	"crypto/x509"
)

// AuthContainer contains common information for TLS authentication.
// Files are not loaded from the beginning, call LoadFiles to load them.
type AuthContainer struct {
	FileCA     string
	FileCert   string
	FileKey    string
	AddrPort   string
	Passphrase string

	CA   *x509.Certificate
	Cert *x509.Certificate
	Key  *rsa.PrivateKey
}

// NewAuthContainer is a shortcut to build a AuthContainer
func NewAuthContainer(fileCA, fileCert, fileKey, addrPort, passphrase string) *AuthContainer {
	return &AuthContainer{
		FileCA:     fileCA,
		FileCert:   fileCert,
		FileKey:    fileKey,
		AddrPort:   addrPort,
		Passphrase: passphrase,
	}
}

// LoadFiles tries to load the required certificates and key for TLS authentication
func (a *AuthContainer) LoadFiles() (ca *x509.Certificate, cert *x509.Certificate, key *rsa.PrivateKey, err error) {
	ca, err = GetCertificate(a.FileCA)
	if err != nil {
		return
	}
	cert, err = GetCertificate(a.FileCert)
	if err != nil {
		return
	}
	key, err = GetPrivateKey(a.FileKey, a.Passphrase)

	a.CA = ca
	a.Cert = cert
	a.Key = key

	return
}