Add ToPublic method to get a public key object from a private key (#65)

This commit is contained in:
wussler 2020-07-22 17:13:23 +02:00 committed by GitHub
parent 48f05401ce
commit 979fdb3f4b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 36 additions and 0 deletions

View file

@ -32,6 +32,11 @@ EncryptBinaryMessageArmored(key string, data []byte) (string, error)
DecryptBinaryMessageArmored(privateKey string, passphrase []byte, ciphertext string) ([]byte, error) DecryptBinaryMessageArmored(privateKey string, passphrase []byte, ciphertext string) ([]byte, error)
``` ```
- Method to derive a public key object from a private key
```go
(key *Key) ToPublic() (publicKey *Key, err error)
```
### Changed ### Changed
- Improved key and message armoring testing - Improved key and message armoring testing
- `EncryptSessionKey` now creates encrypted key packets for each valid encryption key in the provided keyring. - `EncryptSessionKey` now creates encrypted key packets for each valid encryption key in the provided keyring.

View file

@ -359,6 +359,21 @@ func (key *Key) GetEntity() *openpgp.Entity {
return key.entity return key.entity
} }
// ToPublic returns the corresponding public key of the given private key.
func (key *Key) ToPublic() (publicKey *Key, err error) {
if !key.IsPrivate() {
return nil, errors.New("gopenpgp: key is already public")
}
publicKey, err = key.Copy()
if err != nil {
return nil, err
}
publicKey.ClearPrivateParams()
return
}
// --- Internal methods // --- Internal methods
// getSHA256FingerprintBytes computes the SHA256 fingerprint of a public key // getSHA256FingerprintBytes computes the SHA256 fingerprint of a public key

View file

@ -389,3 +389,19 @@ func TestGetEntity(t *testing.T) {
assert.True(t, entity.PrimaryIdentity().SelfSignature.FlagsValid) assert.True(t, entity.PrimaryIdentity().SelfSignature.FlagsValid)
assert.IsType(t, &openpgp.Entity{}, entity) assert.IsType(t, &openpgp.Entity{}, entity)
} }
func TestToPublic(t *testing.T) {
privateKey, err := NewKeyFromArmored(readTestFile("keyring_privateKey", false))
if err != nil {
t.Fatal("Cannot unarmor key:", err)
}
assert.True(t, privateKey.IsPrivate())
publicKey, err := privateKey.ToPublic()
if err != nil {
t.Fatal("Cannot make key public:", err)
}
assert.False(t, publicKey.IsPrivate())
assert.True(t, privateKey.IsPrivate())
}