Beispiel #1
0
// GenerateNewSecRing creates a new secret ring file secRing, with
// a new GPG identity. It returns the public keyId of that identity.
// It returns an error if the file already exists.
func GenerateNewSecRing(secRing string) (keyId string, err error) {
	ent, err := NewEntity()
	if err != nil {
		return "", fmt.Errorf("generating new identity: %v", err)
	}
	if err := os.MkdirAll(filepath.Dir(secRing), 0700); err != nil {
		return "", err
	}
	f, err := wkfs.OpenFile(secRing, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
	if err != nil {
		return "", err
	}
	err = WriteKeyRing(f, openpgp.EntityList([]*openpgp.Entity{ent}))
	if err != nil {
		f.Close()
		return "", fmt.Errorf("Could not write new key ring to %s: %v", secRing, err)
	}
	if err := f.Close(); err != nil {
		return "", fmt.Errorf("Could not close %v: %v", secRing, err)
	}
	return ent.PrimaryKey.KeyIdShortString(), nil
}
func TestWriteKeyRing(t *testing.T) {
	ent, err := EntityFromSecring("26F5ABDA", "testdata/test-secring.gpg")
	if err != nil {
		t.Fatalf("NewEntity: %v", err)
	}
	var buf bytes.Buffer
	err = WriteKeyRing(&buf, openpgp.EntityList([]*openpgp.Entity{ent}))
	if err != nil {
		t.Fatalf("WriteKeyRing: %v", err)
	}

	el, err := openpgp.ReadKeyRing(&buf)
	if err != nil {
		t.Fatalf("ReadKeyRing: %v", err)
	}
	if len(el) != 1 {
		t.Fatalf("ReadKeyRing read %d entities; want 1", len(el))
	}
	orig := entityString(ent)
	got := entityString(el[0])
	if orig != got {
		t.Fatalf("original vs. wrote-then-read entities differ:\norig: %s\n got: %s", orig, got)
	}
}