lego/acme/crypto_test.go

77 lines
2 KiB
Go
Raw Normal View History

package acme
import (
"bytes"
2016-01-27 01:01:58 +00:00
"crypto/rand"
"crypto/rsa"
"testing"
"time"
2018-09-15 17:16:35 +00:00
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGeneratePrivateKey(t *testing.T) {
2016-01-27 01:01:58 +00:00
key, err := generatePrivateKey(RSA2048)
2018-09-15 17:16:35 +00:00
require.NoError(t, err, "Error generating private key")
assert.NotNil(t, key)
}
func TestGenerateCSR(t *testing.T) {
2016-01-27 01:01:58 +00:00
key, err := rsa.GenerateKey(rand.Reader, 512)
2018-09-15 17:16:35 +00:00
require.NoError(t, err, "Error generating private key")
csr, err := generateCsr(key, "fizz.buzz", nil, true)
2018-09-15 17:16:35 +00:00
require.NoError(t, err, "Error generating CSR")
assert.NotEmpty(t, csr)
}
func TestPEMEncode(t *testing.T) {
buf := bytes.NewBufferString("TestingRSAIsSoMuchFun")
reader := MockRandReader{b: buf}
key, err := rsa.GenerateKey(reader, 32)
2018-09-15 17:16:35 +00:00
require.NoError(t, err, "Error generating private key")
data := pemEncode(key)
2018-09-15 17:16:35 +00:00
require.NotNil(t, data)
assert.Len(t, data, 127)
}
func TestPEMCertExpiration(t *testing.T) {
2016-01-27 01:01:58 +00:00
privKey, err := generatePrivateKey(RSA2048)
2018-09-15 17:16:35 +00:00
require.NoError(t, err, "Error generating private key")
expiration := time.Now().Add(365)
expiration = expiration.Round(time.Second)
certBytes, err := generateDerCert(privKey.(*rsa.PrivateKey), expiration, "test.com", nil)
2018-09-15 17:16:35 +00:00
require.NoError(t, err, "Error generating cert")
buf := bytes.NewBufferString("TestingRSAIsSoMuchFun")
// Some random string should return an error.
2018-09-15 17:16:35 +00:00
ctime, err := GetPEMCertExpiration(buf.Bytes())
require.Errorf(t, err, "Expected getCertExpiration to return an error for garbage string but returned %v", ctime)
// A DER encoded certificate should return an error.
2018-09-15 17:16:35 +00:00
_, err = GetPEMCertExpiration(certBytes)
require.Error(t, err, "Expected getCertExpiration to return an error for DER certificates")
// A PEM encoded certificate should work ok.
pemCert := pemEncode(derCertificateBytes(certBytes))
2018-09-15 17:16:35 +00:00
ctime, err = GetPEMCertExpiration(pemCert)
require.NoError(t, err)
assert.Equal(t, expiration.UTC(), ctime)
}
type MockRandReader struct {
b *bytes.Buffer
}
func (r MockRandReader) Read(p []byte) (int, error) {
return r.b.Read(p)
}