From 12366c5ec150d0d6ede2139ec92e5d410d5c71c6 Mon Sep 17 00:00:00 2001 From: tal-botvinnik Date: Thu, 29 Aug 2019 10:25:45 -0400 Subject: [PATCH] Lint, errcheck, vet, deadcode on ProtonMail-provided code. Halfway through Halfway through Finished first pass Solving tests. Relaxing a bit on useless comments, but frowning. Fix comment Linted openpgp/packet, at least some of it Reverting ID -> Id Reverting Fingerprint -> FingerPrint Solving tests Relaxing on some useless comment and reverting Fingerprint -> FingerPrint Missing parenthesis Corrected exported object comments globally --- argon2/argon2.go | 2 +- bcrypt/bcrypt.go | 12 +- bitcurves/bitcurve.go | 9 +- blake2b/blake2b.go | 8 +- blake2s/blake2s.go | 6 +- blowfish/cipher.go | 2 +- bn256/bn256.go | 2 +- brainpool/brainpool.go | 2 +- brainpool/rcurve.go | 2 +- cryptobyte/asn1.go | 2 +- internal/chacha20/chacha_generic.go | 2 +- internal/randutil/randutil.go | 5 +- md4/md4.go | 4 +- openpgp/canonical_text.go | 24 +++- openpgp/clearsign/clearsign.go | 28 +++- openpgp/ecdh/ecdh.go | 12 +- openpgp/ecdh/x25519.go | 10 +- openpgp/end_to_end_test.go | 198 +++++++++++++-------------- openpgp/errors/errors.go | 6 + openpgp/internal/algorithm/cipher.go | 7 +- openpgp/internal/ecc/curveInfo.go | 8 +- openpgp/internal/ecc/curveType.go | 3 +- openpgp/keys.go | 4 +- openpgp/packet/compressed.go | 1 + openpgp/packet/config.go | 10 ++ openpgp/packet/encrypted_key.go | 19 ++- openpgp/packet/opaque.go | 7 +- openpgp/packet/packet.go | 3 + openpgp/packet/private_key.go | 23 +++- openpgp/packet/public_key.go | 5 + openpgp/packet/public_key_v3.go | 1 + openpgp/packet/reader.go | 1 + openpgp/packet/signature.go | 6 +- openpgp/packet/signature_v3.go | 6 +- openpgp/packet/userattribute.go | 1 + openpgp/s2k/s2k.go | 2 +- openpgp/write.go | 2 +- pkcs12/internal/rc2/rc2.go | 4 +- rand/rand_test.go | 8 +- ripemd160/ripemd160.go | 4 +- rsa/pkcs1v15.go | 2 +- rsa/pss.go | 6 +- rsa/rsa.go | 6 +- ssh/keys.go | 2 +- xtea/cipher.go | 2 +- 45 files changed, 301 insertions(+), 178 deletions(-) diff --git a/argon2/argon2.go b/argon2/argon2.go index b423feae..2b9bd4dc 100644 --- a/argon2/argon2.go +++ b/argon2/argon2.go @@ -43,7 +43,7 @@ import ( "golang.org/x/crypto/blake2b" ) -// The Argon2 version implemented by this package. +// Version represents the Argon2 version implemented by this package. const Version = 0x13 const ( diff --git a/bcrypt/bcrypt.go b/bcrypt/bcrypt.go index aeb73f81..a2bad802 100644 --- a/bcrypt/bcrypt.go +++ b/bcrypt/bcrypt.go @@ -24,23 +24,21 @@ const ( DefaultCost int = 10 // the cost that will actually be set if a cost below MinCost is passed into GenerateFromPassword ) -// The error returned from CompareHashAndPassword when a password and hash do -// not match. +// ErrMismatchedHashAndPassword is returned from CompareHashAndPassword when a password and hash do not match. var ErrMismatchedHashAndPassword = errors.New("crypto/bcrypt: hashedPassword is not the hash of the given password") -// The error returned from CompareHashAndPassword when a hash is too short to -// be a bcrypt hash. +// ErrHashTooShort is returned from CompareHashAndPassword when a hash is too short to be a bcrypt hash. var ErrHashTooShort = errors.New("crypto/bcrypt: hashedSecret too short to be a bcrypted password") -// The error returned from CompareHashAndPassword when a hash was created with -// a bcrypt algorithm newer than this implementation. +// HashVersionTooNewError is returned from CompareHashAndPassword when a hash was created with // a bcrypt algorithm +// newer than this implementation. type HashVersionTooNewError byte func (hv HashVersionTooNewError) Error() string { return fmt.Sprintf("crypto/bcrypt: bcrypt algorithm version '%c' requested is newer than current version '%c'", byte(hv), majorVersion) } -// The error returned from CompareHashAndPassword when a hash starts with something other than '$' +// InvalidHashPrefixError is returned from CompareHashAndPassword when a hash starts with something other than '$' type InvalidHashPrefixError byte func (ih InvalidHashPrefixError) Error() string { diff --git a/bitcurves/bitcurve.go b/bitcurves/bitcurve.go index 470631e6..bbef90c3 100644 --- a/bitcurves/bitcurve.go +++ b/bitcurves/bitcurve.go @@ -33,6 +33,7 @@ type BitCurve struct { BitSize int // the size of the underlying field } +// Params returns an elliptic.CurveParams with the given BitCurve parameters. func (BitCurve *BitCurve) Params() (cp *elliptic.CurveParams) { cp = new (elliptic.CurveParams) cp.Name = BitCurve.Name @@ -44,7 +45,7 @@ func (BitCurve *BitCurve) Params() (cp *elliptic.CurveParams) { return cp } -// IsOnBitCurve returns true if the given (x,y) lies on the BitCurve. +// IsOnCurve returns true if the given (x,y) lies on the BitCurve. func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { // y² = x³ + b y2 := new(big.Int).Mul(y, y)//y² @@ -185,8 +186,8 @@ 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. +//TODO: double check if it is okay 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 // point at infinity) cannot be represented in (x, y) form on a finite @@ -233,9 +234,9 @@ 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. +//TODO: double check if it is okay func (BitCurve *BitCurve) GenerateKey(rand io.Reader) (priv []byte, x, y *big.Int, err error) { byteLen := (BitCurve.BitSize + 7) >> 3 priv = make([]byte, byteLen) @@ -372,4 +373,4 @@ func S224() *BitCurve { func S256() *BitCurve { initonce.Do(initAll) return secp256k1 -} \ No newline at end of file +} diff --git a/blake2b/blake2b.go b/blake2b/blake2b.go index c160e1a4..38c8ecf4 100644 --- a/blake2b/blake2b.go +++ b/blake2b/blake2b.go @@ -23,13 +23,13 @@ import ( ) const ( - // The blocksize of BLAKE2b in bytes. + // BlockSize of BLAKE2b in bytes. BlockSize = 128 - // The hash size of BLAKE2b-512 in bytes. + // Size is the hash size of BLAKE2b-512 in bytes. Size = 64 - // The hash size of BLAKE2b-384 in bytes. + // Size384 is the hash size of BLAKE2b-384 in bytes. Size384 = 48 - // The hash size of BLAKE2b-256 in bytes. + // Size256 is the hash size of BLAKE2b-256 in bytes. Size256 = 32 ) diff --git a/blake2s/blake2s.go b/blake2s/blake2s.go index 5fb4a9ec..2360b190 100644 --- a/blake2s/blake2s.go +++ b/blake2s/blake2s.go @@ -23,13 +23,13 @@ import ( ) const ( - // The blocksize of BLAKE2s in bytes. + // BlockSize is the blocksize of BLAKE2s in bytes. BlockSize = 64 - // The hash size of BLAKE2s-256 in bytes. + // Size is the hash size of BLAKE2s-256 in bytes. Size = 32 - // The hash size of BLAKE2s-128 in bytes. + // Size128 is the hash size of BLAKE2s-128 in bytes. Size128 = 16 ) diff --git a/blowfish/cipher.go b/blowfish/cipher.go index 213bf204..c0985c3c 100644 --- a/blowfish/cipher.go +++ b/blowfish/cipher.go @@ -18,7 +18,7 @@ package blowfish // import "golang.org/x/crypto/blowfish" import "strconv" -// The Blowfish block size in bytes. +// BlockSize is the Blowfish block size in bytes. const BlockSize = 8 // A Cipher is an instance of Blowfish encryption using a particular key. diff --git a/bn256/bn256.go b/bn256/bn256.go index 9c99fcdb..5d6d198b 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/brainpool.go b/brainpool/brainpool.go index b4d9eb0b..77fb8b9a 100644 --- a/brainpool/brainpool.go +++ b/brainpool/brainpool.go @@ -131,4 +131,4 @@ func P512t1() elliptic.Curve { func P512r1() elliptic.Curve { once.Do(initAll) return p512r1 -} \ No newline at end of file +} diff --git a/brainpool/rcurve.go b/brainpool/rcurve.go index 2d535508..7e291d6a 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 528b9bff..0d577b1b 100644 --- a/cryptobyte/asn1.go +++ b/cryptobyte/asn1.go @@ -487,7 +487,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/internal/chacha20/chacha_generic.go b/internal/chacha20/chacha_generic.go index 6570847f..6c065b66 100644 --- a/internal/chacha20/chacha_generic.go +++ b/internal/chacha20/chacha_generic.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package ChaCha20 implements the core ChaCha20 function as specified +// Package chacha20 implements the core ChaCha20 function as specified // in https://tools.ietf.org/html/rfc7539#section-2.3. package chacha20 diff --git a/internal/randutil/randutil.go b/internal/randutil/randutil.go index 84b1295a..5cebd36b 100755 --- a/internal/randutil/randutil.go +++ b/internal/randutil/randutil.go @@ -33,6 +33,9 @@ func MaybeReadByte(r io.Reader) { return case <-closedChan: var buf [1]byte - r.Read(buf[:]) + _, err := r.Read(buf[:]) + if err != nil { + panic(err) + } } } diff --git a/md4/md4.go b/md4/md4.go index 59d34806..dee0da05 100644 --- a/md4/md4.go +++ b/md4/md4.go @@ -18,10 +18,10 @@ func init() { crypto.RegisterHash(crypto.MD4, New) } -// The size of an MD4 checksum in bytes. +// Size of an MD4 checksum in bytes. const Size = 16 -// The blocksize of MD4 in bytes. +// BlockSize of MD4 in bytes. const BlockSize = 64 const ( diff --git a/openpgp/canonical_text.go b/openpgp/canonical_text.go index a94f6150..6b70f479 100644 --- a/openpgp/canonical_text.go +++ b/openpgp/canonical_text.go @@ -20,18 +20,33 @@ type canonicalTextHash struct { s int } +// Auxiliary struct to optimize error checking (from +// https://blog.golang.org/errors-are-values) +type errWriter struct { + w io.Writer + err error +} + +func (ew *errWriter) write(buf []byte) { + if ew.err != nil { + return + } + _, ew.err = ew.w.Write(buf) +} + var newline = []byte{'\r', '\n'} func writeCanonical(cw io.Writer, buf []byte, s *int) (int, error) { start := 0 + ew := &errWriter{w: cw} for i, c := range buf { switch *s { case 0: if c == '\r' { *s = 1 } else if c == '\n' { - cw.Write(buf[start:i]) - cw.Write(newline) + ew.write(buf[start:i]) + ew.write(newline) start = i + 1 } case 1: @@ -39,7 +54,10 @@ func writeCanonical(cw io.Writer, buf []byte, s *int) (int, error) { } } - cw.Write(buf[start:]) + ew.write(buf[start:]) + if ew.err != nil { + return 0, ew.err + } return len(buf), nil } diff --git a/openpgp/clearsign/clearsign.go b/openpgp/clearsign/clearsign.go index ad2963d4..df526eee 100644 --- a/openpgp/clearsign/clearsign.go +++ b/openpgp/clearsign/clearsign.go @@ -214,7 +214,22 @@ type dashEscaper struct { config *packet.Config } +// Auxiliary struct to optimize error checking (from +// https://blog.golang.org/errors-are-values) +type errWriter struct { + w io.Writer + err error +} + +func (ew *errWriter) write(buf []byte) { + if ew.err != nil { + return + } + _, ew.err = ew.w.Write(buf) +} + func (d *dashEscaper) Write(data []byte) (n int, err error) { + ew := &errWriter{w: d.toHash} for _, b := range data { d.byteBuf[0] = b @@ -222,7 +237,7 @@ func (d *dashEscaper) Write(data []byte) (n int, err error) { // The final CRLF isn't included in the hash so we have to wait // until this point (the start of the next line) before writing it. if !d.isFirstLine { - d.toHash.Write(crlf) + ew.write(crlf) } d.isFirstLine = false } @@ -243,12 +258,12 @@ func (d *dashEscaper) Write(data []byte) (n int, err error) { if _, err = d.buffered.Write(dashEscape); err != nil { return } - d.toHash.Write(d.byteBuf) + ew.write(d.byteBuf) d.atBeginningOfLine = false } else if b == '\n' { // Nothing to do because we delay writing CRLF to the hash. } else { - d.toHash.Write(d.byteBuf) + ew.write(d.byteBuf) d.atBeginningOfLine = false } if err = d.buffered.WriteByte(b); err != nil { @@ -269,13 +284,13 @@ func (d *dashEscaper) Write(data []byte) (n int, err error) { // Any buffered whitespace wasn't at the end of the line so // we need to write it out. if len(d.whitespace) > 0 { - d.toHash.Write(d.whitespace) + ew.write(d.whitespace) if _, err = d.buffered.Write(d.whitespace); err != nil { return } d.whitespace = d.whitespace[:0] } - d.toHash.Write(d.byteBuf) + ew.write(d.byteBuf) if err = d.buffered.WriteByte(b); err != nil { return } @@ -284,6 +299,9 @@ func (d *dashEscaper) Write(data []byte) (n int, err error) { } n = len(data) + if err == nil { + err = ew.err + } return } diff --git a/openpgp/ecdh/ecdh.go b/openpgp/ecdh/ecdh.go index 1c8cc65f..7b1b5b06 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 a7df5004..f00985e4 100644 --- a/openpgp/ecdh/x25519.go +++ b/openpgp/ecdh/x25519.go @@ -16,6 +16,8 @@ import ( "golang.org/x/crypto/openpgp/internal/ecc" ) +// X25519GenerateParams generates and returns the parameters specified in RFC +// 6637, section 8, with the given random reader. func X25519GenerateParams(rand io.Reader) (priv [32]byte, x [32]byte, err error) { var n, helper = new (big.Int), new (big.Int) n.SetUint64(1) @@ -43,6 +45,8 @@ func X25519GenerateParams(rand io.Reader) (priv [32]byte, x [32]byte, err error) return } +// X25519GenerateKey generates and returns a private key from the given random +// reader and KDF, along with an eventual error. func X25519GenerateKey(rand io.Reader, kdf KDF) (priv *PrivateKey, err error) { ci := ecc.FindByName("Curve25519") priv = new(PrivateKey) @@ -69,6 +73,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 := X25519GenerateParams(random) if err != nil { @@ -101,6 +107,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 { @@ -141,4 +149,4 @@ func copyReversed(out []byte, in []byte) { for i := 0; i < l; i++ { out[i] = in[l-i-1] } -} \ No newline at end of file +} diff --git a/openpgp/end_to_end_test.go b/openpgp/end_to_end_test.go index c0e8f6d7..ed893015 100644 --- a/openpgp/end_to_end_test.go +++ b/openpgp/end_to_end_test.go @@ -27,84 +27,84 @@ type algorithmSet struct { var testSets = []algorithmSet{ { - test_message, + testMessage, "rsa", - rsa_priv_key, - rsa_pub_key, - rsa_pass, - rsa_enc_sign_message, + rsaPrivKey, + rsaPubKey, + rsaPass, + rsaEncSignMessage, }, { - test_message, + testMessage, "dsa", - dsa_elgamal_priv, - dsa_elgamal_pub, - dsa_elgamal_pass, - dsa_elgamal_enc_sign_message, + dsaElGamalPriv, + dsaElGamalPub, + dsaElGamalPass, + dsaElGamalEncSignMessage, }, { - test_message, + testMessage, "p256", - p256_priv, - p256_pub, - p256_pass, - p256_enc_sign_message, + p256Priv, + p256Pub, + p256Pass, + p256EncSignMessage, }, { - test_message, + testMessage, "p384", - p384_priv, - p384_pub, - p384_pass, - p384_enc_sign_message, + p384Priv, + p384Pub, + p384Pass, + p384EncSignMessage, }, { - test_message, + testMessage, "p521", - p521_priv, - p521_pub, - p521_pass, - p521_enc_sign_message, + p521Priv, + p521Pub, + p521Pass, + p521EncSignMessage, }, { - test_message, + testMessage, "secp256k1", - secp256k1_priv, - secp256k1_pub, - secp256k1_pass, - secp256k1_enc_sign_message, + secp256k1Priv, + secp256k1Pub, + secp256k1Pass, + secp256k1EncSignMessage, }, { - test_message, + testMessage, "ed25519", - ed25519_priv, - ed25519_pub, - ed25519_pass, - ed25519_enc_sign_message, + ed25519Priv, + ed25519Pub, + ed25519Pass, + ed25519EncSignMessage, }, { - brainpool_testmessage, + brainpoolTestMessage, "brainpoolp256r1", - brainpoolp256r1_priv, - brainpoolp256r1_pub, - brainpoolp256r1_pass, - brainpoolp256r1_enc_sign_message, + brainpoolp256r1Priv, + brainpoolp256r1Pub, + brainpoolp256r1Pass, + brainpoolp256r1EncSignMessage, }, { - brainpool_testmessage, + brainpoolTestMessage, "brainpoolp384r1", - brainpoolp384r1_priv, - brainpoolp384r1_pub, - brainpoolp384r1_pass, - brainpoolp384r1_enc_sign_message, + brainpoolp384r1Priv, + brainpoolp384r1Pub, + brainpoolp384r1Pass, + brainpoolp384r1EncSignMessage, }, { - brainpool_testmessage, + brainpoolTestMessage, "brainpoolp512r1", - brainpoolp512r1_priv, - brainpoolp512r1_pub, - brainpoolp512r1_pass, - brainpoolp512r1_enc_sign_message, + brainpoolp512r1Priv, + brainpoolp512r1Pub, + brainpoolp512r1Pass, + brainpoolp512r1EncSignMessage, }, } @@ -252,9 +252,9 @@ func encryptDecryptTest(t *testing.T, testSetFrom algorithmSet, testSetTo algori t.Fatal("The message should be encrypted") } signKey, _ := signed.SigningKey(time.Now()) - expectedKeyId := signKey.PublicKey.KeyId - if md.SignedByKeyId != expectedKeyId { - t.Fatalf("Message signed by wrong key id, got: %v, want: %v", *md.SignedBy, expectedKeyId) + expectedKeyID := signKey.PublicKey.KeyId + if md.SignedByKeyId != expectedKeyID { + t.Fatalf("Message signed by wrong key id, got: %v, want: %v", *md.SignedBy, expectedKeyID) } if md.SignedBy == nil { t.Fatalf("Failed to find the signing Entity") @@ -266,9 +266,9 @@ func encryptDecryptTest(t *testing.T, testSetFrom algorithmSet, testSetTo algori } encryptKey, _ := publicKeyTo[0].EncryptionKey(time.Now()) - expectedEncKeyId := encryptKey.PublicKey.KeyId - if len(md.EncryptedToKeyIds) != 1 || md.EncryptedToKeyIds[0] != expectedEncKeyId { - t.Errorf("Expected message to be encrypted to %v, but got %#v", expectedKeyId, md.EncryptedToKeyIds) + expectedEncKeyID := encryptKey.PublicKey.KeyId + if len(md.EncryptedToKeyIds) != 1 || md.EncryptedToKeyIds[0] != expectedEncKeyID { + t.Errorf("Expected message to be encrypted to %v, but got %#v", expectedKeyID, md.EncryptedToKeyIds) } if string(plaintext) != message { @@ -388,7 +388,7 @@ func makeKeyGenTestSets() (testSets []algorithmSet, err error) { newTestSet := algorithmSet{} newTestSet.name = keySet.name + "_keygen" newTestSet.password = password - newTestSet.message = test_message + newTestSet.message = testMessage newEntity, _ := NewEntity(email, comments, email, keySet.cfg) if err = newEntity.SelfSign(nil); err != nil { @@ -477,11 +477,11 @@ func TestEndToEnd(t *testing.T) { } } -const test_message = "test問量鮮控到案進平" +const testMessage = "test問量鮮控到案進平" -const rsa_pass = "hello world" +const rsaPass = "hello world" -const rsa_priv_key = `-----BEGIN PGP PRIVATE KEY BLOCK----- +const rsaPrivKey = `-----BEGIN PGP PRIVATE KEY BLOCK----- lQH+BFJhL04BBADclrUEDDsm0PSZbQ6pml9FpzTyXiyCyDN+rMOsy9J300Oc10kt /nyBej9vZSRcaW5VpNNj0iA+c1/w2FPf84zNsTzvDmuMaNHFUzky4/vkYuZra//3 @@ -519,7 +519,7 @@ SXuqKcWqoEuO7OBSEFThCXBfUYMC01OrqKEswPm/V3zZkLu01q12UMwZach28QwK =lw5e -----END PGP PRIVATE KEY BLOCK-----` -const rsa_pub_key = `-----BEGIN PGP PUBLIC KEY BLOCK----- +const rsaPubKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- mI0EUmEvTgEEANyWtQQMOybQ9JltDqmaX0WnNPJeLILIM36sw6zL0nfTQ5zXSS3+ fIF6P29lJFxpblWk02PSID5zX/DYU9/zjM2xPO8Oa4xo0cVTOTLj++Ri5mtr//f5 @@ -542,7 +542,7 @@ hz3tYjKhoFTKEIq3y3Pp =h/aX -----END PGP PUBLIC KEY BLOCK-----` -const rsa_enc_sign_message = `-----BEGIN PGP MESSAGE----- +const rsaEncSignMessage = `-----BEGIN PGP MESSAGE----- wYwD4IT3RGwgLJcBA/9txflPrGAhTRBISzQFVrMU2DYjuKy+XbOxMEsNy1H9 eXbCp6lP6AeKxAGrdDfJb209LoL6lvS4UpCV4eV+ucZ1tzZYBlqxTtMq4oC6 @@ -556,9 +556,9 @@ bBBgRdPauYvDNmUQb9UFfFGiD6GTqNEQd827fz+2r1Lp4OdEdkh1BMeQ =wyjK -----END PGP MESSAGE-----` -const dsa_elgamal_pass = "abcd" +const dsaElGamalPass = "abcd" -const dsa_elgamal_priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- +const dsaElGamalPriv = `-----BEGIN PGP PRIVATE KEY BLOCK----- lQHhBFERnrMRBADmM0hIfkI3yosjgbWo9v0Lnr3CCE+8KsMszgVS+hBu0XfGraKm ivcA2aaJimHqVYOP7gEnwFAxHBBpeTJcu5wzCFyJwEYqVeS3nnaIhBPplSF14Duf @@ -585,7 +585,7 @@ AKC8omYPPomN1E/UJFfXdLDIMi5LoA== =LSrW -----END PGP PRIVATE KEY BLOCK-----` -const dsa_elgamal_pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- +const dsaElGamalPub = `-----BEGIN PGP PUBLIC KEY BLOCK----- xsDiBFERnrMRBADmM0hIfkI3yosjgbWo9v0Lnr3CCE+8KsMszgVS+hBu0XfG raKmivcA2aaJimHqVYOP7gEnwFAxHBBpeTJcu5wzCFyJwEYqVeS3nnaIhBPp @@ -610,7 +610,7 @@ wnO9/+vzIVnL93W3k0/8AKC8omYPPomN1E/UJFfXdLDIMi5LoA== =Oa9H -----END PGP PUBLIC KEY BLOCK-----` -const dsa_elgamal_enc_sign_message = `-----BEGIN PGP MESSAGE----- +const dsaElGamalEncSignMessage = `-----BEGIN PGP MESSAGE----- wcBOA1N4OCSSjECBEAP8DhX4Ii5TxauisNiJ6ThzZVo0rDrM37eG55Z9/Fp9 wOFcMoYiM7muadPd0jjVkGk0Y0d1QrfmAW1619L3kv4lGJcB92jEVXeg6HPq @@ -625,9 +625,9 @@ pBbKbBAQW+fw6ajsKSNoWPqYriVEOGtKCfmrCTe32W0Diifyap7VbsY5q9yK =+rSf -----END PGP MESSAGE-----` -const p256_pass = "" +const p256Pass = "" -const p256_priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- +const p256Priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- lHcEWqvIexMIKoZIzj0DAQcCAwTHEN/Yb0iLnIdL1TZcPDB2k+KqSnMlOxiK2YwV xd9or0tNccGkt7Sg3NcNua7X/YW45Vgkxq0p9lf3pJsepydVAAD/SqMfMs2IAGx3 @@ -644,7 +644,7 @@ vhrof7LYUWcOUggO69XoCM9Log== =bVnA -----END PGP PRIVATE KEY BLOCK-----` -const p256_pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- +const p256Pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- xlIEWqvIexMIKoZIzj0DAQcCAwTHEN/Yb0iLnIdL1TZcPDB2k+KqSnMlOxiK 2YwVxd9or0tNccGkt7Sg3NcNua7X/YW45Vgkxq0p9lf3pJsepydVzR90ZXN0 @@ -660,7 +660,7 @@ hic7M74a6H+y2FFnDlIIDuvV6AjPS6I= =UrtO -----END PGP PUBLIC KEY BLOCK-----` -const p256_enc_sign_message = `-----BEGIN PGP MESSAGE----- +const p256EncSignMessage = `-----BEGIN PGP MESSAGE----- wX4DaAJTyVNTRvUSAgMERFsv0Org2FHPu0n5k6xNOv520Yh2dk2SDojc6cF3 ynPgyMftshAfmDQZ6zPDwW1Ya8EB9ihsXcbjBg4Uf1xoBjCdQHkVTjI39ehZ @@ -673,9 +673,9 @@ YUjQR2GU+zI4qrw= =GXt6 -----END PGP MESSAGE-----` -const p384_pass = "" +const p384Pass = "" -const p384_priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- +const p384Priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- lKQEWqvMThMFK4EEACIDAwQeVELezSIjmPkpfo3QejOWQwPxxaA6xnh3Lgu0zoTz jbYeE6xFejlLMuHGRs/msuwkqRIEKPufVxDA9t4llIClJus82Bei2FV6gF+21xdI @@ -695,7 +695,7 @@ g++gKRKmxI7Jg0+oAOcL4v2iuUx6Yo66T67gCg== =CW/l -----END PGP PRIVATE KEY BLOCK-----` -const p384_pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- +const p384Pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- xm8EWqvMThMFK4EEACIDAwQeVELezSIjmPkpfo3QejOWQwPxxaA6xnh3Lgu0 zoTzjbYeE6xFejlLMuHGRs/msuwkqRIEKPufVxDA9t4llIClJus82Bei2FV6 @@ -714,7 +714,7 @@ THpijrpPruAK =DewR -----END PGP PUBLIC KEY BLOCK-----` -const p384_enc_sign_message = `-----BEGIN PGP MESSAGE----- +const p384EncSignMessage = `-----BEGIN PGP MESSAGE----- wZ4D3tsm495R/DQSAwME/mB7VDjlMWyJzp0BHit9A4M5hFCHSSI70xNeXAqP +eziDTAoo/J3ulVEVx6dyBvXizBxHIz4F5y8eQPfiz8zgj7572z5kuH+/OIh @@ -728,9 +728,9 @@ ho/jQzANS17yy2O17IXqZUvroDfNjdY8Rw/fiCTL =cfGW -----END PGP MESSAGE-----` -const p521_pass = "" +const p521Pass = "" -const p521_priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- +const p521Priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- lNoEWqvMtxMFK4EEACMEIwQBG+c6zB/CLvG89VPlwcEf7lVw1o/USkR1BKwdEJX+ 6kevyCfoW9i5fr3Xj3te/KEkWbm53fYCxQxT1YPCOEQe2/gAyH+Sa+xIL3WFxOho @@ -754,7 +754,7 @@ FBv4c44lu5xpvsgGgmDaIwlgLunElVMnKSXrO9Hqpn9a+pRJv5Be/BsZOW82Y2f7 =dTWU -----END PGP PRIVATE KEY BLOCK-----` -const p521_pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- +const p521Pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- xpMEWqvMtxMFK4EEACMEIwQBG+c6zB/CLvG89VPlwcEf7lVw1o/USkR1BKwd EJX+6kevyCfoW9i5fr3Xj3te/KEkWbm53fYCxQxT1YPCOEQe2/gAyH+Sa+xI @@ -776,7 +776,7 @@ NmNn+/yu01M2DSWu =KibM -----END PGP PUBLIC KEY BLOCK-----` -const p521_enc_sign_message = `-----BEGIN PGP MESSAGE----- +const p521EncSignMessage = `-----BEGIN PGP MESSAGE----- wcACAzZYNqaBUBrOEgQjBABmhjNT+HfNdK3mVvVRpIbP8BACPUzmnFagNzd7 d4jFqfRrP3Il3ohx+scNEYxFgloGOooukRJXASauk4MUXgvpFAFtycVNTT3N @@ -792,9 +792,9 @@ UC6h8O9obgz9IN4= =/S1e -----END PGP MESSAGE-----` -const secp256k1_pass = "juliet" +const secp256k1Pass = "juliet" -const secp256k1_priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- +const secp256k1Priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- xaIEVjET2xMFK4EEAAoCAwS/zT2gefLhEnISXN3rvdV3eD6MVrPwxNMAR+LM ZzFO1gdtZbf7XQSZP02CYQe3YFrNQYYuJ4CGkTvOVJSV+yrA/gkDCILD3FP2 @@ -813,7 +813,7 @@ rsJhBBgTCAATBQJWMRPbCRDCsSOJtAGkPQIbDAAA5IMBAOAd5crBXv9/ihPz =C3TW -----END PGP PRIVATE KEY BLOCK-----` -const secp256k1_pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- +const secp256k1Pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- xk8EVjET2xMFK4EEAAoCAwS/zT2gefLhEnISXN3rvdV3eD6MVrPwxNMAR+LM ZzFO1gdtZbf7XQSZP02CYQe3YFrNQYYuJ4CGkTvOVJSV+yrAzS5Sb21lbyBN @@ -828,7 +828,7 @@ HLr5fhoGnRots3JSC0j20UQQOKVOXaW3 =VpL9 -----END PGP PUBLIC KEY BLOCK-----` -const secp256k1_enc_sign_message = `-----BEGIN PGP MESSAGE----- +const secp256k1EncSignMessage = `-----BEGIN PGP MESSAGE----- wX4DDYFqRW5CSpsSAgMEre9Mf7Ig5et7Z+E6dTM/pTEKD8cEIfuW5yV8RL2X 3FqGkGbhpmxgyIrWvf3cJhhmusdkzl+AisnGz71bVgfBYjCfe3olAfyvlZUj @@ -841,9 +841,9 @@ UMcIpI0EsrGSCI8= =8BUx -----END PGP MESSAGE-----` -const ed25519_pass = "sun" +const ed25519Pass = "sun" -const ed25519_priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- +const ed25519Priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- lIYEWkN+5BYJKwYBBAHaRw8BAQdAIGqj23Kp273IPkgjwA7ue5MDIRAfWLYRqnFy c2AFMcD+BwMCeaL+cNXzgI7uJQ7HBv53TAXO3y5uyJQMonkFtQtldL8YDbNP3pbd @@ -860,7 +860,7 @@ QdsBANlddInzoZ8CCwsNagZXujp+2gWtue5axTPnDkjGhLIK =wo91 -----END PGP PRIVATE KEY BLOCK-----` -const ed25519_pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- +const ed25519Pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- mDMEWkN+5BYJKwYBBAHaRw8BAQdAIGqj23Kp273IPkgjwA7ue5MDIRAfWLYRqnFy c2AFMcC0EUxpZ2h0IDxsaWdodEBzdW4+iJAEExYIADgWIQSGS0GuVELT3Rs0woce @@ -874,7 +874,7 @@ Ba257lrFM+cOSMaEsgo= =D8HS -----END PGP PUBLIC KEY BLOCK-----` -const ed25519_enc_sign_message = `-----BEGIN PGP MESSAGE----- +const ed25519EncSignMessage = `-----BEGIN PGP MESSAGE----- wV4DzYfy+90rz7YSAQdAWBKmhkgx+WtyERt903WpExRZfyAhxji8FKhthTRI Lw4w/vzk9zMULlXZSknznkPnRlJyFUHqH9gFt8e3EQlij62Kd5T5AQBc0CLC @@ -886,12 +886,12 @@ KN5U4Rx7ftKgsaTMsEnKk/w8rEqxL8a1YtLe4X1tdecRBTi7qbndYeXp5lVl =Co9x -----END PGP MESSAGE-----` -const brainpool_testmessage = `test問量鮮控到案進平 +const brainpoolTestMessage = `test問量鮮控到案進平 ` -const brainpoolp256r1_pass = "" +const brainpoolp256r1Pass = "" -const brainpoolp256r1_priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- +const brainpoolp256r1Priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- lHgEWrpD4RMJKyQDAwIIAQEHAgMEMyiJsl3MxlZFRRg518IiUbv+/294KU+dBq/B QYbvt4dHh4M7O9Rgfic8EPbe47wKr6v6Z7wXgHpjqtKRoBzlxAAA/jhgOEGBKP4E @@ -908,7 +908,7 @@ gTHjrXXT++KbkzQRVWMO8UpRwg== =BkRB -----END PGP PRIVATE KEY BLOCK-----` -const brainpoolp256r1_pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- +const brainpoolp256r1Pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- mFMEWrpD4RMJKyQDAwIIAQEHAgMEMyiJsl3MxlZFRRg518IiUbv+/294KU+dBq/B QYbvt4dHh4M7O9Rgfic8EPbe47wKr6v6Z7wXgHpjqtKRoBzlxLQddGVzdEBnb2Ny @@ -923,7 +923,7 @@ Q7eIqzMnDgD+NDXL5S0lB6zul0GTwIEx46110/vim5M0EVVjDvFKUcI= =Bx7J -----END PGP PUBLIC KEY BLOCK-----` -const brainpoolp256r1_enc_sign_message = `-----BEGIN PGP MESSAGE----- +const brainpoolp256r1EncSignMessage = `-----BEGIN PGP MESSAGE----- hH4DLFUmpfJ2kxcSAgMElfY0YbA1dI8s8MMhBHOXw0wwR/O+S8Pm/huBbkIbOb2c AL7ImXZYvPgS5tkpbxmItEedlLF439E8rwrPBqmrWTDSy/q9CyR2IKVSVNbConaz @@ -936,9 +936,9 @@ wyZAsOwGJD4+TQ== =GeXG -----END PGP MESSAGE-----` -const brainpoolp384r1_pass = "" +const brainpoolp384r1Pass = "" -const brainpoolp384r1_priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- +const brainpoolp384r1Priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- lKgEWrqJ2RMJKyQDAwIIAQELAwMELWPYFx5PjaQLkP/dNEmMYqD72jsx/IzSO9j1 FsmwE7hmosHMjXcDWrsxDuRqPfFMN98P/8kRB4Qn+o2dNHHdRuzAm/O5XCpoFGRL @@ -958,7 +958,7 @@ MfjeXWX2rg7rPiWO9HU41dsEcZ2pvN3sC5mQchfqivFINTvIngmk2g== =8J0V -----END PGP PRIVATE KEY BLOCK-----` -const brainpoolp384r1_pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- +const brainpoolp384r1Pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- mHMEWrqJ2RMJKyQDAwIIAQELAwMELWPYFx5PjaQLkP/dNEmMYqD72jsx/IzSO9j1 FsmwE7hmosHMjXcDWrsxDuRqPfFMN98P/8kRB4Qn+o2dNHHdRuzAm/O5XCpoFGRL @@ -976,7 +976,7 @@ JY70dTjV2wRxnam83ewLmZByF+qK8Ug1O8ieCaTa =vEH0 -----END PGP PUBLIC KEY BLOCK-----` -const brainpoolp384r1_enc_sign_message = `-----BEGIN PGP MESSAGE----- +const brainpoolp384r1EncSignMessage = `-----BEGIN PGP MESSAGE----- hJ4D25491by3UQcSAwMEidpiLdDr/FBd9HVhN1kjJkagjbXQrKPuu47ws2k67MBS gNo913vEQOzhqdiVliYtMAIpEt4sNyWCQ+TUEigsFiaG6Dp0wPG4/qVhRgRB4poN @@ -990,9 +990,9 @@ bmKARW86AH7YpKjCbedsy9e5SvQohv102w/mZVk= =C5uY -----END PGP MESSAGE-----` -const brainpoolp512r1_pass = "" +const brainpoolp512r1Pass = "" -const brainpoolp512r1_priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- +const brainpoolp512r1Priv = `-----BEGIN PGP PRIVATE KEY BLOCK----- lNgEWrqKjRMJKyQDAwIIAQENBAMEDI4HTYTe2L0kzVVIJUrN7+8KivNLQNRUeLFp oeKHeEqZdzv2zuYsqW91wTcxuobHuyhz2Rw/6GuxCjHMZKe1OEKzO73MHvk5x3Ut @@ -1016,7 +1016,7 @@ u4H95mtsxZo= =Qb7k -----END PGP PRIVATE KEY BLOCK-----` -const brainpoolp512r1_pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- +const brainpoolp512r1Pub = `-----BEGIN PGP PUBLIC KEY BLOCK----- mJMEWrqKjRMJKyQDAwIIAQENBAMEDI4HTYTe2L0kzVVIJUrN7+8KivNLQNRUeLFp oeKHeEqZdzv2zuYsqW91wTcxuobHuyhz2Rw/6GuxCjHMZKe1OEKzO73MHvk5x3Ut @@ -1037,7 +1037,7 @@ UygWL2RYu4H95mtsxZo= =3o0a -----END PGP PUBLIC KEY BLOCK-----` -const brainpoolp512r1_enc_sign_message = `-----BEGIN PGP MESSAGE----- +const brainpoolp512r1EncSignMessage = `-----BEGIN PGP MESSAGE----- hL4DpJcoPAigmZESBAMEonrXiHjcMR/PE/ZwHEfC2rqhzugPOjxoytUCFx/WwLyI hREwlk3QA4wKO/xM9bgIkUg9bVlbJtsGceAcDgzxPonaeP+UhEMpi+otV4NT9y/F diff --git a/openpgp/errors/errors.go b/openpgp/errors/errors.go index f05964ad..37550c7a 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 a09dd910..5418a55c 100644 --- a/openpgp/internal/algorithm/cipher.go +++ b/openpgp/internal/algorithm/cipher.go @@ -44,11 +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) +// Id returns the algorithm Id, as a byte, of cipher. +func (cipher CipherFunction) Id() uint8 { + return uint8(cipher) } var keySizeByID = map[uint8]int{ diff --git a/openpgp/internal/ecc/curveInfo.go b/openpgp/internal/ecc/curveInfo.go index a58f52bf..b2871ced 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 de8bca0a..5d837b37 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 e0cfa0c7..007193d1 100644 --- a/openpgp/keys.go +++ b/openpgp/keys.go @@ -182,7 +182,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) { @@ -539,7 +539,7 @@ func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error return nil } -// SerializePrivate serializes an Entity, including private key material, to +// SerializePrivateNoSign serializes an Entity, including private key material, to // the given Writer. For now, it must only be used on an Entity returned from // NewEntity. // If config is nil, sensible defaults will be used. diff --git a/openpgp/packet/compressed.go b/openpgp/packet/compressed.go index e8f0b5ca..02611e62 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 cb8df070..bc49daf9 100644 --- a/openpgp/packet/config.go +++ b/openpgp/packet/config.go @@ -54,6 +54,8 @@ type Config struct { RSAPrimes []*big.Int } +// 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 @@ -61,6 +63,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 @@ -68,6 +72,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 @@ -75,6 +81,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() @@ -82,6 +89,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 @@ -89,6 +97,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 67dcf9dc..7a52a705 100644 --- a/openpgp/packet/encrypted_key.go +++ b/openpgp/packet/encrypted_key.go @@ -142,11 +142,20 @@ func (e *EncryptedKey) Serialize(w io.Writer) error { return errors.InvalidArgumentError("don't know how to serialize encrypted key type " + strconv.Itoa(int(e.Algo))) } - serializeHeader(w, packetTypeEncryptedKey, 1 /* version */ +8 /* key id */ +1 /* algo */ +mpiLen) + err := serializeHeader(w, packetTypeEncryptedKey, 1 /* version */ +8 /* key id */ +1 /* algo */ +mpiLen) + if err != nil { + 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: @@ -167,8 +176,6 @@ func (e *EncryptedKey) Serialize(w io.Writer) error { default: panic("internal error") } - - return nil } // SerializeEncryptedKey serializes an encrypted key packet to w that contains diff --git a/openpgp/packet/opaque.go b/openpgp/packet/opaque.go index 456d807f..ec47ae4d 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 { @@ -76,7 +77,7 @@ func (or *OpaqueReader) Next() (op *OpaquePacket, err error) { op = &OpaquePacket{Tag: uint8(tag), Reason: err} err = op.parse(contents) if err != nil { - consumeAll(contents) + _, err = consumeAll(contents) } return } @@ -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 ce645270..f80dc492 100644 --- a/openpgp/packet/packet.go +++ b/openpgp/packet/packet.go @@ -423,6 +423,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 @@ -462,6 +463,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 @@ -502,6 +504,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 28e24d58..47b4e083 100644 --- a/openpgp/packet/private_key.go +++ b/openpgp/packet/private_key.go @@ -57,6 +57,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) @@ -64,6 +66,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) @@ -71,6 +75,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) @@ -78,6 +84,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) @@ -109,6 +117,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) @@ -116,6 +126,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)) @@ -190,6 +202,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) @@ -199,9 +213,12 @@ func (pk *PrivateKey) Serialize(w io.Writer) (err error) { privateKeyBuf := bytes.NewBuffer(nil) if pk.Encrypted { - pk.SerializeEncrypted(privateKeyBuf) + err = pk.SerializeEncrypted(privateKeyBuf) } else { - pk.SerializeUnEncrypted(privateKeyBuf) + err = pk.SerializeUnEncrypted(privateKeyBuf) + } + if err != nil { + return } ptype := packetTypePrivateKey @@ -254,7 +271,7 @@ func (pk *PrivateKey) SerializeUnEncrypted(w io.Writer) (err error) { checksumBytes[1] = byte(checksum) privateKeyBytes = append(privateKeyBytes, checksumBytes[:]...) } - w.Write(privateKeyBytes) + _, err = w.Write(privateKeyBytes) return } diff --git a/openpgp/packet/public_key.go b/openpgp/packet/public_key.go index 81589d2b..201a1b99 100644 --- a/openpgp/packet/public_key.go +++ b/openpgp/packet/public_key.go @@ -106,6 +106,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, @@ -123,6 +124,7 @@ 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 @@ -154,6 +156,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{ @@ -445,6 +448,8 @@ func (pk *PublicKey) SerializeSignaturePrefix(h 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 diff --git a/openpgp/packet/public_key_v3.go b/openpgp/packet/public_key_v3.go index dcce323b..9d270b37 100644 --- a/openpgp/packet/public_key_v3.go +++ b/openpgp/packet/public_key_v3.go @@ -133,6 +133,7 @@ func (pk *PublicKeyV3) SerializeSignaturePrefix(w io.Writer) { 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/reader.go b/openpgp/packet/reader.go index 34bc7c61..7e704d0f 100644 --- a/openpgp/packet/reader.go +++ b/openpgp/packet/reader.go @@ -68,6 +68,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 96009473..858fdf83 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 @@ -331,7 +331,7 @@ func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (r sig.PreferredCompression = make([]byte, len(subpacket)) copy(sig.PreferredCompression, subpacket) case primaryUserIdSubpacket: - // Primary User ID, section 5.2.3.19 + // Primary User Id, section 5.2.3.19 if !isHashed { return } @@ -452,7 +452,7 @@ func subpacketsLength(subpackets []outputSubpacket, hashed bool) (length int) { for _, subpacket := range subpackets { if subpacket.hashed == hashed { length += subpacketLengthLength(len(subpacket.contents) + 1) - length += 1 // type byte + length ++ // type byte length += len(subpacket.contents) } } diff --git a/openpgp/packet/signature_v3.go b/openpgp/packet/signature_v3.go index c6e8d72a..ad1ec7c1 100644 --- a/openpgp/packet/signature_v3.go +++ b/openpgp/packet/signature_v3.go @@ -60,7 +60,7 @@ func (sig *SignatureV3) parse(r io.Reader) (err error) { t := binary.BigEndian.Uint32(buf[1:5]) sig.CreationTime = time.Unix(int64(t), 0) - // Eight-octet Key ID of signer. + // Eight-octet Key Id of signer. if _, err = readFull(r, buf[:8]); err != nil { return } @@ -117,13 +117,13 @@ func (sig *SignatureV3) Serialize(w io.Writer) (err error) { return } - // Write the issuer long key ID + // Write the issuer long key Id binary.BigEndian.PutUint64(buf[:8], sig.IssuerKeyId) if _, err = w.Write(buf[:8]); err != nil { return } - // Write public key algorithm, hash ID, and hash value + // Write public key algorithm, hash Id, and hash value buf[0] = byte(sig.PubKeyAlgo) hashId, ok := s2k.HashToHashId(sig.Hash) if !ok { diff --git a/openpgp/packet/userattribute.go b/openpgp/packet/userattribute.go index d19ffbc7..250a3a0a 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 diff --git a/openpgp/s2k/s2k.go b/openpgp/s2k/s2k.go index ae72e7b7..a59f3181 100644 --- a/openpgp/s2k/s2k.go +++ b/openpgp/s2k/s2k.go @@ -247,7 +247,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 0f6c12f4..90394a93 100644 --- a/openpgp/write.go +++ b/openpgp/write.go @@ -164,7 +164,7 @@ func hashToHashId(h crypto.Hash) uint8 { return v } -// Encrypt encrypts a message to a number of recipients and, optionally, signs +// EncryptText encrypts a message to a number of recipients and, optionally, signs // it. hints contains optional information, that is also encrypted, that aids // the recipients in processing the message. The resulting WriteCloser must // be closed after the contents of the file have been written. diff --git a/pkcs12/internal/rc2/rc2.go b/pkcs12/internal/rc2/rc2.go index 7499e3fb..af0d0642 100644 --- a/pkcs12/internal/rc2/rc2.go +++ b/pkcs12/internal/rc2/rc2.go @@ -16,14 +16,14 @@ import ( "encoding/binary" ) -// The rc2 block size in bytes +// BlockSize is the RC2 block size in bytes const BlockSize = 8 type rc2Cipher struct { k [64]uint16 } -// New returns a new rc2 cipher with the given key and effective key length t1 +// New returns a new RC2 cipher with the given key and effective key length t1 func New(key []byte, t1 int) (cipher.Block, error) { // TODO(dgryski): error checking for key length return &rc2Cipher{ diff --git a/rand/rand_test.go b/rand/rand_test.go index e45f58e4..8ee9042a 100755 --- a/rand/rand_test.go +++ b/rand/rand_test.go @@ -24,8 +24,12 @@ func TestRead(t *testing.T) { var z bytes.Buffer f, _ := flate.NewWriter(&z, 5) - f.Write(b) - f.Close() + if _, err = f.Write(b); err != nil { + panic(err) + } + if err = f.Close(); err != nil { + panic(err) + } if z.Len() < len(b)*99/100 { t.Fatalf("Compressed %d -> %d", len(b), z.Len()) } diff --git a/ripemd160/ripemd160.go b/ripemd160/ripemd160.go index cf3eeb15..b6e2b849 100644 --- a/ripemd160/ripemd160.go +++ b/ripemd160/ripemd160.go @@ -22,10 +22,10 @@ func init() { crypto.RegisterHash(crypto.RIPEMD160, New) } -// The size of the checksum in bytes. +// Size of the checksum in bytes. const Size = 20 -// The block size of the hash algorithm in bytes. +// BlockSize of the hash algorithm in bytes. const BlockSize = 64 const ( diff --git a/rsa/pkcs1v15.go b/rsa/pkcs1v15.go index 73411d78..90a97798 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 3ff0c2f4..35768615 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 2b05eb0d..1413cfd0 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 0e3222d1..c5e2d627 100644 --- a/ssh/keys.go +++ b/ssh/keys.go @@ -170,7 +170,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 { diff --git a/xtea/cipher.go b/xtea/cipher.go index a4c2fd02..d9d1ac62 100644 --- a/xtea/cipher.go +++ b/xtea/cipher.go @@ -18,7 +18,7 @@ package xtea // import "golang.org/x/crypto/xtea" import "strconv" -// The XTEA block size in bytes. +// BlockSize is the XTEA block size in bytes. const BlockSize = 8 // A Cipher is an instance of an XTEA cipher using a particular key.