Ceremony: refactor key ceremonies to share more code
diff --git a/cmd/ceremony/ecdsa.go b/cmd/ceremony/ecdsa.go
index e6d8700..4f0a699 100644
--- a/cmd/ceremony/ecdsa.go
+++ b/cmd/ceremony/ecdsa.go
@@ -1,7 +1,7 @@
 package main
 
 import (
-	"crypto/ecdsa"
+	"crypto"
 	"crypto/elliptic"
 	"errors"
 	"fmt"
@@ -25,83 +25,47 @@
 	elliptic.P521().Params().Name: {6, 5, 43, 129, 4, 0, 35},
 }
 
-// ecArgs constructs the private and public key template attributes sent to the
-// device and specifies which mechanism should be used. curve determines which
-// type of key should be generated.
-func ecArgs(label string, curve elliptic.Curve, keyID []byte) generateArgs {
-	encodedCurve := curveToOIDDER[curve.Params().Name]
-	log.Printf("\tEncoded curve parameters for %s: %X\n", curve.Params().Name, encodedCurve)
-	return generateArgs{
-		mechanism: []*pkcs11.Mechanism{
-			pkcs11.NewMechanism(pkcs11.CKM_EC_KEY_PAIR_GEN, nil),
-		},
-		publicAttrs: []*pkcs11.Attribute{
-			pkcs11.NewAttribute(pkcs11.CKA_ID, keyID),
-			pkcs11.NewAttribute(pkcs11.CKA_LABEL, label),
-			pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
-			pkcs11.NewAttribute(pkcs11.CKA_VERIFY, true),
-			pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, encodedCurve),
-		},
-		privateAttrs: []*pkcs11.Attribute{
-			pkcs11.NewAttribute(pkcs11.CKA_ID, keyID),
-			pkcs11.NewAttribute(pkcs11.CKA_LABEL, label),
-			pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
-			// Prevent attributes being retrieved
-			pkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, true),
-			// Prevent the key being extracted from the device
-			pkcs11.NewAttribute(pkcs11.CKA_EXTRACTABLE, false),
-			// Allow the key to sign data
-			pkcs11.NewAttribute(pkcs11.CKA_SIGN, true),
-		},
+// ecKeyGen is a keyGenerator for ECDSA key pairs on the given curve.
+type ecKeyGen struct {
+	curve elliptic.Curve
+}
+
+// newECKeyGen returns an ecKeyGen for ECDSA key pairs on the curve specified by
+// curveStr.
+func newECKeyGen(curveStr string) (ecKeyGen, error) {
+	curve, present := stringToCurve[curveStr]
+	if !present {
+		return ecKeyGen{}, fmt.Errorf("curve %q not supported", curveStr)
+	}
+	log.Printf("Generating ECDSA key with curve %s\n", curveStr)
+	return ecKeyGen{curve: curve}, nil
+}
+
+func (g ecKeyGen) mechanism() uint {
+	return pkcs11.CKM_EC_KEY_PAIR_GEN
+}
+
+// publicAttrs specifies the curve of the key.
+func (g ecKeyGen) publicAttrs() []*pkcs11.Attribute {
+	encodedCurve := curveToOIDDER[g.curve.Params().Name]
+	log.Printf("\tEncoded curve parameters for %s: %X\n", g.curve.Params().Name, encodedCurve)
+	return []*pkcs11.Attribute{
+		pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, encodedCurve),
 	}
 }
 
-// ecPub extracts the generated public key, specified by the provided object
+// publicKey extracts the generated public key, specified by the provided object
 // handle, and constructs an ecdsa.PublicKey. It also checks that the key is of
 // the correct curve type.
