request.go 1.16 KB
Newer Older
1 2 3 4 5 6
// Package security is responsible for generating keys and certificate requests
package security

import (
	"crypto/rsa"
	"fmt"
ElyKar's avatar
ElyKar committed
7

Caro Axel's avatar
Caro Axel committed
8 9
	"dfss/auth"
	"dfss/dfssc/common"
ElyKar's avatar
ElyKar committed
10
	"github.com/spf13/viper"
11 12 13
)

// GenerateKeys generate a pair of keys and save it to the disk
ElyKar's avatar
ElyKar committed
14
func GenerateKeys(bits int, passphrase string) (*rsa.PrivateKey, error) {
15 16 17 18 19 20 21 22 23 24
	key, err := auth.GeneratePrivateKey(bits)
	if err != nil {
		return nil, err
	}

	pem, err := auth.PrivateKeyToEncryptedPEM(key, passphrase)
	if err != nil {
		return nil, err
	}

ElyKar's avatar
ElyKar committed
25
	err = common.SaveToDisk(pem, viper.GetString("file_key"))
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
	if err != nil {
		return nil, err
	}

	return key, nil
}

// GenerateCertificateRequest generate a certificate request from data, and
// return a PEM-encoded certificate as a string
func GenerateCertificateRequest(country, organization, unit, mail string, key *rsa.PrivateKey) (string, error) {
	data, err := auth.GetCertificateRequest(country, organization, unit, mail, key)
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("%s", data), nil

}

// SaveCertificate saves a PEM-encoded certificate on disk
func SaveCertificate(cert, filename string) error {
	return common.SaveStringToDisk(cert, filename)
}