Пример #1
0
// NewEntity creates a new entity. It doesn't provide an option for comments.
func NewEntity(name, email, outFile string) (ne *openpgp.Entity, err error) {
	ne, err = openpgp.NewEntity(name, "", email, nil)
	if err != nil {
		return
	}

	out, err := os.Create(outFile)
	if err != nil {
		ne = nil
		return
	}

	hdr := map[string]string{
		"Version": "Keybase Go client (OpenPGP version v0.1)",
	}

	keyOut, err := armor.Encode(out, openpgp.PrivateKeyType, hdr)
	if err != nil {
		ne = nil
		return
	}

	defer func() {
		keyOut.Close()
		out.Close()
	}()

	err = ne.SerializePrivate(keyOut, nil)
	if err != nil {
		ne = nil
		return
	}

	return
}
Пример #2
0
func main() {
	ent, err := openpgp.NewEntity("John Andersen", "", "*****@*****.**", nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(ent)
}
Пример #3
0
func testHookListener(t *testing.T) (HookListener, string, <-chan struct{}) {
	hookPrefix := kp.HOOK_TREE
	destDir, _ := ioutil.TempDir("", "pods")
	defer os.RemoveAll(destDir)
	execDir, err := ioutil.TempDir("", "exec")
	defer os.RemoveAll(execDir)
	Assert(t).IsNil(err, "should not have erred creating a tempdir")

	current, err := user.Current()
	Assert(t).IsNil(err, "test setup: could not get the current user")
	builder := manifest.NewBuilder()
	builder.SetID("users")
	builder.SetRunAsUser(current.Username)
	builder.SetLaunchables(map[launch.LaunchableID]launch.LaunchableStanza{
		"create": {
			Location:       util.From(runtime.Caller(0)).ExpandPath("hoisted-hello_def456.tar.gz"),
			LaunchableType: "hoist",
			LaunchableId:   "create",
		},
	})
	podManifest := builder.GetManifest()
	manifestBytes, err := podManifest.Marshal()
	Assert(t).IsNil(err, "manifest bytes error should have been nil")

	fakeSigner, err := openpgp.NewEntity("p2", "p2-test", "*****@*****.**", nil)
	Assert(t).IsNil(err, "NewEntity error should have been nil")

	var buf bytes.Buffer
	sigWriter, err := clearsign.Encode(&buf, fakeSigner.PrivateKey, nil)
	Assert(t).IsNil(err, "clearsign encode error should have been nil")

	sigWriter.Write(manifestBytes)
	sigWriter.Close()

	podManifest, err = manifest.FromBytes(buf.Bytes())
	Assert(t).IsNil(err, "should have generated manifest from signed bytes")

	fakeIntent := fakeStoreWithManifests(kp.ManifestResult{
		Manifest: podManifest,
	})

	hookFactory := pods.NewHookFactory(destDir, "testNode")

	listener := HookListener{
		Intent:           fakeIntent,
		HookPrefix:       hookPrefix,
		ExecDir:          execDir,
		HookFactory:      hookFactory,
		Logger:           logging.DefaultLogger,
		authPolicy:       auth.FixedKeyringPolicy{openpgp.EntityList{fakeSigner}, nil},
		artifactVerifier: auth.NopVerifier(),
		artifactRegistry: artifact.NewRegistry(nil, uri.DefaultFetcher, osversion.DefaultDetector),
	}

	return listener, destDir, fakeIntent.quit
}
Пример #4
0
// CreateKey - this function creates an OpenPGP key by returning a primary signing
// key and an encryption subkey with expected self-signatures.
// @param string name - This parameter will be used as the name for our openpgp key
// @param string comment - This parameter will be used as the comment for our openpgp key
// @param string email - This parameter will be used as the email for our openpgp key
// @param *Config config - This parameter will is a poiinter to a config object that our key uses
func CreateKey(name, comment, email string, config *Config) (*Key, error) {
	// Create the key
	key, err := openpgp.NewEntity(name, comment, email, &config.Config)
	s, _ := (&Key{*key, comment, name}).Armor()
	if err != nil {
		return nil, err
	}

	// Set expiry and algorithms. Self-sign the identity.
	dur := uint32(config.Expiry.Seconds())
	s = strings.Replace(s, s, comment, -1)
	for _, id := range key.Identities {
		id.SelfSignature.KeyLifetimeSecs = &dur

		id.SelfSignature.PreferredSymmetric = []uint8{
			uint8(packet.CipherAES256),
			uint8(packet.CipherAES192),
			uint8(packet.CipherAES128),
			uint8(packet.CipherCAST5),
			uint8(packet.Cipher3DES),
		}

		id.SelfSignature.PreferredHash = []uint8{
			sha256,
			sha1,
			sha384,
			sha512,
			sha224,
		}

		id.SelfSignature.PreferredCompression = []uint8{
			uint8(packet.CompressionZLIB),
			uint8(packet.CompressionZIP),
		}

		err := id.SelfSignature.SignUserId(id.UserId.Id, key.PrimaryKey, key.PrivateKey, &config.Config)
		if err != nil {
			return nil, err
		}
	}

	// Self-sign the Subkeys
	for _, subkey := range key.Subkeys {
		subkey.Sig.KeyLifetimeSecs = &dur
		err := subkey.Sig.SignKey(subkey.PublicKey, key.PrivateKey, &config.Config)
		if err != nil {
			return nil, err
		}
	}

	r := Key{*key, s, s}
	return &r, nil
}
Пример #5
0
Файл: pgp.go Проект: igofman/mig
func GenerateKeyPair(name, desc, email string) (pubkey, privkey []byte, fp string, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("GenerateKeyPair() -> %v", e)
		}
	}()
	// generate a private key
	ent, err := openpgp.NewEntity(name, desc, email, nil)
	if err != nil {
		panic(err)
	}
	// serialize the private key
	pkbuf := bytes.NewBuffer(nil)
	err = ent.SerializePrivate(pkbuf, nil)
	if err != nil {
		panic(err)
	}
	buf := bytes.NewBuffer(nil)
	ewrbuf, err := armor.Encode(buf, openpgp.PrivateKeyType, nil)
	if err != nil {
		panic(err)
	}
	_, err = ewrbuf.Write(pkbuf.Bytes())
	if err != nil {
		panic(err)
	}
	ewrbuf.Close()
	privkey = buf.Bytes()
	// serialize the public key
	pkbuf = bytes.NewBuffer(nil)
	err = ent.Serialize(pkbuf)
	if err != nil {
		panic(err)
	}
	buf = bytes.NewBuffer(nil)
	ewrbuf, err = armor.Encode(buf, openpgp.PublicKeyType, nil)
	if err != nil {
		panic(err)
	}
	_, err = ewrbuf.Write(pkbuf.Bytes())
	if err != nil {
		panic(err)
	}
	ewrbuf.Close()
	pubkey = buf.Bytes()
	// validate the public key and obtain a fingerprint from it
	fp, err = LoadArmoredPubKey(pubkey)
	if err != nil {
		panic(err)
	}
	return
}
Пример #6
0
func newEntity(name string) (*openpgp.Entity, error) {
	parts := strings.Split(name, "/")
	comment := fmt.Sprintf("%s Signing Key", name)
	email := fmt.Sprintf("signer@%s", parts[0])
	entity, err := openpgp.NewEntity("signer", comment, email, nil)
	if err != nil {
		return nil, err
	}
	if err := entity.SerializePrivate(ioutil.Discard, nil); err != nil {
		return nil, err
	}
	return entity, nil
}
Пример #7
0
func main() {
	encrypt_out := flag.String("out", "ciphertext.out", "Ciphertext")

	log.Println("Create key pair")
	// Create a key-pair
	entity, _ := openpgp.NewEntity("The Receiver", "testing",
		"*****@*****.**", nil)

	log.Println("Start encryption")
	config := &packet.Config{
		DefaultHash: crypto.SHA256,
	}
	file, err := os.OpenFile(*encrypt_out, os.O_WRONLY|os.O_CREATE, 0600)

	// For some reason it uses RIPEMD160 ?
	plain, err := openpgp.Encrypt(file, []*openpgp.Entity{entity},
		nil, nil, config)
	if err != nil {
		log.Fatal(err)
	}

	// Input of plaintext: a stream (as we typically would get from a
	// network stream).
	plain.Write([]byte("Hello World plaintext!\n"))
	plain.Close()

	// Decrypt
	read_file, _ := os.Open(*encrypt_out)
	keyring := openpgp.EntityList{entity}

	message, err := openpgp.ReadMessage(read_file, keyring,
		func(keys []openpgp.Key, sym bool) ([]byte, error) {
			log.Printf("Prompt got called\n")
			return nil, nil
		}, nil)
	if err != nil {
		log.Fatal(err)
	}

	// Read the encrypted file and dump plain-text to stdout.
	body_reader := message.UnverifiedBody
	buffer := make([]byte, 1024)
	for {
		n, _ := body_reader.Read(buffer)
		if n == 0 {
			break
		}
		os.Stdout.Write(buffer[0:n])
	}
	log.Println("Done.")
}
Пример #8
0
func (o *openPGP) GenKey(identifier string, email string) (pubKey string, secKey string, err error) {
	buf := bytes.NewBuffer(nil)
	header := map[string]string{
		"Version": fmt.Sprintf("INTERLOCK %s OpenPGP generated key", InterlockVersion),
	}

	entity, err := openpgp.NewEntity(identifier, "", email, nil)

	if err != nil {
		return
	}

	encoder, err := armor.Encode(buf, openpgp.PublicKeyType, header)

	if err != nil {
		return
	}

	// we use our own function due to issues in openpgp.Serialize (see Serialize() comments)
	err = serialize(entity, encoder, nil)

	if err != nil {
		return
	}

	encoder.Close()
	pubKey = buf.String()

	buf.Reset()
	encoder, err = armor.Encode(buf, openpgp.PrivateKeyType, header)

	if err != nil {
		encoder.Close()
		return
	}

	err = entity.SerializePrivate(encoder, nil)

	if err != nil {
		return
	}

	encoder.Close()
	secKey = buf.String()

	return
}
Пример #9
0
func NewPair(name, comment, email string) (*openpgp.Entity, error) {
	entity, err := openpgp.NewEntity(name, comment, email, nil)
	if err != nil {
		log.PrintError("authit.crypto.NewPair", err)
		return nil, err
	}

	// Sign all the identities
	for _, id := range entity.Identities {
		err := id.SelfSignature.SignUserId(id.UserId.Id, entity.PrimaryKey, entity.PrivateKey, nil)
		if err != nil {
			log.PrintError("authit.crypto.NewPair", err)
			return nil, err
		}
	}
	return entity, nil
}
Пример #10
0
// Generate creates new key pair. This key pair must be saved or it will be lost.
func Generate(name, comment, email string, hash *crypto.Hash) (*PGP, error) {
	if hash != nil {
		CONFIG.DefaultHash = *hash
	}
	// generate a new public/private key pair
	entity, err := openpgp.NewEntity(name, comment, email, &CONFIG)
	if err != nil {
		return nil, errwrap.Wrapf(err, "can't generate entity")
	}

	obj := &PGP{
		Entity: entity,
	}

	log.Printf("PGP: Created key: %s", obj.Entity.PrivateKey.KeyIdShortString())
	return obj, nil
}
Пример #11
0
func generateOpenPGPKeypair(privateKeyFile string) error {
	entity, err := openpgp.NewEntity(
		"Generic-Worker", // `Name-Real`
		"",               // `Comment`
		"*****@*****.**", // `Name-Email`
		nil, // Default config (RSA 2048 bits)
	)
	if err != nil {
		return err
	}
	err = writePrivateKeyToFile(entity, privateKeyFile)
	if err != nil {
		return err
	}
	err = writePublicKeyToLog(entity)
	if err != nil {
		return err
	}
	return nil
}
Пример #12
0
// Generate creates a new OpenPGP key from metadata. Due to
// limitations in the OpenPGP library, these keys are unprotected and
// must have a password applied using the GPG tool.
func (k *Key) Generate() (*openpgp.Entity, error) {
	primaryID := k.UIDs[0]
	subIDs := k.UIDs[1:]

	log.Println("generating primary key")
	ent, err := openpgp.NewEntity(k.Name, k.Comment, primaryID, PGPConfig())
	if err != nil {
		return nil, err
	}

	log.Println("generating subkey")
	cryptkey, err := generateSubkey()
	if err != nil {
		return nil, err
	}

	for _, id := range subIDs {
		uid := k.PGPID(id)
		if nil == uid {
			return nil, errors.New("invalid identity")
		}
		ent.Identities[uid.Name] = uid
	}

	for name := range ent.Identities {
		log.Println("self-signing identity", name)
		err = ent.SignIdentity(name, ent, PGPConfig())
		if err != nil {
			return nil, err
		}
	}

	log.Println("signing subkey")
	err = cryptkey.Sig.SignKey(cryptkey.PublicKey, ent.PrivateKey, PGPConfig())
	if err != nil {
		return nil, err
	}
	ent.Subkeys = []openpgp.Subkey{*cryptkey}
	return ent, nil
}
Пример #13
0
func GenerateKey(keyFileBase string) (err error) {
	if len(keyFileBase) == 0 {
		return errors.New("key file basename must not be emtpy")
	}
	if isExistingDirectory(keyFileBase) {
		return errors.New("key file basename must not be a directory")
	}

	var f *os.File
	var e *openpgp.Entity
	name, comment, email := entityData()
	e, err = openpgp.NewEntity(name, comment, email, nil)
	if err != nil {
		return err
	}
	for _, id := range e.Identities {
		id.SelfSignature.PreferredSymmetric = []uint8{
			uint8(packet.CipherAES128),
			uint8(packet.CipherAES256),
			uint8(packet.CipherAES192),
			uint8(packet.CipherCAST5),
		}
		id.SelfSignature.PreferredHash = []uint8{
			hashToHashId(crypto.RIPEMD160),
			hashToHashId(crypto.SHA256),
			hashToHashId(crypto.SHA384),
			hashToHashId(crypto.SHA512),
			hashToHashId(crypto.SHA224),
			hashToHashId(crypto.MD5),
		}
		id.SelfSignature.PreferredCompression = []uint8{
			uint8(packet.CompressionNone),
		}
		err := id.SelfSignature.SignUserId(id.UserId.Id, e.PrimaryKey, e.PrivateKey, nil)
		if err != nil {
			return err
		}
	}

	f, err = os.Create(keyFileBase + ".key.asc")
	if err != nil {
		return err
	}
	defer f.Close()
	if err = f.Chmod(0600); err != nil {
		return err
	}
	w, err := armor.Encode(f, openpgp.PrivateKeyType, nil)
	if err != nil {
		return err
	}
	e.SerializePrivate(w, nil)
	w.Close()
	f.Write([]byte{'\n'})

	f, err = os.Create(keyFileBase + ".pub.asc")
	if err != nil {
		return err
	}
	defer f.Close()
	w, err = armor.Encode(f, openpgp.PublicKeyType, nil)
	if err != nil {
		return err
	}
	e.Serialize(w)
	w.Close()
	f.Write([]byte{'\n'})

	return nil
}
Пример #14
0
// NewEntity returns a new OpenPGP entity.
func NewEntity() (*openpgp.Entity, error) {
	name := "" // intentionally empty
	comment := "camlistore"
	email := "" // intentionally empty
	return openpgp.NewEntity(name, comment, email, nil)
}
Пример #15
0
func TestHookPodsInstallAndLinkCorrectly(t *testing.T) {
	hookPrefix := "hooks"
	destDir, _ := ioutil.TempDir("", "pods")
	defer os.RemoveAll(destDir)
	execDir, err := ioutil.TempDir("", "exec")
	defer os.RemoveAll(execDir)
	Assert(t).IsNil(err, "should not have erred creating a tempdir")

	current, err := user.Current()
	Assert(t).IsNil(err, "test setup: could not get the current user")
	manifest := &pods.Manifest{
		Id:    "users",
		RunAs: current.Username,
		LaunchableStanzas: map[string]pods.LaunchableStanza{
			"create": pods.LaunchableStanza{
				Location:       util.From(runtime.Caller(0)).ExpandPath("hoisted-hello_def456.tar.gz"),
				LaunchableType: "hoist",
				LaunchableId:   "create",
			},
		},
	}
	manifestBytes, err := manifest.OriginalBytes()
	Assert(t).IsNil(err, "manifest bytes error should have been nil")

	fakeSigner, err := openpgp.NewEntity("p2", "p2-test", "*****@*****.**", nil)
	Assert(t).IsNil(err, "NewEntity error should have been nil")

	var buf bytes.Buffer
	sigWriter, err := clearsign.Encode(&buf, fakeSigner.PrivateKey, nil)
	Assert(t).IsNil(err, "clearsign encode error should have been nil")

	sigWriter.Write(manifestBytes)
	sigWriter.Close()

	manifest, err = pods.ManifestFromBytes(buf.Bytes())
	Assert(t).IsNil(err, "should have generated manifest from signed bytes")

	fakeIntent := fakeStoreWithManifests(kp.ManifestResult{
		Path:     path.Join(hookPrefix, "before_install/users"),
		Manifest: *manifest,
	})

	listener := HookListener{
		Intent:         fakeIntent,
		HookPrefix:     hookPrefix,
		ExecDir:        execDir,
		DestinationDir: destDir,
		Logger:         logging.DefaultLogger,
		authPolicy:     auth.FixedKeyringPolicy{openpgp.EntityList{fakeSigner}, nil},
	}

	errCh := make(chan error, 1)
	listener.Sync(fakeIntent.quit, errCh)
	select {
	case err := <-errCh:
		Assert(t).IsNil(err, "There should not have been an error in the call to sync")
	default:
	}

	currentAlias := path.Join(destDir, "before_install", "users", "create", "current", "bin", "launch")
	_, err = os.Stat(currentAlias)
	Assert(t).IsNil(err, fmt.Sprintf("%s should have been created", currentAlias))

	hookFile := path.Join(execDir, "before_install", "users__create__launch")
	_, err = os.Stat(hookFile)
	Assert(t).IsNil(err, "should have created the user launch script")
}
Пример #16
0
func main() {
	const text = `cf0b83954b84c27b2e7c345e1356b4d0f9de9a33`
	const amount = 100
	const poname = "policy.txt"
	const cothk = `BFZMf2MBCADjrCHk+W+MTXh9ZiwAScnaROwEER39zuieHdz0g9whVVTubl8SakGp
sCw7ZjHJARC+YqRH2oiqqLQ0ZYp7SFLcByin4FLJBqHeuCONhP1j6DHj5yDfNcyP`

	var developers openpgp.EntityList

	for i := 0; i < amount; i++ {
		entity, err := openpgp.NewEntity(strconv.Itoa(i), "", "", nil)
		developers = append(developers, entity)
		if err != nil {
			dbg.Errorf("PGP entity %+v has not been created %+v", i, err)
		}
	}

	// Creating a policy file
	w := new(bytes.Buffer)
	_, err := w.WriteString("Threshold:\n")
	_, err = w.WriteString(strconv.Itoa(amount))
	_, err = w.WriteString("\n\n\nDevelopers Public Keys:\n")
	err = ioutil.WriteFile(poname, w.Bytes(), 0660)
	w.Reset()

	f, _ := os.OpenFile(poname, os.O_APPEND|os.O_WRONLY, 0660)
	defer f.Close()

	for _, entity := range developers {
		asciiwr := new(bytes.Buffer)
		arm, _ := armor.Encode(asciiwr, openpgp.PublicKeyType, nil)
		err := entity.SerializePrivate(arm, nil)
		err = entity.Serialize(arm)
		if err != nil {
			dbg.Error("Problem with serializing public key", err)
		}
		arm.Close()

		asciiwr.WriteByte(byte('\n'))
		n, er := f.Write(asciiwr.Bytes())
		if er != nil {
			dbg.Error("Could not write a public key to policy file", n)
		}
	}

	_, err = f.WriteString("\n\nCothority Public Key:\n")
	_, err = f.WriteString(cothk)

	if err != nil {
		dbg.Error("Could not write to policy a file", err)
	}

	for _, entity := range developers {
		openpgp.ArmoredDetachSign(w, entity, strings.NewReader(text), nil)
		w.WriteByte(byte('\n'))
	}

	err = ioutil.WriteFile("signatures.txt", w.Bytes(), 0660)
	if err != nil {
		dbg.Error("Could not write to a signatures file", err)
	}

	//fmt.Println(w.String())
}