-func ecPub(
-	session *pkcs11helpers.Session,
-	object pkcs11.ObjectHandle,
-	expectedCurve elliptic.Curve,
-) (*ecdsa.PublicKey, error) {
+func (g ecKeyGen) publicKey(session *pkcs11helpers.Session, object pkcs11.ObjectHandle) (crypto.PublicKey, error) {
 	pubKey, err := session.GetECDSAPublicKey(object)
 	if err != nil {
 		return nil, err
 	}
-	if pubKey.Curve != expectedCurve {
+	if pubKey.Curve != g.curve {
 		return nil, errors.New("returned EC parameters doesn't match expected curve")
 	}
 	log.Printf("\tX: %X\n", pubKey.X.Bytes())
 	log.Printf("\tY: %X\n", pubKey.Y.Bytes())
 	return pubKey, nil
 }
-
-// ecGenerate is used to generate and verify a ECDSA key pair of the type
-// specified by curveStr and with the provided label. It returns the public
-// part of the generated key pair as a ecdsa.PublicKey and the random key ID
-// that the HSM uses to identify the key pair.
-func ecGenerate(session *pkcs11helpers.Session, label, curveStr string) (*ecdsa.PublicKey, []byte, error) {
-	curve, present := stringToCurve[curveStr]
-	if !present {
-		return nil, nil, fmt.Errorf("curve %q not supported", curveStr)
-	}
-	keyID := make([]byte, 4)
-	_, err := newRandReader(session).Read(keyID)
-	if err != nil {
-		return nil, nil, err
-	}
-	log.Printf("Generating ECDSA key with curve %s and ID %x\n", curveStr, keyID)
-	args := ecArgs(label, curve, keyID)
-	pub, _, err := session.GenerateKeyPair(args.mechanism, args.publicAttrs, args.privateAttrs)
-	if err != nil {
-		return nil, nil, err
-	}
-	log.Println("Key generated")
-	log.Println("Extracting public key")
-	pk, err := ecPub(session, pub, curve)
-	if err != nil {
-		return nil, nil, err
-	}
-	log.Println("Extracted public key")
-	return pk, keyID, nil
-}
diff --git a/cmd/ceremony/ecdsa_test.go b/cmd/ceremony/ecdsa_test.go
index 8bd3486..510ef77 100644
--- a/cmd/ceremony/ecdsa_test.go
+++ b/cmd/ceremony/ecdsa_test.go
@@ -12,15 +12,15 @@
 	"github.com/miekg/pkcs11"
 )
 
-func TestECPub(t *testing.T) {
+func TestECPublicKey(t *testing.T) {
 	s, ctx := pkcs11helpers.NewSessionWithMock()
 
 	// test we fail when pkcs11helpers.GetECDSAPublicKey fails
 	ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
 		return nil, errors.New("bad!")
 	}
-	_, err := ecPub(s, 0, elliptic.P256())
-	test.AssertError(t, err, "ecPub didn't fail with non-matching curve")
+	_, err := ecKeyGen{curve: elliptic.P256()}.publicKey(s, 0)
+	test.AssertError(t, err, "publicKey didn't fail with non-matching curve")
 	test.AssertEquals(t, err.Error(), "Failed to retrieve key attributes: bad!")
 
 	// test we fail to construct key with non-matching curve
@@ -30,8 +30,8 @@
 			pkcs11.NewAttribute(pkcs11.CKA_EC_POINT, []byte{4, 217, 225, 246, 210, 153, 134, 246, 104, 95, 79, 122, 206, 135, 241, 37, 114, 199, 87, 56, 167, 83, 56, 136, 174, 6, 145, 97, 239, 221, 49, 67, 148, 13, 126, 65, 90, 208, 195, 193, 171, 105, 40, 98, 132, 124, 30, 189, 215, 197, 178, 226, 166, 238, 240, 57, 215}),
 		}, nil
 	}
-	_, err = ecPub(s, 0, elliptic.P256())
-	test.AssertError(t, err, "ecPub didn't fail with non-matching curve")
+	_, err = ecKeyGen{curve: elliptic.P256()}.publicKey(s, 0)
+	test.AssertError(t, err, "publicKey didn't fail with non-matching curve")
 }
 
 func TestECGenerate(t *testing.T) {
@@ -43,28 +43,31 @@
 	priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
 	test.AssertNotError(t, err, "Failed to generate a ECDSA test key")
 
-	// Test ecGenerate fails with unknown curve
-	_, _, err = ecGenerate(s, "", "bad-curve")
-	test.AssertError(t, err, "ecGenerate accepted unknown curve")
+	// Test newECKeyGen fails with unknown curve
+	_, err = newECKeyGen("bad-curve")
+	test.AssertError(t, err, "newECKeyGen accepted unknown curve")
 
-	// Test ecGenerate fails when GenerateKeyPair fails
+	gen, err := newECKeyGen("P-256")
+	test.AssertNotError(t, err, "newECKeyGen failed with valid curve")
+
+	// Test generateKeyPair fails when GenerateKeyPair fails
 	ctx.GenerateKeyPairFunc = func(pkcs11.SessionHandle, []*pkcs11.Mechanism, []*pkcs11.Attribute, []*pkcs11.Attribute) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) {
 		return 0, 0, errors.New("bad")
 	}
