mirror of
https://github.com/golang/go
synced 2024-11-21 13:34:39 -07:00
crypto/openpgp: add package
R=bradfitzgo CC=golang-dev https://golang.org/cl/3989052
This commit is contained in:
parent
27ccb41c4a
commit
6ca009f58d
@ -42,6 +42,11 @@ DIRS=\
|
||||
crypto/md4\
|
||||
crypto/md5\
|
||||
crypto/ocsp\
|
||||
crypto/openpgp\
|
||||
crypto/openpgp/armor\
|
||||
crypto/openpgp/error\
|
||||
crypto/openpgp/packet\
|
||||
crypto/openpgp/s2k\
|
||||
crypto/rand\
|
||||
crypto/rc4\
|
||||
crypto/ripemd160\
|
||||
@ -158,6 +163,7 @@ endif
|
||||
|
||||
NOTEST=\
|
||||
crypto\
|
||||
crypto/openpgp/error\
|
||||
debug/proc\
|
||||
exp/draw/x11\
|
||||
go/ast\
|
||||
|
14
src/pkg/crypto/openpgp/Makefile
Normal file
14
src/pkg/crypto/openpgp/Makefile
Normal file
@ -0,0 +1,14 @@
|
||||
# Copyright 2011 The Go Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style
|
||||
# license that can be found in the LICENSE file.
|
||||
|
||||
include ../../../Make.inc
|
||||
|
||||
TARG=crypto/openpgp
|
||||
GOFILES=\
|
||||
canonical_text.go\
|
||||
keys.go\
|
||||
read.go\
|
||||
write.go\
|
||||
|
||||
include ../../../Make.pkg
|
58
src/pkg/crypto/openpgp/canonical_text.go
Normal file
58
src/pkg/crypto/openpgp/canonical_text.go
Normal file
@ -0,0 +1,58 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package openpgp
|
||||
|
||||
import (
|
||||
"hash"
|
||||
"os"
|
||||
)
|
||||
|
||||
// NewCanonicalTextHash reformats text written to it into the canonical
|
||||
// form and then applies the hash h. See RFC 4880, section 5.2.1.
|
||||
func NewCanonicalTextHash(h hash.Hash) hash.Hash {
|
||||
return &canonicalTextHash{h, 0}
|
||||
}
|
||||
|
||||
type canonicalTextHash struct {
|
||||
h hash.Hash
|
||||
s int
|
||||
}
|
||||
|
||||
var newline = []byte{'\r', '\n'}
|
||||
|
||||
func (cth *canonicalTextHash) Write(buf []byte) (int, os.Error) {
|
||||
start := 0
|
||||
|
||||
for i, c := range buf {
|
||||
switch cth.s {
|
||||
case 0:
|
||||
if c == '\r' {
|
||||
cth.s = 1
|
||||
} else if c == '\n' {
|
||||
cth.h.Write(buf[start:i])
|
||||
cth.h.Write(newline)
|
||||
start = i + 1
|
||||
}
|
||||
case 1:
|
||||
cth.s = 0
|
||||
}
|
||||
}
|
||||
|
||||
cth.h.Write(buf[start:])
|
||||
return len(buf), nil
|
||||
}
|
||||
|
||||
func (cth *canonicalTextHash) Sum() []byte {
|
||||
return cth.h.Sum()
|
||||
}
|
||||
|
||||
func (cth *canonicalTextHash) Reset() {
|
||||
cth.h.Reset()
|
||||
cth.s = 0
|
||||
}
|
||||
|
||||
func (cth *canonicalTextHash) Size() int {
|
||||
return cth.h.Size()
|
||||
}
|
50
src/pkg/crypto/openpgp/canonical_text_test.go
Normal file
50
src/pkg/crypto/openpgp/canonical_text_test.go
Normal file
@ -0,0 +1,50 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package openpgp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type recordingHash struct {
|
||||
buf *bytes.Buffer
|
||||
}
|
||||
|
||||
func (r recordingHash) Write(b []byte) (n int, err os.Error) {
|
||||
return r.buf.Write(b)
|
||||
}
|
||||
|
||||
func (r recordingHash) Sum() []byte {
|
||||
return r.buf.Bytes()
|
||||
}
|
||||
|
||||
func (r recordingHash) Reset() {
|
||||
panic("shouldn't be called")
|
||||
}
|
||||
|
||||
func (r recordingHash) Size() int {
|
||||
panic("shouldn't be called")
|
||||
}
|
||||
|
||||
|
||||
func testCanonicalText(t *testing.T, input, expected string) {
|
||||
r := recordingHash{bytes.NewBuffer(nil)}
|
||||
c := NewCanonicalTextHash(r)
|
||||
c.Write([]byte(input))
|
||||
result := c.Sum()
|
||||
if expected != string(result) {
|
||||
t.Errorf("input: %x got: %x want: %x", input, result, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanonicalText(t *testing.T) {
|
||||
testCanonicalText(t, "foo\n", "foo\r\n")
|
||||
testCanonicalText(t, "foo", "foo")
|
||||
testCanonicalText(t, "foo\r\n", "foo\r\n")
|
||||
testCanonicalText(t, "foo\r\nbar", "foo\r\nbar")
|
||||
testCanonicalText(t, "foo\r\nbar\n\n", "foo\r\nbar\r\n\r\n")
|
||||
}
|
280
src/pkg/crypto/openpgp/keys.go
Normal file
280
src/pkg/crypto/openpgp/keys.go
Normal file
@ -0,0 +1,280 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package openpgp
|
||||
|
||||
import (
|
||||
"crypto/openpgp/error"
|
||||
"crypto/openpgp/packet"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// PublicKeyType is the armor type for a PGP public key.
|
||||
var PublicKeyType = "PGP PUBLIC KEY BLOCK"
|
||||
|
||||
// An Entity represents the components of an OpenPGP key: a primary public key
|
||||
// (which must be a signing key), one or more identities claimed by that key,
|
||||
// and zero or more subkeys, which may be encryption keys.
|
||||
type Entity struct {
|
||||
PrimaryKey *packet.PublicKey
|
||||
PrivateKey *packet.PrivateKey
|
||||
Identities map[string]*Identity // indexed by Identity.Name
|
||||
Subkeys []Subkey
|
||||
}
|
||||
|
||||
// An Identity represents an identity claimed by an Entity and zero or more
|
||||
// assertions by other entities about that claim.
|
||||
type Identity struct {
|
||||
Name string // by convention, has the form "Full Name (comment) <email@example.com>"
|
||||
UserId *packet.UserId
|
||||
SelfSignature *packet.Signature
|
||||
Signatures []*packet.Signature
|
||||
}
|
||||
|
||||
// A Subkey is an additional public key in an Entity. Subkeys can be used for
|
||||
// encryption.
|
||||
type Subkey struct {
|
||||
PublicKey *packet.PublicKey
|
||||
PrivateKey *packet.PrivateKey
|
||||
Sig *packet.Signature
|
||||
}
|
||||
|
||||
// A Key identifies a specific public key in an Entity. This is either the
|
||||
// Entity's primary key or a subkey.
|
||||
type Key struct {
|
||||
Entity *Entity
|
||||
PublicKey *packet.PublicKey
|
||||
PrivateKey *packet.PrivateKey
|
||||
SelfSignature *packet.Signature
|
||||
}
|
||||
|
||||
// A KeyRing provides access to public and private keys.
|
||||
type KeyRing interface {
|
||||
// KeysById returns the set of keys that have the given key id.
|
||||
KeysById(id uint64) []Key
|
||||
// DecryptionKeys returns all private keys that are valid for
|
||||
// decryption.
|
||||
DecryptionKeys() []Key
|
||||
}
|
||||
|
||||
// An EntityList contains one or more Entities.
|
||||
type EntityList []*Entity
|
||||
|
||||
// KeysById returns the set of keys that have the given key id.
|
||||
func (el EntityList) KeysById(id uint64) (keys []Key) {
|
||||
for _, e := range el {
|
||||
if e.PrimaryKey.KeyId == id {
|
||||
var selfSig *packet.Signature
|
||||
for _, ident := range e.Identities {
|
||||
if selfSig == nil {
|
||||
selfSig = ident.SelfSignature
|
||||
} else if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId {
|
||||
selfSig = ident.SelfSignature
|
||||
break
|
||||
}
|
||||
}
|
||||
keys = append(keys, Key{e, e.PrimaryKey, e.PrivateKey, selfSig})
|
||||
}
|
||||
|
||||
for _, subKey := range e.Subkeys {
|
||||
if subKey.PublicKey.KeyId == id {
|
||||
keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig})
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// DecryptionKeys returns all private keys that are valid for decryption.
|
||||
func (el EntityList) DecryptionKeys() (keys []Key) {
|
||||
for _, e := range el {
|
||||
for _, subKey := range e.Subkeys {
|
||||
if subKey.PrivateKey != nil && (!subKey.Sig.FlagsValid || subKey.Sig.FlagEncryptStorage || subKey.Sig.FlagEncryptCommunications) {
|
||||
keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig})
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file.
|
||||
func ReadArmoredKeyRing(r io.Reader) (EntityList, os.Error) {
|
||||
body, err := readArmored(r, PublicKeyType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ReadKeyRing(body)
|
||||
}
|
||||
|
||||
// ReadKeyRing reads one or more public/private keys, ignoring unsupported keys.
|
||||
func ReadKeyRing(r io.Reader) (el EntityList, err os.Error) {
|
||||
packets := packet.NewReader(r)
|
||||
|
||||
for {
|
||||
var e *Entity
|
||||
e, err = readEntity(packets)
|
||||
if err != nil {
|
||||
if _, ok := err.(error.UnsupportedError); ok {
|
||||
err = readToNextPublicKey(packets)
|
||||
}
|
||||
if err == os.EOF {
|
||||
err = nil
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
el = nil
|
||||
return
|
||||
}
|
||||
} else {
|
||||
el = append(el, e)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// readToNextPublicKey reads packets until the start of the entity and leaves
|
||||
// the first packet of the new entity in the Reader.
|
||||
func readToNextPublicKey(packets *packet.Reader) (err os.Error) {
|
||||
var p packet.Packet
|
||||
for {
|
||||
p, err = packets.Next()
|
||||
if err == os.EOF {
|
||||
return
|
||||
} else if err != nil {
|
||||
if _, ok := err.(error.UnsupportedError); ok {
|
||||
err = nil
|
||||
continue
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if pk, ok := p.(*packet.PublicKey); ok && !pk.IsSubkey {
|
||||
packets.Unread(p)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
// readEntity reads an entity (public key, identities, subkeys etc) from the
|
||||
// given Reader.
|
||||
func readEntity(packets *packet.Reader) (*Entity, os.Error) {
|
||||
e := new(Entity)
|
||||
e.Identities = make(map[string]*Identity)
|
||||
|
||||
p, err := packets.Next()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var ok bool
|
||||
if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok {
|
||||
if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok {
|
||||
packets.Unread(p)
|
||||
return nil, error.StructuralError("first packet was not a public/private key")
|
||||
} else {
|
||||
e.PrimaryKey = &e.PrivateKey.PublicKey
|
||||
}
|
||||
}
|
||||
|
||||
var current *Identity
|
||||
EachPacket:
|
||||
for {
|
||||
p, err := packets.Next()
|
||||
if err == os.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch pkt := p.(type) {
|
||||
case *packet.UserId:
|
||||
current = new(Identity)
|
||||
current.Name = pkt.Id
|
||||
current.UserId = pkt
|
||||
e.Identities[pkt.Id] = current
|
||||
p, err = packets.Next()
|
||||
if err == os.EOF {
|
||||
err = io.ErrUnexpectedEOF
|
||||
}
|
||||
if err != nil {
|
||||
if _, ok := err.(error.UnsupportedError); ok {
|
||||
return nil, err
|
||||
}
|
||||
return nil, error.StructuralError("identity self-signature invalid: " + err.String())
|
||||
}
|
||||
current.SelfSignature, ok = p.(*packet.Signature)
|
||||
if !ok {
|
||||
return nil, error.StructuralError("user ID packet not followed by self signature")
|
||||
}
|
||||
if current.SelfSignature.SigType != packet.SigTypePositiveCert {
|
||||
return nil, error.StructuralError("user ID self-signature with wrong type")
|
||||
}
|
||||
if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, current.SelfSignature); err != nil {
|
||||
return nil, error.StructuralError("user ID self-signature invalid: " + err.String())
|
||||
}
|
||||
case *packet.Signature:
|
||||
if current == nil {
|
||||
return nil, error.StructuralError("signature packet found before user id packet")
|
||||
}
|
||||
current.Signatures = append(current.Signatures, pkt)
|
||||
case *packet.PrivateKey:
|
||||
if pkt.IsSubkey == false {
|
||||
packets.Unread(p)
|
||||
break EachPacket
|
||||
}
|
||||
err = addSubkey(e, packets, &pkt.PublicKey, pkt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case *packet.PublicKey:
|
||||
if pkt.IsSubkey == false {
|
||||
packets.Unread(p)
|
||||
break EachPacket
|
||||
}
|
||||
err = addSubkey(e, packets, pkt, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
// we ignore unknown packets
|
||||
}
|
||||
}
|
||||
|
||||
if len(e.Identities) == 0 {
|
||||
return nil, error.StructuralError("entity without any identities")
|
||||
}
|
||||
|
||||
return e, nil
|
||||
}
|
||||
|
||||
func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) os.Error {
|
||||
var subKey Subkey
|
||||
subKey.PublicKey = pub
|
||||
subKey.PrivateKey = priv
|
||||
p, err := packets.Next()
|
||||
if err == os.EOF {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
if err != nil {
|
||||
return error.StructuralError("subkey signature invalid: " + err.String())
|
||||
}
|
||||
var ok bool
|
||||
subKey.Sig, ok = p.(*packet.Signature)
|
||||
if !ok {
|
||||
return error.StructuralError("subkey packet not followed by signature")
|
||||
}
|
||||
if subKey.Sig.SigType != packet.SigTypeSubkeyBinding {
|
||||
return error.StructuralError("subkey signature with wrong type")
|
||||
}
|
||||
err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, subKey.Sig)
|
||||
if err != nil {
|
||||
return error.StructuralError("subkey signature invalid: " + err.String())
|
||||
}
|
||||
e.Subkeys = append(e.Subkeys, subKey)
|
||||
return nil
|
||||
}
|
@ -261,13 +261,13 @@ func Read(r io.Reader) (p Packet, err os.Error) {
|
||||
case packetTypePrivateKey, packetTypePrivateSubkey:
|
||||
pk := new(PrivateKey)
|
||||
if tag == packetTypePrivateSubkey {
|
||||
pk.IsSubKey = true
|
||||
pk.IsSubkey = true
|
||||
}
|
||||
p = pk
|
||||
case packetTypePublicKey, packetTypePublicSubkey:
|
||||
pk := new(PublicKey)
|
||||
if tag == packetTypePublicSubkey {
|
||||
pk.IsSubKey = true
|
||||
pk.IsSubkey = true
|
||||
}
|
||||
p = pk
|
||||
case packetTypeCompressed:
|
||||
|
@ -23,7 +23,7 @@ type PublicKey struct {
|
||||
PublicKey interface{} // Either a *rsa.PublicKey or *dsa.PublicKey
|
||||
Fingerprint [20]byte
|
||||
KeyId uint64
|
||||
IsSubKey bool
|
||||
IsSubkey bool
|
||||
|
||||
n, e, p, q, g, y parsedMPI
|
||||
}
|
||||
|
413
src/pkg/crypto/openpgp/read.go
Normal file
413
src/pkg/crypto/openpgp/read.go
Normal file
@ -0,0 +1,413 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// This openpgp package implements high level operations on OpenPGP messages.
|
||||
package openpgp
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/openpgp/armor"
|
||||
"crypto/openpgp/error"
|
||||
"crypto/openpgp/packet"
|
||||
"crypto/rsa"
|
||||
_ "crypto/sha256"
|
||||
"hash"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// SignatureType is the armor type for a PGP signature.
|
||||
var SignatureType = "PGP SIGNATURE"
|
||||
|
||||
// readArmored reads an armored block with the given type.
|
||||
func readArmored(r io.Reader, expectedType string) (body io.Reader, err os.Error) {
|
||||
block, err := armor.Decode(r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if block.Type != expectedType {
|
||||
return nil, error.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type)
|
||||
}
|
||||
|
||||
return block.Body, nil
|
||||
}
|
||||
|
||||
// MessageDetails contains the result of parsing an OpenPGP encrypted and/or
|
||||
// signed message.
|
||||
type MessageDetails struct {
|
||||
IsEncrypted bool // true if the message was encrypted.
|
||||
EncryptedToKeyIds []uint64 // the list of recipient key ids.
|
||||
IsSymmetricallyEncrypted bool // true if a passphrase could have decrypted the message.
|
||||
DecryptedWith Key // the private key used to decrypt the message, if any.
|
||||
IsSigned bool // true if the message is signed.
|
||||
SignedByKeyId uint64 // the key id of the signer, if any.
|
||||
SignedBy *Key // the key of the signer, if availible.
|
||||
LiteralData *packet.LiteralData // the metadata of the contents
|
||||
UnverifiedBody io.Reader // the contents of the message.
|
||||
|
||||
// If IsSigned is true and SignedBy is non-zero then the signature will
|
||||
// be verified as UnverifiedBody is read. The signature cannot be
|
||||
// checked until the whole of UnverifiedBody is read so UnverifiedBody
|
||||
// must be consumed until EOF before the data can trusted. Even if a
|
||||
// message isn't signed (or the signer is unknown) the data may contain
|
||||
// an authentication code that is only checked once UnverifiedBody has
|
||||
// been consumed. Once EOF has been seen, the following fields are
|
||||
// valid. (An authentication code failure is reported as a
|
||||
// SignatureError error when reading from UnverifiedBody.)
|
||||
|
||||
SignatureError os.Error // nil if the signature is good.
|
||||
Signature *packet.Signature // the signature packet itself.
|
||||
|
||||
decrypted io.ReadCloser
|
||||
}
|
||||
|
||||
// A PromptFunction is used as a callback by functions that may need to decrypt
|
||||
// a private key, or prompt for a passphrase. It is called with a list of
|
||||
// acceptable, encrypted private keys and a boolean that indicates whether a
|
||||
// passphrase is usable. It should either decrypt a private key or return a
|
||||
// passphrase to try. If the decrypted private key or given passphrase isn't
|
||||
// correct, the function will be called again, forever. Any error returned will
|
||||
// be passed up.
|
||||
type PromptFunction func(keys []Key, symmetric bool) ([]byte, os.Error)
|
||||
|
||||
// A keyEnvelopePair is used to store a private key with the envelope that
|
||||
// contains a symmetric key, encrypted with that key.
|
||||
type keyEnvelopePair struct {
|
||||
key Key
|
||||
encryptedKey *packet.EncryptedKey
|
||||
}
|
||||
|
||||
// ReadMessage parses an OpenPGP message that may be signed and/or encrypted.
|
||||
// The given KeyRing should contain both public keys (for signature
|
||||
// verification) and, possibly encrypted, private keys for decrypting.
|
||||
func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction) (md *MessageDetails, err os.Error) {
|
||||
var p packet.Packet
|
||||
|
||||
var symKeys []*packet.SymmetricKeyEncrypted
|
||||
var pubKeys []keyEnvelopePair
|
||||
var se *packet.SymmetricallyEncrypted
|
||||
|
||||
packets := packet.NewReader(r)
|
||||
md = new(MessageDetails)
|
||||
md.IsEncrypted = true
|
||||
|
||||
// The message, if encrypted, starts with a number of packets
|
||||
// containing an encrypted decryption key. The decryption key is either
|
||||
// encrypted to a public key, or with a passphrase. This loop
|
||||
// collects these packets.
|
||||
ParsePackets:
|
||||
for {
|
||||
p, err = packets.Next()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch p := p.(type) {
|
||||
case *packet.SymmetricKeyEncrypted:
|
||||
// This packet contains the decryption key encrypted with a passphrase.
|
||||
md.IsSymmetricallyEncrypted = true
|
||||
symKeys = append(symKeys, p)
|
||||
case *packet.EncryptedKey:
|
||||
// This packet contains the decryption key encrypted to a public key.
|
||||
md.EncryptedToKeyIds = append(md.EncryptedToKeyIds, p.KeyId)
|
||||
if p.Algo != packet.PubKeyAlgoRSA && p.Algo != packet.PubKeyAlgoRSAEncryptOnly {
|
||||
continue
|
||||
}
|
||||
var keys []Key
|
||||
if p.KeyId == 0 {
|
||||
keys = keyring.DecryptionKeys()
|
||||
} else {
|
||||
keys = keyring.KeysById(p.KeyId)
|
||||
}
|
||||
for _, k := range keys {
|
||||
pubKeys = append(pubKeys, keyEnvelopePair{k, p})
|
||||
}
|
||||
case *packet.SymmetricallyEncrypted:
|
||||
se = p
|
||||
break ParsePackets
|
||||
case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature:
|
||||
// This message isn't encrypted.
|
||||
if len(symKeys) != 0 || len(pubKeys) != 0 {
|
||||
return nil, error.StructuralError("key material not followed by encrypted message")
|
||||
}
|
||||
packets.Unread(p)
|
||||
return readSignedMessage(packets, nil, keyring)
|
||||
}
|
||||
}
|
||||
|
||||
var candidates []Key
|
||||
var decrypted io.ReadCloser
|
||||
|
||||
// Now that we have the list of encrypted keys we need to decrypt at
|
||||
// least one of them or, if we cannot, we need to call the prompt
|
||||
// function so that it can decrypt a key or give us a passphrase.
|
||||
FindKey:
|
||||
for {
|
||||
// See if any of the keys already have a private key availible
|
||||
candidates = candidates[:0]
|
||||
candidateFingerprints := make(map[string]bool)
|
||||
|
||||
for _, pk := range pubKeys {
|
||||
if pk.key.PrivateKey == nil {
|
||||
continue
|
||||
}
|
||||
if !pk.key.PrivateKey.Encrypted {
|
||||
if len(pk.encryptedKey.Key) == 0 {
|
||||
pk.encryptedKey.DecryptRSA(pk.key.PrivateKey.PrivateKey.(*rsa.PrivateKey))
|
||||
}
|
||||
if len(pk.encryptedKey.Key) == 0 {
|
||||
continue
|
||||
}
|
||||
decrypted, err = se.Decrypt(pk.encryptedKey.CipherFunc, pk.encryptedKey.Key)
|
||||
if err != nil && err != error.KeyIncorrectError {
|
||||
return nil, err
|
||||
}
|
||||
if decrypted != nil {
|
||||
md.DecryptedWith = pk.key
|
||||
break FindKey
|
||||
}
|
||||
} else {
|
||||
fpr := string(pk.key.PublicKey.Fingerprint[:])
|
||||
if v := candidateFingerprints[fpr]; v {
|
||||
continue
|
||||
}
|
||||
candidates = append(candidates, pk.key)
|
||||
candidateFingerprints[fpr] = true
|
||||
}
|
||||
}
|
||||
|
||||
if len(candidates) == 0 && len(symKeys) == 0 {
|
||||
return nil, error.KeyIncorrectError
|
||||
}
|
||||
|
||||
if prompt == nil {
|
||||
return nil, error.KeyIncorrectError
|
||||
}
|
||||
|
||||
passphrase, err := prompt(candidates, len(symKeys) != 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Try the symmetric passphrase first
|
||||
if len(symKeys) != 0 && passphrase != nil {
|
||||
for _, s := range symKeys {
|
||||
err = s.Decrypt(passphrase)
|
||||
if err == nil && !s.Encrypted {
|
||||
decrypted, err = se.Decrypt(s.CipherFunc, s.Key)
|
||||
if err != nil && err != error.KeyIncorrectError {
|
||||
return nil, err
|
||||
}
|
||||
if decrypted != nil {
|
||||
break FindKey
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
md.decrypted = decrypted
|
||||
packets.Push(decrypted)
|
||||
return readSignedMessage(packets, md, keyring)
|
||||
}
|
||||
|
||||
// readSignedMessage reads a possibily signed message if mdin is non-zero then
|
||||
// that structure is updated and returned. Otherwise a fresh MessageDetails is
|
||||
// used.
|
||||
func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing) (md *MessageDetails, err os.Error) {
|
||||
if mdin == nil {
|
||||
mdin = new(MessageDetails)
|
||||
}
|
||||
md = mdin
|
||||
|
||||
var p packet.Packet
|
||||
var h hash.Hash
|
||||
var wrappedHash hash.Hash
|
||||
FindLiteralData:
|
||||
for {
|
||||
p, err = packets.Next()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch p := p.(type) {
|
||||
case *packet.Compressed:
|
||||
packets.Push(p.Body)
|
||||
case *packet.OnePassSignature:
|
||||
if !p.IsLast {
|
||||
return nil, error.UnsupportedError("nested signatures")
|
||||
}
|
||||
|
||||
h, wrappedHash, err = hashForSignature(p.Hash, p.SigType)
|
||||
if err != nil {
|
||||
md = nil
|
||||
return
|
||||
}
|
||||
|
||||
md.IsSigned = true
|
||||
md.SignedByKeyId = p.KeyId
|
||||
keys := keyring.KeysById(p.KeyId)
|
||||
for _, key := range keys {
|
||||
if key.SelfSignature.FlagsValid && !key.SelfSignature.FlagSign {
|
||||
continue
|
||||
}
|
||||
md.SignedBy = &key
|
||||
}
|
||||
case *packet.LiteralData:
|
||||
md.LiteralData = p
|
||||
break FindLiteralData
|
||||
}
|
||||
}
|
||||
|
||||
if md.SignedBy != nil {
|
||||
md.UnverifiedBody = &signatureCheckReader{packets, h, wrappedHash, md}
|
||||
} else if md.decrypted != nil {
|
||||
md.UnverifiedBody = checkReader{md}
|
||||
} else {
|
||||
md.UnverifiedBody = md.LiteralData.Body
|
||||
}
|
||||
|
||||
return md, nil
|
||||
}
|
||||
|
||||
// hashForSignature returns a pair of hashes that can be used to verify a
|
||||
// signature. The signature may specify that the contents of the signed message
|
||||
// should be preprocessed (i.e. to normalise line endings). Thus this function
|
||||
// returns two hashes. The second should be used to hash the message itself and
|
||||
// performs any needed preprocessing.
|
||||
func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, os.Error) {
|
||||
h := hashId.New()
|
||||
if h == nil {
|
||||
return nil, nil, error.UnsupportedError("hash not availible: " + strconv.Itoa(int(hashId)))
|
||||
}
|
||||
|
||||
switch sigType {
|
||||
case packet.SigTypeBinary:
|
||||
return h, h, nil
|
||||
case packet.SigTypeText:
|
||||
return h, NewCanonicalTextHash(h), nil
|
||||
}
|
||||
|
||||
return nil, nil, error.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType)))
|
||||
}
|
||||
|
||||
// checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF
|
||||
// it closes the ReadCloser from any SymmetricallyEncrypted packet to trigger
|
||||
// MDC checks.
|
||||
type checkReader struct {
|
||||
md *MessageDetails
|
||||
}
|
||||
|
||||
func (cr checkReader) Read(buf []byte) (n int, err os.Error) {
|
||||
n, err = cr.md.LiteralData.Body.Read(buf)
|
||||
if err == os.EOF {
|
||||
mdcErr := cr.md.decrypted.Close()
|
||||
if mdcErr != nil {
|
||||
err = mdcErr
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// signatureCheckReader wraps an io.Reader from a LiteralData packet and hashes
|
||||
// the data as it is read. When it sees an EOF from the underlying io.Reader
|
||||
// it parses and checks a trailing Signature packet and triggers any MDC checks.
|
||||
type signatureCheckReader struct {
|
||||
packets *packet.Reader
|
||||
h, wrappedHash hash.Hash
|
||||
md *MessageDetails
|
||||
}
|
||||
|
||||
func (scr *signatureCheckReader) Read(buf []byte) (n int, err os.Error) {
|
||||
n, err = scr.md.LiteralData.Body.Read(buf)
|
||||
scr.wrappedHash.Write(buf[:n])
|
||||
if err == os.EOF {
|
||||
var p packet.Packet
|
||||
p, scr.md.SignatureError = scr.packets.Next()
|
||||
if scr.md.SignatureError != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var ok bool
|
||||
if scr.md.Signature, ok = p.(*packet.Signature); !ok {
|
||||
scr.md.SignatureError = error.StructuralError("LiteralData not followed by Signature")
|
||||
return
|
||||
}
|
||||
|
||||
scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignature(scr.h, scr.md.Signature)
|
||||
|
||||
// The SymmetricallyEncrypted packet, if any, might have an
|
||||
// unsigned hash of its own. In order to check this we need to
|
||||
// close that Reader.
|
||||
if scr.md.decrypted != nil {
|
||||
mdcErr := scr.md.decrypted.Close()
|
||||
if mdcErr != nil {
|
||||
err = mdcErr
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// CheckDetachedSignature takes a signed file and a detached signature and
|
||||
// returns the signer if the signature is valid. If the signer isn't know,
|
||||
// UnknownIssuerError is returned.
|
||||
func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err os.Error) {
|
||||
p, err := packet.Read(signature)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
sig, ok := p.(*packet.Signature)
|
||||
if !ok {
|
||||
return nil, error.StructuralError("non signature packet found")
|
||||
}
|
||||
|
||||
if sig.IssuerKeyId == nil {
|
||||
return nil, error.StructuralError("signature doesn't have an issuer")
|
||||
}
|
||||
|
||||
keys := keyring.KeysById(*sig.IssuerKeyId)
|
||||
if len(keys) == 0 {
|
||||
return nil, error.UnknownIssuerError
|
||||
}
|
||||
|
||||
h, wrappedHash, err := hashForSignature(sig.Hash, sig.SigType)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
_, err = io.Copy(wrappedHash, signed)
|
||||
if err != nil && err != os.EOF {
|
||||
return
|
||||
}
|
||||
|
||||
for _, key := range keys {
|
||||
if key.SelfSignature.FlagsValid && !key.SelfSignature.FlagSign {
|
||||
continue
|
||||
}
|
||||
err = key.PublicKey.VerifySignature(h, sig)
|
||||
if err == nil {
|
||||
return key.Entity, nil
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return nil, error.UnknownIssuerError
|
||||
}
|
||||
|
||||
// CheckArmoredDetachedSignature performs the same actions as
|
||||
// CheckDetachedSignature but expects the signature to be armored.
|
||||
func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err os.Error) {
|
||||
body, err := readArmored(signature, SignatureType)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return CheckDetachedSignature(keyring, signed, body)
|
||||
}
|
237
src/pkg/crypto/openpgp/read_test.go
Normal file
237
src/pkg/crypto/openpgp/read_test.go
Normal file
File diff suppressed because one or more lines are too long
92
src/pkg/crypto/openpgp/write.go
Normal file
92
src/pkg/crypto/openpgp/write.go
Normal file
@ -0,0 +1,92 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package openpgp
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/openpgp/armor"
|
||||
"crypto/openpgp/error"
|
||||
"crypto/openpgp/packet"
|
||||
"crypto/rsa"
|
||||
_ "crypto/sha256"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DetachSign signs message with the private key from signer (which must
|
||||
// already have been decrypted) and writes the signature to w.
|
||||
func DetachSign(w io.Writer, signer *Entity, message io.Reader) os.Error {
|
||||
return detachSign(w, signer, message, packet.SigTypeBinary)
|
||||
}
|
||||
|
||||
// ArmoredDetachSign signs message with the private key from signer (which
|
||||
// must already have been decrypted) and writes an armored signature to w.
|
||||
func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader) (err os.Error) {
|
||||
return armoredDetachSign(w, signer, message, packet.SigTypeBinary)
|
||||
}
|
||||
|
||||
// DetachSignText signs message (after canonicalising the line endings) with
|
||||
// the private key from signer (which must already have been decrypted) and
|
||||
// writes the signature to w.
|
||||
func DetachSignText(w io.Writer, signer *Entity, message io.Reader) os.Error {
|
||||
return detachSign(w, signer, message, packet.SigTypeText)
|
||||
}
|
||||
|
||||
// ArmoredDetachSignText signs message (after canonicalising the line endings)
|
||||
// with the private key from signer (which must already have been decrypted)
|
||||
// and writes an armored signature to w.
|
||||
func SignTextDetachedArmored(w io.Writer, signer *Entity, message io.Reader) os.Error {
|
||||
return armoredDetachSign(w, signer, message, packet.SigTypeText)
|
||||
}
|
||||
|
||||
func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType) (err os.Error) {
|
||||
out, err := armor.Encode(w, SignatureType, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = detachSign(out, signer, message, sigType)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return out.Close()
|
||||
}
|
||||
|
||||
func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType) (err os.Error) {
|
||||
if signer.PrivateKey == nil {
|
||||
return error.InvalidArgumentError("signing key doesn't have a private key")
|
||||
}
|
||||
if signer.PrivateKey.Encrypted {
|
||||
return error.InvalidArgumentError("signing key is encrypted")
|
||||
}
|
||||
|
||||
sig := new(packet.Signature)
|
||||
sig.SigType = sigType
|
||||
sig.PubKeyAlgo = signer.PrivateKey.PubKeyAlgo
|
||||
sig.Hash = crypto.SHA256
|
||||
sig.CreationTime = uint32(time.Seconds())
|
||||
sig.IssuerKeyId = &signer.PrivateKey.KeyId
|
||||
|
||||
h, wrappedHash, err := hashForSignature(sig.Hash, sig.SigType)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
io.Copy(wrappedHash, message)
|
||||
|
||||
switch signer.PrivateKey.PubKeyAlgo {
|
||||
case packet.PubKeyAlgoRSA, packet.PubKeyAlgoRSASignOnly:
|
||||
priv := signer.PrivateKey.PrivateKey.(*rsa.PrivateKey)
|
||||
err = sig.SignRSA(h, priv)
|
||||
default:
|
||||
err = error.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo)))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return sig.Serialize(w)
|
||||
}
|
34
src/pkg/crypto/openpgp/write_test.go
Normal file
34
src/pkg/crypto/openpgp/write_test.go
Normal file
@ -0,0 +1,34 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package openpgp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSignDetached(t *testing.T) {
|
||||
kring, _ := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex))
|
||||
out := bytes.NewBuffer(nil)
|
||||
message := bytes.NewBufferString(signedInput)
|
||||
err := DetachSign(out, kring[0], message)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
testDetachedSignature(t, kring, out, signedInput, "check")
|
||||
}
|
||||
|
||||
func TestSignTextDetached(t *testing.T) {
|
||||
kring, _ := ReadKeyRing(readerFromHex(testKeys1And2PrivateHex))
|
||||
out := bytes.NewBuffer(nil)
|
||||
message := bytes.NewBufferString(signedInput)
|
||||
err := DetachSignText(out, kring[0], message)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
testDetachedSignature(t, kring, out, signedInput, "check")
|
||||
}
|
Loading…
Reference in New Issue
Block a user