Browse Source

crypto/openpgp: make it possible to set the key length

Fixes golang/go#6693.

Change-Id: I7322e107bd5f7ad07062dcaadeaa3e85a101015a
Reviewed-on: https://go-review.googlesource.com/12473
Reviewed-by: Adam Langley <agl@golang.org>
Run-TryBot: Adam Langley <agl@golang.org>
Jeff R. Allen 10 years ago
parent
commit
56474dfd62
3 changed files with 35 additions and 2 deletions
  1. 7 2
      openpgp/keys.go
  2. 3 0
      openpgp/packet/config.go
  3. 25 0
      openpgp/write_test.go

+ 7 - 2
openpgp/keys.go

@@ -464,15 +464,20 @@ const defaultRSAKeyBits = 2048
 func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) {
 	currentTime := config.Now()
 
+	bits := defaultRSAKeyBits
+	if config != nil && config.RSABits != 0 {
+		bits = config.RSABits
+	}
+
 	uid := packet.NewUserId(name, comment, email)
 	if uid == nil {
 		return nil, errors.InvalidArgumentError("user id field contained invalid characters")
 	}
-	signingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits)
+	signingPriv, err := rsa.GenerateKey(config.Random(), bits)
 	if err != nil {
 		return nil, err
 	}
-	encryptingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits)
+	encryptingPriv, err := rsa.GenerateKey(config.Random(), bits)
 	if err != nil {
 		return nil, err
 	}

+ 3 - 0
openpgp/packet/config.go

@@ -43,6 +43,9 @@ type Config struct {
 	// use a value that is at least 65536. See RFC 4880 Section
 	// 3.7.1.3.
 	S2KCount int
+	// RSABits is the number of bits in new RSA keys made with NewEntity.
+	// If zero, then 2048 bit keys are created.
+	RSABits int
 }
 
 func (c *Config) Random() io.Reader {

+ 25 - 0
openpgp/write_test.go

@@ -10,6 +10,8 @@ import (
 	"io/ioutil"
 	"testing"
 	"time"
+
+	"golang.org/x/crypto/openpgp/packet"
 )
 
 func TestSignDetached(t *testing.T) {
@@ -53,11 +55,34 @@ func TestNewEntity(t *testing.T) {
 		return
 	}
 
+	// Check bit-length with no config.
 	e, err := NewEntity("Test User", "test", "test@example.com", nil)
 	if err != nil {
 		t.Errorf("failed to create entity: %s", err)
 		return
 	}
+	bl, err := e.PrimaryKey.BitLength()
+	if err != nil {
+		t.Errorf("failed to find bit length: %s", err)
+	}
+	if int(bl) != defaultRSAKeyBits {
+		t.Errorf("BitLength %v, expected %v", defaultRSAKeyBits)
+	}
+
+	// Check bit-length with a config.
+	cfg := &packet.Config{RSABits: 1024}
+	e, err = NewEntity("Test User", "test", "test@example.com", cfg)
+	if err != nil {
+		t.Errorf("failed to create entity: %s", err)
+		return
+	}
+	bl, err = e.PrimaryKey.BitLength()
+	if err != nil {
+		t.Errorf("failed to find bit length: %s", err)
+	}
+	if int(bl) != cfg.RSABits {
+		t.Errorf("BitLength %v, expected %v", bl, cfg.RSABits)
+	}
 
 	w := bytes.NewBuffer(nil)
 	if err := e.SerializePrivate(w, nil); err != nil {