-	_, _, err = ecGenerate(s, "", "P-256")
-	test.AssertError(t, err, "ecGenerate didn't fail on GenerateKeyPair error")
+	_, _, err = generateKeyPair(s, "", gen)
+	test.AssertError(t, err, "generateKeyPair didn't fail on GenerateKeyPair error")
 
-	// Test ecGenerate fails when ecPub fails
+	// Test generateKeyPair fails when publicKey fails
 	ctx.GenerateKeyPairFunc = func(pkcs11.SessionHandle, []*pkcs11.Mechanism, []*pkcs11.Attribute, []*pkcs11.Attribute) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) {
 		return 0, 0, nil
 	}
 	ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
 		return nil, errors.New("bad")
 	}
-	_, _, err = ecGenerate(s, "", "P-256")
-	test.AssertError(t, err, "ecGenerate didn't fail on ecPub error")
+	_, _, err = generateKeyPair(s, "", gen)
+	test.AssertError(t, err, "generateKeyPair didn't fail on publicKey error")
 
-	// Test ecGenerate fails when ecVerify fails
+	// Test generateKeyPair fails when ecVerify fails
 	ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
 		return []*pkcs11.Attribute{
 			pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, []byte{6, 8, 42, 134, 72, 206, 61, 3, 1, 7}),
@@ -74,10 +77,10 @@
 	ctx.GenerateRandomFunc = func(pkcs11.SessionHandle, int) ([]byte, error) {
 		return nil, errors.New("yup")
 	}
-	_, _, err = ecGenerate(s, "", "P-256")
-	test.AssertError(t, err, "ecGenerate didn't fail on ecVerify error")
+	_, _, err = generateKeyPair(s, "", gen)
+	test.AssertError(t, err, "generateKeyPair didn't fail on ecVerify error")
 
-	// Test ecGenerate doesn't fail when everything works
+	// Test generateKeyPair doesn't fail when everything works
 	ctx.SignInitFunc = func(pkcs11.SessionHandle, []*pkcs11.Mechanism, pkcs11.ObjectHandle) error {
 		return nil
 	}
@@ -87,8 +90,8 @@
 	ctx.SignFunc = func(_ pkcs11.SessionHandle, msg []byte) ([]byte, error) {
 		return ecPKCS11Sign(priv, msg)
 	}
-	_, _, err = ecGenerate(s, "", "P-256")
-	test.AssertNotError(t, err, "ecGenerate didn't succeed when everything worked as expected")
+	_, _, err = generateKeyPair(s, "", gen)
+	test.AssertNotError(t, err, "generateKeyPair didn't succeed when everything worked as expected")
 }
 
 func ecPKCS11Sign(priv *ecdsa.PrivateKey, msg []byte) ([]byte, error) {
diff --git a/cmd/ceremony/key.go b/cmd/ceremony/key.go
index 5db5987..37644ea 100644
--- a/cmd/ceremony/key.go
+++ b/cmd/ceremony/key.go
@@ -29,10 +29,66 @@
 	return len(r), nil
 }
 
