diff --git a/bitcurves/bitcurve.go b/bitcurves/bitcurve.go index 3ed3f4357..c45ae5d7c 100644 --- a/bitcurves/bitcurve.go +++ b/bitcurves/bitcurve.go @@ -191,7 +191,6 @@ func (bitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, return x3, y3, z3 } -//TODO: double check if it is okay // ScalarMult returns k*(Bx,By) where k is a number in big-endian form. func (bitCurve *BitCurve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { // We have a slight problem in that the identity of the group (the @@ -239,7 +238,6 @@ func (bitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f} -//TODO: double check if it is okay // GenerateKey returns a public/private key pair. The private key is generated // using the given reader, which must return random data. func (bitCurve *BitCurve) GenerateKey(rand io.Reader) (priv []byte, x, y *big.Int, err error) { diff --git a/bn256/bn256.go b/bn256/bn256.go index 9c99fcdb5..5d6d198bc 100644 --- a/bn256/bn256.go +++ b/bn256/bn256.go @@ -162,7 +162,7 @@ type G2 struct { p *twistPoint } -// RandomG1 returns x and g₂ˣ where x is a random, non-zero number read from r. +// RandomG2 returns x and g₂ˣ where x is a random, non-zero number read from r. func RandomG2(r io.Reader) (*big.Int, *G2, error) { var k *big.Int var err error diff --git a/brainpool/rcurve.go b/brainpool/rcurve.go index 2d5355085..7e291d6aa 100644 --- a/brainpool/rcurve.go +++ b/brainpool/rcurve.go @@ -80,4 +80,4 @@ func (curve *rcurve) ScalarMult(x1, y1 *big.Int, scalar []byte) (x, y *big.Int) func (curve *rcurve) ScalarBaseMult(scalar []byte) (x, y *big.Int) { return curve.fromTwisted(curve.twisted.ScalarBaseMult(scalar)) -} \ No newline at end of file +} diff --git a/cryptobyte/asn1.go b/cryptobyte/asn1.go index f930f7e52..24c46c41b 100644 --- a/cryptobyte/asn1.go +++ b/cryptobyte/asn1.go @@ -488,7 +488,7 @@ func (s *String) ReadASN1BitString(out *encoding_asn1.BitString) bool { return true } -// ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances. It is +// ReadASN1BitStringAsBytes decodes an ASN.1 BIT STRING into out and advances. It is // an error if the BIT STRING is not a whole number of bytes. It reports // whether the read was successful. func (s *String) ReadASN1BitStringAsBytes(out *[]byte) bool { diff --git a/openpgp/armor/armor.go b/openpgp/armor/armor.go index 36a680436..8ef3c5201 100644 --- a/openpgp/armor/armor.go +++ b/openpgp/armor/armor.go @@ -10,8 +10,9 @@ import ( "bufio" "bytes" "encoding/base64" - "golang.org/x/crypto/openpgp/errors" "io" + + "golang.org/x/crypto/openpgp/errors" ) // A Block represents an OpenPGP armored structure. diff --git a/openpgp/armor/armor_test.go b/openpgp/armor/armor_test.go index 9334e94e9..6d8cbddd5 100644 --- a/openpgp/armor/armor_test.go +++ b/openpgp/armor/armor_test.go @@ -50,7 +50,7 @@ func TestDecodeEncode(t *testing.T) { w.Close() if !bytes.Equal(buf.Bytes(), []byte(armorExample1)) { - t.Errorf("got: %s\nwant: %s", string(buf.Bytes()), armorExample1) + t.Errorf("got: %s\nwant: %s", buf.String(), armorExample1) } } diff --git a/openpgp/ecdh/ecdh.go b/openpgp/ecdh/ecdh.go index 1c8cc65f2..7b1b5b06c 100644 --- a/openpgp/ecdh/ecdh.go +++ b/openpgp/ecdh/ecdh.go @@ -18,11 +18,13 @@ import ( "golang.org/x/crypto/openpgp/internal/ecc" ) +// KDF is the Key Derivation Function as Specified in RFC 6637, section 7. type KDF struct { Hash algorithm.Hash Cipher algorithm.Cipher } +// PublicKey represents an ECDH public key. type PublicKey struct { ecc.CurveType elliptic.Curve @@ -30,11 +32,13 @@ type PublicKey struct { KDF } +// PrivateKey represents an ECDH private key. type PrivateKey struct { - PublicKey D []byte + PublicKey } +// GenerateKey returns a PrivateKey object and an eventual error. func GenerateKey(c elliptic.Curve, kdf KDF, rand io.Reader) (priv *PrivateKey, err error) { priv = new(PrivateKey) priv.PublicKey.Curve = c @@ -43,6 +47,10 @@ func GenerateKey(c elliptic.Curve, kdf KDF, rand io.Reader) (priv *PrivateKey, e return } +// Encrypt encrypts the given message to the given key. It first generates the +// shared secret from the given random reader, and proceeds to encrypt. It +// returns the generated key pair in compressed form, the ciphertext, and an +// eventual error. func Encrypt(random io.Reader, pub *PublicKey, msg, curveOID, fingerprint []byte) (vsG, c []byte, err error) { if len(msg) > 40 { return nil, nil, errors.New("ecdh: message too long") @@ -86,6 +94,8 @@ func Encrypt(random io.Reader, pub *PublicKey, msg, curveOID, fingerprint []byte } +// Decrypt decrypts the given message with the given private key. It returns a +// plaintext and an eventual error. func Decrypt(priv *PrivateKey, vsG, m, curveOID, fingerprint []byte) (msg []byte, err error) { if priv.PublicKey.CurveType == ecc.Curve25519 { return X25519Decrypt(priv, vsG, m, curveOID, fingerprint) diff --git a/openpgp/ecdh/x25519.go b/openpgp/ecdh/x25519.go index 3db0b2be0..616a7d7e6 100644 --- a/openpgp/ecdh/x25519.go +++ b/openpgp/ecdh/x25519.go @@ -16,7 +16,7 @@ import ( "golang.org/x/crypto/openpgp/internal/ecc" ) -// Generates a private-public key-pair. +// x25519GenerateKeyPairBytes generates a private-public key-pair. // 'priv' is a private key; a scalar belonging to the set // 2^{254} + 8 * [0, 2^{251}), in order to avoid the small subgroup of the // curve. 'pub' is simply 'priv' * G where G is the base point. @@ -28,7 +28,7 @@ func x25519GenerateKeyPairBytes(rand io.Reader) (priv [32]byte, pub [32]byte, er helper.SetString("27742317777372353535851937790883648493", 10) n.Add(n, helper) - for true { + for { _, err = io.ReadFull(rand, priv[:]) if err != nil { return @@ -48,7 +48,6 @@ func x25519GenerateKeyPairBytes(rand io.Reader) (priv [32]byte, pub [32]byte, er curve25519.ScalarBaseMult(&pub, &priv) return } - return } // X25519GenerateKey samples the key pair according to the correct distribution. @@ -82,6 +81,8 @@ func X25519GenerateKey(rand io.Reader, kdf KDF) (priv *PrivateKey, err error) { return priv, nil } +// X25519Encrypt is the Encrypt procedure of the ecdh package when the public +// key is set with curve 25519. func X25519Encrypt(random io.Reader, pub *PublicKey, msg, curveOID, fingerprint []byte) (vsG, c []byte, err error) { d, ephemeralKey, err := x25519GenerateKeyPairBytes(random) if err != nil { @@ -114,6 +115,8 @@ func X25519Encrypt(random io.Reader, pub *PublicKey, msg, curveOID, fingerprint return vsg[:], c, nil } +// X25519Decrypt is the Encrypt procedure of the ecdh package when the public +// key is set with curve 25519. func X25519Decrypt(priv *PrivateKey, vsG, m, curveOID, fingerprint []byte) (msg []byte, err error) { var zb, d, ephemeralKey [32]byte if len(vsG) != 33 || vsG[0] != 0x40 { diff --git a/openpgp/errors/errors.go b/openpgp/errors/errors.go index f7d6c138d..780a29442 100644 --- a/openpgp/errors/errors.go +++ b/openpgp/errors/errors.go @@ -47,6 +47,8 @@ func (se signatureExpiredError) Error() string { return "openpgp: signature expired" } +// ErrSignatureExpired indicates that a signature has expired, regardless of +// its syntactic validity. var ErrSignatureExpired error = signatureExpiredError(0) type keyIncorrectError int @@ -55,6 +57,7 @@ func (ki keyIncorrectError) Error() string { return "openpgp: incorrect key" } +// ErrKeyIncorrect indicates that the passed key is incorrect (see openpgp/read.go). var ErrKeyIncorrect error = keyIncorrectError(0) type unknownIssuerError int @@ -63,6 +66,7 @@ func (unknownIssuerError) Error() string { return "openpgp: signature made by unknown entity" } +// ErrUnknownIssuer indicates that a signature was made by an unknown entity. var ErrUnknownIssuer error = unknownIssuerError(0) type keyRevokedError int @@ -71,8 +75,10 @@ func (keyRevokedError) Error() string { return "openpgp: signature made by revoked key" } +// ErrKeyRevoked indicates that a signature was made by a revoked key. var ErrKeyRevoked error = keyRevokedError(0) +// UnknownPacketTypeError indicates that the packet ID is not recognized. type UnknownPacketTypeError uint8 func (upte UnknownPacketTypeError) Error() string { diff --git a/openpgp/internal/algorithm/cipher.go b/openpgp/internal/algorithm/cipher.go index 5760cff80..0d266547e 100644 --- a/openpgp/internal/algorithm/cipher.go +++ b/openpgp/internal/algorithm/cipher.go @@ -44,19 +44,12 @@ var CipherById = map[uint8]Cipher{ AES256.Id(): AES256, } +// CipherFunction determines the block cipher algorithm. type CipherFunction uint8 -// ID returns the algorithm Id, as a byte, of cipher. -func (sk CipherFunction) Id() uint8 { - return uint8(sk) -} - -var keySizeByID = map[uint8]int{ - TripleDES.Id(): 24, - CAST5.Id(): cast5.KeySize, - AES128.Id(): 16, - AES192.Id(): 24, - AES256.Id(): 32, +// Id returns the algorithm ID, as a byte, of cipher. +func (cipher CipherFunction) Id() uint8 { + return uint8(cipher) } // KeySize returns the key size, in bytes, of cipher. diff --git a/openpgp/internal/ecc/curveInfo.go b/openpgp/internal/ecc/curveInfo.go index a58f52bfe..b2871ced5 100644 --- a/openpgp/internal/ecc/curveInfo.go +++ b/openpgp/internal/ecc/curveInfo.go @@ -8,6 +8,7 @@ import ( "golang.org/x/crypto/brainpool" ) +// SignatureAlgorithm indicates the cryptographic signing algorithm. type SignatureAlgorithm uint8 const ( @@ -15,6 +16,7 @@ const ( EdDSA SignatureAlgorithm = 2 ) +// CurveInfo holds information about the chosen elliptic curve. type CurveInfo struct { Name string Oid *encoding.OID @@ -89,6 +91,8 @@ var curves = []CurveInfo{ }, } +// FindByCurve returns the information of the given elliptic.Curve, or nil if +// the curve is not available. func FindByCurve(curve elliptic.Curve) *CurveInfo { for _, curveInfo := range curves { if curveInfo.Curve == curve { @@ -98,6 +102,7 @@ func FindByCurve(curve elliptic.Curve) *CurveInfo { return nil } +// FindByOid returns the information of the curve holding the given oid. func FindByOid(oid encoding.Field) *CurveInfo { var rawBytes = oid.Bytes() for _, curveInfo := range curves { @@ -108,6 +113,7 @@ func FindByOid(oid encoding.Field) *CurveInfo { return nil } +// FindByName returns the information of the curve holding the given name. func FindByName(name string) *CurveInfo { for _, curveInfo := range curves { if curveInfo.Name == name { @@ -115,4 +121,4 @@ func FindByName(name string) *CurveInfo { } } return nil -} \ No newline at end of file +} diff --git a/openpgp/internal/ecc/curveType.go b/openpgp/internal/ecc/curveType.go index de8bca0ac..5d837b373 100644 --- a/openpgp/internal/ecc/curveType.go +++ b/openpgp/internal/ecc/curveType.go @@ -1,5 +1,6 @@ package ecc +// CurveType determines the type of the curve being used. type CurveType uint8 const ( @@ -7,4 +8,4 @@ const ( Curve25519 CurveType = 2 BitCurve CurveType = 3 BrainpoolCurve CurveType = 4 -) \ No newline at end of file +) diff --git a/openpgp/keys.go b/openpgp/keys.go index fc074a9e0..a6bbce03f 100644 --- a/openpgp/keys.go +++ b/openpgp/keys.go @@ -5,9 +5,9 @@ package openpgp import ( + goerrors "errors" "io" "time" - goerrors "errors" "golang.org/x/crypto/openpgp/armor" "golang.org/x/crypto/openpgp/errors" @@ -183,7 +183,7 @@ func (el EntityList) KeysById(id uint64) (keys []Key) { return } -// KeysByIdAndUsage returns the set of keys with the given id that also meet +// KeysByIdUsage returns the set of keys with the given id that also meet // the key usage given by requiredUsage. The requiredUsage is expressed as // the bitwise-OR of packet.KeyFlag* values. func (el EntityList) KeysByIdUsage(id uint64, requiredUsage byte) (keys []Key) { @@ -345,7 +345,7 @@ EachPacket: switch pkt := p.(type) { case *packet.UserId: - if err := addUserID(e, packets, pkt); err != nil { + if err = addUserID(e, packets, pkt); err != nil { return nil, err } case *packet.Signature: @@ -359,7 +359,7 @@ EachPacket: // Else, ignoring the signature as it does not follow anything // we would know to attach it to. case *packet.PrivateKey: - if pkt.IsSubkey == false { + if !pkt.IsSubkey { packets.Unread(p) break EachPacket } @@ -368,7 +368,7 @@ EachPacket: return nil, err } case *packet.PublicKey: - if pkt.IsSubkey == false { + if !pkt.IsSubkey { packets.Unread(p) break EachPacket } diff --git a/openpgp/packet/compressed.go b/openpgp/packet/compressed.go index e8f0b5caa..02611e62a 100644 --- a/openpgp/packet/compressed.go +++ b/openpgp/packet/compressed.go @@ -19,6 +19,7 @@ type Compressed struct { Body io.Reader } +// Compressions from the flate package (see RFC 1951) const ( NoCompression = flate.NoCompression BestSpeed = flate.BestSpeed diff --git a/openpgp/packet/config.go b/openpgp/packet/config.go index 8e564d9eb..2099facf1 100644 --- a/openpgp/packet/config.go +++ b/openpgp/packet/config.go @@ -63,6 +63,8 @@ type Config struct { AEADConfig *AEADConfig } +// Random returns the random reader of the given Config. If Rand is +// not set, it returns rand.Reader from the crypto/rand package. func (c *Config) Random() io.Reader { if c == nil || c.Rand == nil { return rand.Reader @@ -70,6 +72,8 @@ func (c *Config) Random() io.Reader { return c.Rand } +// Hash returns the default hash algorithm of the given Config. If it is +// not set, it returns SHA256 from the crypto package. func (c *Config) Hash() crypto.Hash { if c == nil || uint(c.DefaultHash) == 0 { return crypto.SHA256 @@ -77,6 +81,8 @@ func (c *Config) Hash() crypto.Hash { return c.DefaultHash } +// Cipher returns the default block cipher algorithm of the given Config. If it +// is not set, it returns CipherAES128 (defined in the packet package). func (c *Config) Cipher() CipherFunction { if c == nil || uint8(c.DefaultCipher) == 0 { return CipherAES128 @@ -84,6 +90,7 @@ func (c *Config) Cipher() CipherFunction { return c.DefaultCipher } +// Now returns the time attribute of the given Config. func (c *Config) Now() time.Time { if c == nil || c.Time == nil { return time.Now() @@ -91,6 +98,7 @@ func (c *Config) Now() time.Time { return c.Time() } +// Compression returns the default compression algorithm of the given Config. func (c *Config) Compression() CompressionAlgo { if c == nil { return CompressionNone @@ -98,6 +106,8 @@ func (c *Config) Compression() CompressionAlgo { return c.DefaultCompressionAlgo } +// PasswordHashIterations returns the S2KCount attribute of the given Config, +// or 0 if the attribute is not set. func (c *Config) PasswordHashIterations() int { if c == nil || c.S2KCount == 0 { return 0 diff --git a/openpgp/packet/encrypted_key.go b/openpgp/packet/encrypted_key.go index 7889eb9bf..1e862eb3c 100644 --- a/openpgp/packet/encrypted_key.go +++ b/openpgp/packet/encrypted_key.go @@ -152,9 +152,15 @@ func (e *EncryptedKey) Serialize(w io.Writer) error { return err } - w.Write([]byte{encryptedKeyVersion}) - binary.Write(w, binary.BigEndian, e.KeyId) - w.Write([]byte{byte(e.Algo)}) + if _, err = w.Write([]byte{encryptedKeyVersion}); err != nil { + return err + } + if err = binary.Write(w, binary.BigEndian, e.KeyId); err != nil { + return err + } + if _, err = w.Write([]byte{byte(e.Algo)}); err != nil { + return err + } switch e.Algo { case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: diff --git a/openpgp/packet/opaque.go b/openpgp/packet/opaque.go index 456d807f2..6a806d401 100644 --- a/openpgp/packet/opaque.go +++ b/openpgp/packet/opaque.go @@ -63,11 +63,12 @@ type OpaqueReader struct { r io.Reader } +// NewOpaqueReader returns a new OpaqueReader from the given io.Reader. func NewOpaqueReader(r io.Reader) *OpaqueReader { return &OpaqueReader{r: r} } -// Read the next OpaquePacket. +// Next reads the next OpaquePacket. func (or *OpaqueReader) Next() (op *OpaquePacket, err error) { tag, _, contents, err := readHeader(or.r) if err != nil { @@ -150,6 +151,8 @@ Truncated: return } +// Serialize writes the serialized contents of the OpaqueSubpacket into the +// given io.Writer. func (osp *OpaqueSubpacket) Serialize(w io.Writer) (err error) { buf := make([]byte, 6) n := serializeSubpacketLength(buf, len(osp.Contents)+1) diff --git a/openpgp/packet/packet.go b/openpgp/packet/packet.go index ecb3c401f..6222db231 100644 --- a/openpgp/packet/packet.go +++ b/openpgp/packet/packet.go @@ -433,6 +433,7 @@ const ( // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-12 type PublicKeyAlgorithm uint8 +// Public key algorithms supported by OpenPGP. const ( PubKeyAlgoRSA PublicKeyAlgorithm = 1 PubKeyAlgoElGamal PublicKeyAlgorithm = 16 @@ -472,6 +473,7 @@ func (pka PublicKeyAlgorithm) CanSign() bool { // http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-13 type CipherFunction algorithm.CipherFunction +// Block ciphers specified for OpenPGP. const ( Cipher3DES CipherFunction = 2 CipherCAST5 CipherFunction = 3 @@ -512,6 +514,7 @@ func padToKeySize(pub *rsa.PublicKey, b []byte) []byte { // supported). See Section 9.3 of RFC 4880. type CompressionAlgo uint8 +// Compression algorithms supported by OpenPGP. const ( CompressionNone CompressionAlgo = 0 CompressionZIP CompressionAlgo = 1 diff --git a/openpgp/packet/private_key.go b/openpgp/packet/private_key.go index 38428f608..b2837f70c 100644 --- a/openpgp/packet/private_key.go +++ b/openpgp/packet/private_key.go @@ -61,6 +61,8 @@ const ( S2KCHECKSUM S2KType = 255 ) +// NewRSAPrivateKey returns a new PrivateKey object with the given creationTime +// and private key from the crypto/rsa package. func NewRSAPrivateKey(creationTime time.Time, priv *rsa.PrivateKey) *PrivateKey { pk := new(PrivateKey) pk.PublicKey = *NewRSAPublicKey(creationTime, &priv.PublicKey) @@ -68,6 +70,8 @@ func NewRSAPrivateKey(creationTime time.Time, priv *rsa.PrivateKey) *PrivateKey return pk } +// NewDSAPrivateKey returns a new PrivateKey object with the given creationTime +// and private key from the crypto/dsa package. func NewDSAPrivateKey(creationTime time.Time, priv *dsa.PrivateKey) *PrivateKey { pk := new(PrivateKey) pk.PublicKey = *NewDSAPublicKey(creationTime, &priv.PublicKey) @@ -75,6 +79,8 @@ func NewDSAPrivateKey(creationTime time.Time, priv *dsa.PrivateKey) *PrivateKey return pk } +// NewElGamalPrivateKey returns a new PrivateKey object with the given creationTime +// and private key from the crypto/openpgp/elgamal package. func NewElGamalPrivateKey(creationTime time.Time, priv *elgamal.PrivateKey) *PrivateKey { pk := new(PrivateKey) pk.PublicKey = *NewElGamalPublicKey(creationTime, &priv.PublicKey) @@ -82,6 +88,8 @@ func NewElGamalPrivateKey(creationTime time.Time, priv *elgamal.PrivateKey) *Pri return pk } +// NewECDSAPrivateKey returns a new PrivateKey object with the given creationTime +// and private key from the crypto/ecdsa package. func NewECDSAPrivateKey(creationTime time.Time, priv *ecdsa.PrivateKey) *PrivateKey { pk := new(PrivateKey) pk.PublicKey = *NewECDSAPublicKey(creationTime, &priv.PublicKey) @@ -113,6 +121,8 @@ func NewSignerPrivateKey(creationTime time.Time, signer crypto.Signer) *PrivateK return pk } +// NewECDHPrivateKey returns a new PrivateKey object with the given creationTime +// and private key from the crypto/openpgp/ecdh package. func NewECDHPrivateKey(creationTime time.Time, priv *ecdh.PrivateKey) *PrivateKey { pk := new(PrivateKey) pk.PublicKey = *NewECDHPublicKey(creationTime, &priv.PublicKey) @@ -120,6 +130,8 @@ func NewECDHPrivateKey(creationTime time.Time, priv *ecdh.PrivateKey) *PrivateKe return pk } +// NewEdDSAPrivateKey returns a new PrivateKey object with the given creationTime +// and private key from the crypto/ed25519 package. func NewEdDSAPrivateKey(creationTime time.Time, priv ed25519.PrivateKey) *PrivateKey { pk := new(PrivateKey) pk.PublicKey = *NewEdDSAPublicKey(creationTime, priv.Public().(ed25519.PublicKey)) @@ -207,6 +219,8 @@ func mod64kHash(d []byte) uint16 { return h } +// Serialize writes the contents of the serialized given private key into the +// given io.Writer. func (pk *PrivateKey) Serialize(w io.Writer) (err error) { buf := bytes.NewBuffer(nil) err = pk.PublicKey.serializeWithoutHeaders(buf) @@ -222,7 +236,7 @@ func (pk *PrivateKey) Serialize(w io.Writer) (err error) { } else { err = pk.serializeUnencrypted(privateKeyBuf) } - + if err != nil { return } diff --git a/openpgp/packet/private_key_test.go b/openpgp/packet/private_key_test.go index d9fcedcfd..2a7495f8a 100644 --- a/openpgp/packet/private_key_test.go +++ b/openpgp/packet/private_key_test.go @@ -158,7 +158,7 @@ func TestExternalRSAPrivateKey(t *testing.T) { Primes: rsaPriv.Primes, } xrsaPriv.Precompute() - if err := NewRSAPrivateKey(time.Now(), xrsaPriv).Serialize(&buf); err != nil { + if err = NewRSAPrivateKey(time.Now(), xrsaPriv).Serialize(&buf); err != nil { t.Fatal(err) } @@ -204,7 +204,7 @@ func TestECDSAPrivateKeysRandomizeFast(t *testing.T) { } var buf bytes.Buffer - if err := NewECDSAPrivateKey(time.Now(), ecdsaPriv).Serialize(&buf); err != nil { + if err = NewECDSAPrivateKey(time.Now(), ecdsaPriv).Serialize(&buf); err != nil { t.Fatal(err) } @@ -229,14 +229,14 @@ func TestECDSAPrivateKeysRandomizeFast(t *testing.T) { if err != nil { t.Fatal(err) } - if err := sig.Sign(h, priv, nil); err != nil { + if err = sig.Sign(h, priv, nil); err != nil { t.Fatal(err) } if h, err = populateHash(sig.Hash, msg); err != nil { t.Fatal(err) } - if err := priv.VerifySignature(h, sig); err != nil { + if err = priv.VerifySignature(h, sig); err != nil { t.Fatal(err) } } @@ -266,7 +266,7 @@ func TestRSASignerPrivateKeysRandomizeSlow(t *testing.T) { if err != nil { t.Fatal(err) } - if err := sig.Sign(h, priv, nil); err != nil { + if err = sig.Sign(h, priv, nil); err != nil { t.Fatal(err) } @@ -319,14 +319,14 @@ func TestECDSASignerPrivateKeysRandomizeFast(t *testing.T) { if err != nil { t.Fatal(err) } - if err := sig.Sign(h, priv, nil); err != nil { + if err = sig.Sign(h, priv, nil); err != nil { t.Fatal(err) } if h, err = populateHash(sig.Hash, msg); err != nil { t.Fatal(err) } - if err := priv.VerifySignature(h, sig); err != nil { + if err = priv.VerifySignature(h, sig); err != nil { t.Fatal(err) } } @@ -354,7 +354,7 @@ func TestEdDSASignerPrivateKeyRandomizeFast(t *testing.T) { if err != nil { t.Fatal(err) } - if err := sig.Sign(h, priv, nil); err != nil { + if err = sig.Sign(h, priv, nil); err != nil { t.Fatal(err) } if h, err = populateHash(sig.Hash, msg); err != nil { diff --git a/openpgp/packet/public_key.go b/openpgp/packet/public_key.go index 01f80ef22..e400177a4 100644 --- a/openpgp/packet/public_key.go +++ b/openpgp/packet/public_key.go @@ -30,9 +30,6 @@ import ( "golang.org/x/crypto/rsa" ) -type kdfHashFunction byte -type kdfAlgorithm byte - // PublicKey represents an OpenPGP public key. See RFC 4880, section 5.5.2. type PublicKey struct { CreationTime time.Time @@ -107,6 +104,7 @@ func NewElGamalPublicKey(creationTime time.Time, pub *elgamal.PublicKey) *Public return pk } +// NewECDSAPublicKey returns a PublicKey that wraps the given ecdsa.PublicKey. func NewECDSAPublicKey(creationTime time.Time, pub *ecdsa.PublicKey) *PublicKey { pk := &PublicKey{ CreationTime: creationTime, @@ -124,17 +122,18 @@ func NewECDSAPublicKey(creationTime time.Time, pub *ecdsa.PublicKey) *PublicKey return pk } +// NewECDHPublicKey returns a PublicKey that wraps the given ecdh.PublicKey. func NewECDHPublicKey(creationTime time.Time, pub *ecdh.PublicKey) *PublicKey { var pk *PublicKey var curveInfo *ecc.CurveInfo - var kdf = encoding.NewOID([]byte{ 0x1, pub.Hash.Id(), pub.Cipher.Id() }) + var kdf = encoding.NewOID([]byte{0x1, pub.Hash.Id(), pub.Cipher.Id()}) if pub.CurveType == ecc.Curve25519 { pk = &PublicKey{ CreationTime: creationTime, PubKeyAlgo: PubKeyAlgoECDH, PublicKey: pub, p: encoding.NewMPI(pub.X.Bytes()), - kdf: kdf, + kdf: kdf, } curveInfo = ecc.FindByName("Curve25519") } else { @@ -143,7 +142,7 @@ func NewECDHPublicKey(creationTime time.Time, pub *ecdh.PublicKey) *PublicKey { PubKeyAlgo: PubKeyAlgoECDH, PublicKey: pub, p: encoding.NewMPI(elliptic.Marshal(pub.Curve, pub.X, pub.Y)), - kdf: kdf, + kdf: kdf, } curveInfo = ecc.FindByCurve(pub.Curve) } @@ -155,6 +154,7 @@ func NewECDHPublicKey(creationTime time.Time, pub *ecdh.PublicKey) *PublicKey { return pk } +// NewEdDSAPublicKey returns a PublicKey that wraps the given ed25519.PublicKey. func NewEdDSAPublicKey(creationTime time.Time, pub ed25519.PublicKey) *PublicKey { curveInfo := ecc.FindByName("Ed25519") pk := &PublicKey{ @@ -345,7 +345,7 @@ func (pk *PublicKey) parseECDH(r io.Reader) (err error) { c := curveInfo.Curve cType := curveInfo.CurveType - var x, y *big.Int; + var x, y *big.Int if cType == ecc.Curve25519 { x = new(big.Int) x.SetBytes(pk.p.Bytes()) @@ -373,9 +373,9 @@ func (pk *PublicKey) parseECDH(r io.Reader) (err error) { pk.PublicKey = &ecdh.PublicKey{ CurveType: cType, - Curve: c, - X: x, - Y: y, + Curve: c, + X: x, + Y: y, KDF: ecdh.KDF{ Hash: kdfHash, Cipher: kdfCipher, @@ -452,6 +452,8 @@ func (pk *PublicKey) SerializeSignaturePrefix(w io.Writer) { return } +// Serialize writes the serialized contents of the given PublicKey into the +// given io.Reader. func (pk *PublicKey) Serialize(w io.Writer) (err error) { length := 6 // 6 byte header @@ -755,7 +757,9 @@ func userIdSignatureHash(id string, pk *PublicKey, hashFunc crypto.Hash) (h hash // RFC 4880, section 5.2.4 pk.SerializeSignaturePrefix(h) - pk.serializeWithoutHeaders(h) + if err = pk.serializeWithoutHeaders(h); err != nil { + return nil, err + } var buf [5]byte buf[0] = 0xb4 diff --git a/openpgp/packet/public_key_test.go b/openpgp/packet/public_key_test.go index 4be0ae3c6..1da9be898 100644 --- a/openpgp/packet/public_key_test.go +++ b/openpgp/packet/public_key_test.go @@ -88,7 +88,7 @@ func TestPublicKeySerialize(t *testing.T) { t.Errorf("#%d: Read error (from serialized data): %s", i, err) continue } - pk, ok = packet.(*PublicKey) + _, ok = packet.(*PublicKey) if !ok { t.Errorf("#%d: failed to parse serialized data, got: %#v", i, packet) continue diff --git a/openpgp/packet/public_key_v3.go b/openpgp/packet/public_key_v3.go index ab9ac4db1..e26726fd6 100644 --- a/openpgp/packet/public_key_v3.go +++ b/openpgp/packet/public_key_v3.go @@ -36,6 +36,7 @@ type PublicKeyV3 struct { n, e encoding.Field } +// TODO: This function is unused. Should be deprecated // newRSAPublicKeyV3 returns a PublicKey that wraps the given rsa.PublicKey. // Included here for testing purposes only. RFC 4880, section 5.5.2: // "an implementation MUST NOT generate a V3 key, but MAY accept it." @@ -137,9 +138,9 @@ func (pk *PublicKeyV3) SerializeSignaturePrefix(w io.Writer) { } pLength += 6 w.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)}) - return } +// Serialize writes the serialized PublicKeyV3 to the given writer. func (pk *PublicKeyV3) Serialize(w io.Writer) (err error) { length := 8 // 8 byte header diff --git a/openpgp/packet/public_key_v3_test.go b/openpgp/packet/public_key_v3_test.go index e06405904..cb044a037 100644 --- a/openpgp/packet/public_key_v3_test.go +++ b/openpgp/packet/public_key_v3_test.go @@ -76,7 +76,7 @@ func TestPublicKeyV3Serialize(t *testing.T) { if packet, err = Read(bytes.NewBuffer(serializeBuf.Bytes())); err != nil { t.Fatalf("#%d: Read error (from serialized data): %s", i, err) } - if pk, ok = packet.(*PublicKeyV3); !ok { + if _, ok = packet.(*PublicKeyV3); !ok { t.Fatalf("#%d: failed to parse serialized data, got: %#v", i, packet) } } diff --git a/openpgp/packet/reader.go b/openpgp/packet/reader.go index bbb810a92..2edb9bb13 100644 --- a/openpgp/packet/reader.go +++ b/openpgp/packet/reader.go @@ -70,6 +70,7 @@ func (r *Reader) Unread(p Packet) { r.q = append(r.q, p) } +// NewReader returns a new Reader from the given io.Reader. func NewReader(r io.Reader) *Reader { return &Reader{ q: nil, diff --git a/openpgp/packet/signature.go b/openpgp/packet/signature.go index 4bc1b2228..11783f90d 100644 --- a/openpgp/packet/signature.go +++ b/openpgp/packet/signature.go @@ -22,8 +22,8 @@ import ( "golang.org/x/crypto/openpgp/s2k" ) +// See RFC 4880, section 5.2.3.21 for details. const ( - // See RFC 4880, section 5.2.3.21 for details. KeyFlagCertify = 1 << iota KeyFlagSign KeyFlagEncryptCommunications @@ -488,7 +488,6 @@ func serializeSubpackets(to []byte, subpackets []outputSubpacket, hashed bool) { to = to[n:] } } - return } // SigExpired returns whether sig is a signature that has expired or is created @@ -561,9 +560,9 @@ func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey, config *Config) (err e switch priv.PubKeyAlgo { case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: // supports both *rsa.PrivateKey and crypto.Signer - sigdata, err := priv.PrivateKey.(crypto.Signer).Sign(config.Random(), digest, sig.Hash) + sigData, err := priv.PrivateKey.(crypto.Signer).Sign(config.Random(), digest, sig.Hash) if err == nil { - sig.RSASignature = encoding.NewMPI(sigdata) + sig.RSASignature = encoding.NewMPI(sigData) } case PubKeyAlgoDSA: dsaPriv := priv.PrivateKey.(*dsa.PrivateKey) @@ -595,10 +594,10 @@ func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey, config *Config) (err e sig.ECDSASigS = new(encoding.MPI).SetBig(s) } case PubKeyAlgoEdDSA: - sigdata, err := priv.PrivateKey.(crypto.Signer).Sign(config.Random(), digest, crypto.Hash(0)) + sigData, err := priv.PrivateKey.(crypto.Signer).Sign(config.Random(), digest, crypto.Hash(0)) if err == nil { - sig.EdDSASigR = encoding.NewMPI(sigdata[:32]) - sig.EdDSASigS = encoding.NewMPI(sigdata[32:]) + sig.EdDSASigR = encoding.NewMPI(sigData[:32]) + sig.EdDSASigS = encoding.NewMPI(sigData[32:]) } default: err = errors.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo))) @@ -800,7 +799,6 @@ func (sig *Signature) buildSubpackets() (subpackets []outputSubpacket) { subpackets = append(subpackets, outputSubpacket{true, prefSymmetricAlgosSubpacket, false, sig.PreferredSymmetric}) } - if len(sig.PreferredHash) > 0 { subpackets = append(subpackets, outputSubpacket{true, prefHashAlgosSubpacket, false, sig.PreferredHash}) } diff --git a/openpgp/packet/symmetrically_encrypted_test.go b/openpgp/packet/symmetrically_encrypted_test.go index c5c00f7b9..f09aa8936 100644 --- a/openpgp/packet/symmetrically_encrypted_test.go +++ b/openpgp/packet/symmetrically_encrypted_test.go @@ -8,10 +8,11 @@ import ( "bytes" "crypto/sha1" "encoding/hex" - "golang.org/x/crypto/openpgp/errors" "io" "io/ioutil" "testing" + + "golang.org/x/crypto/openpgp/errors" ) // TestReader wraps a []byte and returns reads of a specific length. @@ -36,6 +37,7 @@ func (t *testReader) Read(buf []byte) (n int, err error) { return } +// TODO: This test is inactive, and not passing. func testMDCReader(t *testing.T) { mdcPlaintext, _ := hex.DecodeString(mdcPlaintextHex) diff --git a/openpgp/packet/userattribute.go b/openpgp/packet/userattribute.go index 0f760ade2..f581ee3f2 100644 --- a/openpgp/packet/userattribute.go +++ b/openpgp/packet/userattribute.go @@ -12,6 +12,7 @@ import ( "io/ioutil" ) +// UserAttrImageSubpacket is used to encode an image. See RFC 4880, 5.12.1. const UserAttrImageSubpacket = 1 // UserAttribute is capable of storing other types of data about a user @@ -71,7 +72,7 @@ func (uat *UserAttribute) Serialize(w io.Writer) (err error) { for _, sp := range uat.Contents { err = sp.Serialize(&buf) if err != nil { - return err + return } } if err = serializeHeader(w, packetTypeUserAttribute, buf.Len()); err != nil { diff --git a/openpgp/read_test.go b/openpgp/read_test.go index 9229f1ba8..78c36477f 100644 --- a/openpgp/read_test.go +++ b/openpgp/read_test.go @@ -447,42 +447,34 @@ func TestIssue11504(t *testing.T) { func TestSignatureV3Message(t *testing.T) { sig, err := armor.Decode(strings.NewReader(signedMessageV3)) if err != nil { - t.Error(err) - return + t.Fatal(err) } key, err := ReadArmoredKeyRing(strings.NewReader(keyV4forVerifyingSignedMessageV3)) if err != nil { - t.Error(err) - return + t.Fatal(err) } md, err := ReadMessage(sig.Body, key, nil, nil) if err != nil { - t.Error(err) - return + t.Fatal(err) } _, err = ioutil.ReadAll(md.UnverifiedBody) if err != nil { - t.Error(err) - return + t.Fatal(err) } // We'll see a sig error here after reading in the UnverifiedBody above, // if there was one to see. if err = md.SignatureError; err != nil { - t.Error(err) - return + t.Fatal(err) } if md.SignatureV3 == nil { - t.Errorf("No available signature after checking signature") - return + t.Fatalf("No available signature after checking signature") } if md.Signature != nil { - t.Errorf("Did not expect a signature V4 back") - return + t.Fatalf("Did not expect a signature V4 back") } - return } func TestSymmetricAeadGcmOpenPGPJsMessage(t *testing.T) { diff --git a/openpgp/s2k/s2k.go b/openpgp/s2k/s2k.go index 280ecd23c..3dedfdeae 100644 --- a/openpgp/s2k/s2k.go +++ b/openpgp/s2k/s2k.go @@ -356,7 +356,7 @@ func HashIdToString(id byte) (name string, ok bool) { return "", false } -// HashIdToHash returns an OpenPGP hash id which corresponds the given Hash. +// HashToHashId returns an OpenPGP hash id which corresponds the given Hash. func HashToHashId(h crypto.Hash) (id byte, ok bool) { for id, hash := range algorithm.HashById { if hash.HashFunc() == h { diff --git a/openpgp/write.go b/openpgp/write.go index 73dc9b67e..40d608952 100644 --- a/openpgp/write.go +++ b/openpgp/write.go @@ -438,7 +438,9 @@ type signatureWriter struct { } func (s signatureWriter) Write(data []byte) (int, error) { - s.wrappedHash.Write(data) + if n, err := s.wrappedHash.Write(data); err != nil { + return n, err + } flag := 0 switch s.sigType { case packet.SigTypeBinary: diff --git a/rand/rand_test.go b/rand/rand_test.go index 278f3e8e3..f6ad25f7b 100755 --- a/rand/rand_test.go +++ b/rand/rand_test.go @@ -24,11 +24,12 @@ func TestRead(t *testing.T) { var z bytes.Buffer f, _ := flate.NewWriter(&z, 5) - _, err = f.Write(b) - if err != nil { - panic(err) + if _, err = f.Write(b); err != nil { + t.Fatal(err) + } + if err = f.Close(); err != nil { + t.Fatal(err) } - f.Close() if z.Len() < len(b)*99/100 { t.Fatalf("Compressed %d -> %d", len(b), z.Len()) } diff --git a/rand/util.go b/rand/util.go index 51e0eda90..b2139b5c4 100755 --- a/rand/util.go +++ b/rand/util.go @@ -11,7 +11,6 @@ import ( ) var bigZero = big.NewInt(0) -var bigOne = big.NewInt(1) var bigTwo = big.NewInt(2) // smallPrimes is a list of small, prime numbers that allows us to rapidly diff --git a/rsa/pkcs1v15.go b/rsa/pkcs1v15.go index 73411d78d..90a977986 100755 --- a/rsa/pkcs1v15.go +++ b/rsa/pkcs1v15.go @@ -16,7 +16,7 @@ import ( // This file implements encryption and decryption using PKCS#1 v1.5 padding. -// PKCS1v15DecrypterOpts is for passing options to PKCS#1 v1.5 decryption using +// PKCS1v15DecryptOptions is for passing options to PKCS#1 v1.5 decryption using // the crypto.Decrypter interface. type PKCS1v15DecryptOptions struct { // SessionKeyLen is the length of the session key that is being diff --git a/rsa/pss.go b/rsa/pss.go index 3ff0c2f4d..357686158 100755 --- a/rsa/pss.go +++ b/rsa/pss.go @@ -235,11 +235,11 @@ func (pssOpts *PSSOptions) HashFunc() crypto.Hash { return pssOpts.Hash } -func (opts *PSSOptions) saltLength() int { - if opts == nil { +func (pssOpts *PSSOptions) saltLength() int { + if pssOpts == nil { return PSSSaltLengthAuto } - return opts.SaltLength + return pssOpts.SaltLength } // SignPSS calculates the signature of hashed using RSASSA-PSS [1]. diff --git a/rsa/rsa.go b/rsa/rsa.go index 2b05eb0d6..1413cfd0b 100755 --- a/rsa/rsa.go +++ b/rsa/rsa.go @@ -136,15 +136,16 @@ func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.D return nil, err } return plaintext, nil - } else { - return DecryptPKCS1v15(rand, priv, ciphertext) } + return DecryptPKCS1v15(rand, priv, ciphertext) default: return nil, errors.New("crypto/rsa: invalid options for Decrypt") } } +// PrecomputedValues holds big.Int values that are computed before +// encryption/decryption rounds. type PrecomputedValues struct { Dp, Dq *big.Int // D mod (P-1) (or mod Q-1) Qinv *big.Int // Q^-1 mod P @@ -567,7 +568,6 @@ func decryptAndCheck(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int } // DecryptOAEP decrypts ciphertext using RSA-OAEP. - // OAEP is parameterised by a hash function that is used as a random oracle. // Encryption and decryption of a given message must use the same hash function // and sha256.New() is a reasonable choice. diff --git a/ssh/keys.go b/ssh/keys.go index b6b2b4d9f..8bf9cb7f2 100644 --- a/ssh/keys.go +++ b/ssh/keys.go @@ -179,7 +179,7 @@ func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey return "", nil, nil, "", nil, io.EOF } -// ParseAuthorizedKeys parses a public key from an authorized_keys +// ParseAuthorizedKey parses a public key from an authorized_keys // file used in OpenSSH according to the sshd(8) manual page. func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error) { for len(in) > 0 {