-type generateArgs struct {
-	mechanism    []*pkcs11.Mechanism
-	privateAttrs []*pkcs11.Attribute
-	publicAttrs  []*pkcs11.Attribute
+// keyGenerator supplies the parts of generating a key pair on an HSM which are
+// specific to one type of key. generateKeyPair supplies everything else,
+// including the template attributes common to all types of key.
+type keyGenerator interface {
+	// mechanism returns the PKCS#11 mechanism (a CKM_* value) which generates
+	// key pairs of this type.
+	mechanism() uint
+	// publicAttrs returns the attributes which specify the requested key, such
+	// as its size, to add to the common public key template.
+	publicAttrs() []*pkcs11.Attribute
+	// publicKey retrieves the generated public key from the HSM, and checks
+	// that it is the key that was requested.
+	publicKey(session *pkcs11helpers.Session, object pkcs11.ObjectHandle) (crypto.PublicKey, error)
+}
+
+// generateKeyPair generates a key pair of the type specified by gen on the
+// HSM, with the provided label and a random key ID. The private key is allowed
+// to sign, and is marked sensitive and non-extractable. It returns the public
+// part of the generated key pair and the key ID.
+func generateKeyPair(session *pkcs11helpers.Session, label string, gen keyGenerator) (crypto.PublicKey, []byte, error) {
+	keyID := make([]byte, 4)
+	_, err := newRandReader(session).Read(keyID)
+	if err != nil {
+		return nil, nil, err
+	}
+	log.Printf("\tKey ID: %x\n", keyID)
+
+	publicAttrs := []*pkcs11.Attribute{
+		pkcs11.NewAttribute(pkcs11.CKA_ID, keyID),
+		pkcs11.NewAttribute(pkcs11.CKA_LABEL, label),
+		pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
+		// Allow the key to verify signatures
+		pkcs11.NewAttribute(pkcs11.CKA_VERIFY, true),
+	}
+	publicAttrs = append(publicAttrs, gen.publicAttrs()...)
+	privateAttrs := []*pkcs11.Attribute{
+		pkcs11.NewAttribute(pkcs11.CKA_ID, keyID),
+		pkcs11.NewAttribute(pkcs11.CKA_LABEL, label),
+		pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
+		// Prevent attributes being retrieved
+		pkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, true),
+		// Prevent the key being extracted from the device
+		pkcs11.NewAttribute(pkcs11.CKA_EXTRACTABLE, false),
+		// Allow the key to create signatures
+		pkcs11.NewAttribute(pkcs11.CKA_SIGN, true),
+	}
+	mechanism := []*pkcs11.Mechanism{pkcs11.NewMechanism(gen.mechanism(), nil)}
+
+	pub, _, err := session.GenerateKeyPair(mechanism, publicAttrs, privateAttrs)
+	if err != nil {
+		return nil, nil, err
+	}
+	log.Println("Key generated")
+	log.Println("Extracting public key")
+	pk, err := gen.publicKey(session, pub)
+	if err != nil {
+		return nil, nil, err
+	}
+	log.Println("Extracted public key")
+	return pk, keyID, nil
 }
 
 // keyInfo is a struct used to pass around information about the public key
@@ -55,12 +111,17 @@
 	var keyID []byte
 	switch config.Type {
 	case "rsa":
-		pubKey, keyID, err = rsaGenerate(session, label, config.RSAModLength)
+		pubKey, keyID, err = generateKeyPair(session, label, newRSAKeyGen(config.RSAModLength))
 		if err != nil {
 			return nil, fmt.Errorf("failed to generate RSA key pair: %w", err)
 		}
 	case "ecdsa":
-		pubKey, keyID, err = ecGenerate(session, label, config.ECDSACurve)
+		var gen ecKeyGen
+		gen, err = newECKeyGen(config.ECDSACurve)
+		if err != nil {
+			return nil, fmt.Errorf("failed to generate ECDSA key pair: %w", err)
+		}
+		pubKey, keyID, err = generateKeyPair(session, label, gen)
 		if err != nil {
 			return nil, fmt.Errorf("failed to generate ECDSA key pair: %w", err)
 		}
diff --git a/cmd/ceremony/key_test.go b/cmd/ceremony/key_test.go
index 5a1768c..caa7435 100644
--- a/cmd/ceremony/key_test.go
+++ b/cmd/ceremony/key_test.go
@@ -8,15 +8,20 @@
 	"crypto/rsa"
 	"crypto/x509"
 	"encoding/pem"
+	"errors"
+	"fmt"
 	"math/big"
 	"os"
 	"path"
+	"reflect"
+	"slices"
 	"strings"
 	"testing"
 
+	"github.com/miekg/pkcs11"
+
 	"github.com/letsencrypt/boulder/pkcs11helpers"
 	"github.com/letsencrypt/boulder/test"
-	"github.com/miekg/pkcs11"
 )
 
 func setupCtx() pkcs11helpers.MockCtx {
@@ -109,6 +114,101 @@
 	test.AssertDeepEquals(t, diskKey, keyInfo.key)
 }
 
+// fmtAttrs formats attrs as their types and values, for test failure messages.
+func fmtAttrs(attrs []*pkcs11.Attribute) string {
+	var parts []string
+	for _, a := range attrs {
+		parts = append(parts, fmt.Sprintf("%#x=%x", a.Type, a.Value))
+	}
+	return "[" + strings.Join(parts, " ") + "]"
+}
+
+// fakeKeyGen is a keyGenerator which returns fixed values.
+type fakeKeyGen struct {
+	pub crypto.PublicKey
+	err error
+}
+
+func (f fakeKeyGen) mechanism() uint {
+	return pkcs11.CKM_VENDOR_DEFINED
+}
+
+func (f fakeKeyGen) publicAttrs() []*pkcs11.Attribute {
+	return []*pkcs11.Attribute{pkcs11.NewAttribute(pkcs11.CKA_VENDOR_DEFINED, "fake")}
+}
+
+func (f fakeKeyGen) publicKey(*pkcs11helpers.Session, pkcs11.ObjectHandle) (crypto.PublicKey, error) {
+	return f.pub, f.err
+}
+
+func TestGenerateKeyPair(t *testing.T) {
+	keyID := []byte{0xa, 0xb, 0xc, 0xd}
+	ctx := setupCtx()
+	ctx.GenerateRandomFunc = func(pkcs11.SessionHandle, int) ([]byte, error) {
+		return keyID, nil
+	}
+	var gotMechs []*pkcs11.Mechanism
+	var gotPubTmpl, gotPrivTmpl []*pkcs11.Attribute
+	ctx.GenerateKeyPairFunc = func(_ pkcs11.SessionHandle, mechs []*pkcs11.Mechanism, pubTmpl []*pkcs11.Attribute, privTmpl []*pkcs11.Attribute) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) {
+		gotMechs = mechs
+		gotPubTmpl = pubTmpl
+		gotPrivTmpl = privTmpl
+		return 0, 0, nil
+	}
+	s := &pkcs11helpers.Session{Module: &ctx, Session: 0}
+	wantPub := &rsa.PublicKey{N: big.NewInt(1337), E: 65537}
+
+	gotPub, gotKeyID, err := generateKeyPair(s, "label", fakeKeyGen{pub: wantPub})
+	if err != nil {
+		t.Fatalf("generateKeyPair() = %v, want success", err)
+	}
+	if gotPub != wantPub {
+		t.Errorf("generateKeyPair() returned key %v, want the keyGenerator's %v", gotPub, wantPub)
+	}
+	if !slices.Equal(gotKeyID, keyID) {
+		t.Errorf("generateKeyPair() returned key ID %x, want %x", gotKeyID, keyID)
+	}
+
+	wantMechs := []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_VENDOR_DEFINED, nil)}
+	if !reflect.DeepEqual(gotMechs, wantMechs) {
+		t.Errorf("GenerateKeyPair got mechanisms %v, want %v", gotMechs, wantMechs)
+	}
+	// The public template is the common attributes followed by the
+	// keyGenerator's attributes.
+	wantPubTmpl := []*pkcs11.Attribute{
+		pkcs11.NewAttribute(pkcs11.CKA_ID, keyID),
+		pkcs11.NewAttribute(pkcs11.CKA_LABEL, "label"),
+		pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
+		pkcs11.NewAttribute(pkcs11.CKA_VERIFY, true),
+		pkcs11.NewAttribute(pkcs11.CKA_VENDOR_DEFINED, "fake"),
+	}
+	if !reflect.DeepEqual(gotPubTmpl, wantPubTmpl) {
+		t.Errorf("GenerateKeyPair got public template %s, want %s", fmtAttrs(gotPubTmpl), fmtAttrs(wantPubTmpl))
+	}
+	wantPrivTmpl := []*pkcs11.Attribute{
+		pkcs11.NewAttribute(pkcs11.CKA_ID, keyID),
+		pkcs11.NewAttribute(pkcs11.CKA_LABEL, "label"),
+		pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
+		pkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, true),
+		pkcs11.NewAttribute(pkcs11.CKA_EXTRACTABLE, false),
+		pkcs11.NewAttribute(pkcs11.CKA_SIGN, true),
+	}
+	if !reflect.DeepEqual(gotPrivTmpl, wantPrivTmpl) {
+		t.Errorf("GenerateKeyPair got private template %s, want %s", fmtAttrs(gotPrivTmpl), fmtAttrs(wantPrivTmpl))
+	}
+
+	// When the keyGenerator fails to retrieve the public key, generateKeyPair
+	// fails and returns a nil key, even if the keyGenerator returned a typed
+	// nil pointer.
+	gotPub, _, err = generateKeyPair(s, "label", fakeKeyGen{pub: (*rsa.PublicKey)(nil), err: errors.New("publicKey broke")})
+	if err == nil || !strings.Contains(err.Error(), "publicKey broke") {
+		t.Errorf("generateKeyPair() = %v, want publicKey error", err)
+	}
+	if gotPub != nil {
+		t.Errorf("generateKeyPair() returned key %#v alongside error, want nil", gotPub)
+	}
+}
+
 func setFindObjectsFuncs(label string, ctx *pkcs11helpers.MockCtx) {
 	var objectsFound []pkcs11.ObjectHandle
 	ctx.FindObjectsInitFunc = func(_ pkcs11.SessionHandle, template []*pkcs11.Attribute) error {
diff --git a/cmd/ceremony/rsa.go b/cmd/ceremony/rsa.go
index 7d0eb4b..ac05bfb 100644
--- a/cmd/ceremony/rsa.go
+++ b/cmd/ceremony/rsa.go
@@ -1,7 +1,7 @@
 package main
 
 import (
-	"crypto/rsa"
+	"crypto"
 	"errors"
 	"log"
 	"math/big"
@@ -15,48 +15,41 @@
 	rsaExp = 65537
 )
 
-// rsaArgs constructs the private and public key template attributes sent to the
-// device and specifies which mechanism should be used. modulusLen specifies the
-// length of the modulus to be generated on the device in bits and exponent
-// specifies the public exponent that should be used.
-func rsaArgs(label string, modulusLen int, keyID []byte) generateArgs {
+// rsaKeyGen is a keyGenerator for RSA key pairs with a modulus of modulusLen
+// bits and the public exponent rsaExp.
+type rsaKeyGen struct {
+	modulusLen int
+}
+
+// newRSAKeyGen returns an rsaKeyGen for RSA key pairs with a modulus of
+// modulusLen bits and the public exponent rsaExp.
+func newRSAKeyGen(modulusLen int) rsaKeyGen {
+	log.Printf("Generating RSA key with %d bit modulus and public exponent %d\n", modulusLen, rsaExp)
+	return rsaKeyGen{modulusLen: modulusLen}
+}
+
+func (g rsaKeyGen) mechanism() uint {
+	return pkcs11.CKM_RSA_PKCS_KEY_PAIR_GEN
+}
+
+// publicAttrs specifies the modulus length and public exponent of the key.
+func (g rsaKeyGen) publicAttrs() []*pkcs11.Attribute {
 	// Encode as unpadded big endian encoded byte slice
 	expSlice := big.NewInt(rsaExp).Bytes()
 	log.Printf("\tEncoded public exponent (%d) as: %0X\n", rsaExp, expSlice)
-	return generateArgs{
-		mechanism: []*pkcs11.Mechanism{
-			pkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_KEY_PAIR_GEN, nil),
-		},
-		publicAttrs: []*pkcs11.Attribute{
-			pkcs11.NewAttribute(pkcs11.CKA_ID, keyID),
-			pkcs11.NewAttribute(pkcs11.CKA_LABEL, label),
-			pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
-			// Allow the key to verify signatures
-			pkcs11.NewAttribute(pkcs11.CKA_VERIFY, true),
-			// Set requested modulus length
-			pkcs11.NewAttribute(pkcs11.CKA_MODULUS_BITS, modulusLen),
-			// Set requested public exponent
-			pkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, expSlice),
-		},
-		privateAttrs: []*pkcs11.Attribute{
-			pkcs11.NewAttribute(pkcs11.CKA_ID, keyID),
-			pkcs11.NewAttribute(pkcs11.CKA_LABEL, label),
-			pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
-			// Prevent attributes being retrieved
-			pkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, true),
-			// Prevent the key being extracted from the device
-			pkcs11.NewAttribute(pkcs11.CKA_EXTRACTABLE, false),
-			// Allow the key to create signatures
-			pkcs11.NewAttribute(pkcs11.CKA_SIGN, true),
-		},
+	return []*pkcs11.Attribute{
+		// Set requested modulus length
+		pkcs11.NewAttribute(pkcs11.CKA_MODULUS_BITS, g.modulusLen),
+		// Set requested public exponent
+		pkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, expSlice),
 	}
 }
 
-// rsaPub extracts the generated public key, specified by the provided object
+// publicKey extracts the generated public key, specified by the provided object
 // handle, and constructs a rsa.PublicKey. It also checks that the key has the
 // correct length modulus and that the public exponent is what was requested in
 // the public key template.
-func rsaPub(session *pkcs11helpers.Session, object pkcs11.ObjectHandle, modulusLen int) (*rsa.PublicKey, error) {
+func (g rsaKeyGen) publicKey(session *pkcs11helpers.Session, object pkcs11.ObjectHandle) (crypto.PublicKey, error) {
 	pubKey, err := session.GetRSAPublicKey(object)
 	if err != nil {
 		return nil, err
@@ -64,36 +57,10 @@
 	if pubKey.E != rsaExp {
 		return nil, errors.New("returned CKA_PUBLIC_EXPONENT doesn't match expected exponent")
 	}
-	if pubKey.N.BitLen() != modulusLen {
+	if pubKey.N.BitLen() != g.modulusLen {
 		return nil, errors.New("returned CKA_MODULUS isn't of the expected bit length")
 	}
 	log.Printf("\tPublic exponent: %d\n", pubKey.E)
 	log.Printf("\tModulus: (%d bits) %X\n", pubKey.N.BitLen(), pubKey.N.Bytes())
 	return pubKey, nil
 }
-
-// rsaGenerate is used to generate and verify a RSA key pair of the size
-// specified by modulusLen and with the exponent 65537.
-// It returns the public part of the generated key pair as a rsa.PublicKey
-// and the random key ID that the HSM uses to identify the key pair.
-func rsaGenerate(session *pkcs11helpers.Session, label string, modulusLen int) (*rsa.PublicKey, []byte, error) {
-	keyID := make([]byte, 4)
-	_, err := newRandReader(session).Read(keyID)
-	if err != nil {
-		return nil, nil, err
-	}
-	log.Printf("Generating RSA key with %d bit modulus and public exponent %d and ID %x\n", modulusLen, rsaExp, keyID)
-	args := rsaArgs(label, modulusLen, keyID)
-	pub, _, err := session.GenerateKeyPair(args.mechanism, args.publicAttrs, args.privateAttrs)
-	if err != nil {
-		return nil, nil, err
-	}
-	log.Println("Key generated")
-	log.Println("Extracting public key")
-	pk, err := rsaPub(session, pub, modulusLen)
-	if err != nil {
-		return nil, nil, err
-	}
-	log.Println("Extracted public key")
-	return pk, keyID, nil
-}
diff --git a/cmd/ceremony/rsa_test.go b/cmd/ceremony/rsa_test.go
index 40eb9d5..0a0ade1 100644
--- a/cmd/ceremony/rsa_test.go
+++ b/cmd/ceremony/rsa_test.go
@@ -14,7 +14,7 @@
 	"github.com/letsencrypt/boulder/test"
 )
 
-func TestRSAPub(t *testing.T) {
+func TestRSAPublicKey(t *testing.T) {
 	s, ctx := pkcs11helpers.NewSessionWithMock()
 
 	// test we fail to construct key with non-matching modulus
@@ -24,8 +24,8 @@
 			pkcs11.NewAttribute(pkcs11.CKA_MODULUS, []byte{255}),
 		}, nil
 	}
-	_, err := rsaPub(s, 0, 16)
-	test.AssertError(t, err, "rsaPub didn't fail with non-matching modulus size")
+	_, err := rsaKeyGen{modulusLen: 16}.publicKey(s, 0)
+	test.AssertError(t, err, "publicKey didn't fail with non-matching modulus size")
 
 	// test we don't fail with the correct attributes
 	ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
@@ -34,8 +34,8 @@
 			pkcs11.NewAttribute(pkcs11.CKA_MODULUS, []byte{255}),
 		}, nil
 	}
-	_, err = rsaPub(s, 0, 8)
-	test.AssertNotError(t, err, "rsaPub failed with valid attributes")
+	_, err = rsaKeyGen{modulusLen: 8}.publicKey(s, 0)
+	test.AssertNotError(t, err, "publicKey failed with valid attributes")
 }
 
 func TestRSAGenerate(t *testing.T) {
@@ -47,24 +47,24 @@
 	priv, err := rsa.GenerateKey(rand.Reader, 1024)
 	test.AssertNotError(t, err, "Failed to generate a RSA test key")
 
-	// Test rsaGenerate fails when GenerateKeyPair fails
+	// Test generateKeyPair fails when GenerateKeyPair fails
 	ctx.GenerateKeyPairFunc = func(pkcs11.SessionHandle, []*pkcs11.Mechanism, []*pkcs11.Attribute, []*pkcs11.Attribute) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) {
 		return 0, 0, errors.New("bad")
 	}
-	_, _, err = rsaGenerate(s, "", 1024)
-	test.AssertError(t, err, "rsaGenerate didn't fail on GenerateKeyPair error")
+	_, _, err = generateKeyPair(s, "", newRSAKeyGen(1024))
+	test.AssertError(t, err, "generateKeyPair didn't fail on GenerateKeyPair error")
 
-	// Test rsaGenerate fails when rsaPub fails
+	// Test generateKeyPair fails when publicKey fails
 	ctx.GenerateKeyPairFunc = func(pkcs11.SessionHandle, []*pkcs11.Mechanism, []*pkcs11.Attribute, []*pkcs11.Attribute) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) {
 		return 0, 0, nil
 	}
 	ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
 		return nil, errors.New("bad")
 	}
-	_, _, err = rsaGenerate(s, "", 1024)
-	test.AssertError(t, err, "rsaGenerate didn't fail on rsaPub error")
+	_, _, err = generateKeyPair(s, "", newRSAKeyGen(1024))
+	test.AssertError(t, err, "generateKeyPair didn't fail on publicKey error")
 
-	// Test rsaGenerate fails when rsaVerify fails
+	// Test generateKeyPair fails when rsaVerify fails
 	ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
 		return []*pkcs11.Attribute{
 			pkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, big.NewInt(int64(priv.E)).Bytes()),
@@ -74,10 +74,10 @@
 	ctx.GenerateRandomFunc = func(pkcs11.SessionHandle, int) ([]byte, error) {
 		return nil, errors.New("yup")
 	}
-	_, _, err = rsaGenerate(s, "", 1024)
-	test.AssertError(t, err, "rsaGenerate didn't fail on rsaVerify error")
+	_, _, err = generateKeyPair(s, "", newRSAKeyGen(1024))
+	test.AssertError(t, err, "generateKeyPair didn't fail on rsaVerify error")
 
-	// Test rsaGenerate doesn't fail when everything works
+	// Test generateKeyPair doesn't fail when everything works
 	ctx.SignInitFunc = func(pkcs11.SessionHandle, []*pkcs11.Mechanism, pkcs11.ObjectHandle) error {
 		return nil
 	}
@@ -88,6 +88,6 @@
 		// Chop of the hash identifier and feed back into rsa.SignPKCS1v15
 		return rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA256, msg[19:])
 	}
-	_, _, err = rsaGenerate(s, "", 1024)
-	test.AssertNotError(t, err, "rsaGenerate didn't succeed when everything worked as expected")
+	_, _, err = generateKeyPair(s, "", newRSAKeyGen(1024))
+	test.AssertNotError(t, err, "generateKeyPair didn't succeed when everything worked as expected")
 }