From 56f158ae121d0fc2f4e994a36434ce5efd689c09 Mon Sep 17 00:00:00 2001 From: tal-botvinnik Date: Wed, 28 Aug 2019 11:57:36 -0400 Subject: [PATCH 1/7] Strong lint, omitting exported function and variable names --- openpgp/armor/armor.go | 1 + openpgp/armor/armor_test.go | 5 +- openpgp/armor/encode.go | 7 +- openpgp/canonical_text.go | 13 ++- openpgp/clearsign/clearsign.go | 20 +++- openpgp/ecdh/ecdh.go | 11 +- openpgp/ecdh/x25519.go | 6 +- openpgp/end_to_end_test.go | 198 ++++++++++++++++----------------- openpgp/key_generation.go | 4 +- openpgp/keys.go | 4 +- openpgp/keys_test.go | 5 +- openpgp/read.go | 23 ++-- openpgp/read_test.go | 26 ++--- openpgp/write.go | 21 ++-- openpgp/write_test.go | 26 ++--- 15 files changed, 206 insertions(+), 164 deletions(-) diff --git a/openpgp/armor/armor.go b/openpgp/armor/armor.go index 592d18643..b864d7426 100644 --- a/openpgp/armor/armor.go +++ b/openpgp/armor/armor.go @@ -35,6 +35,7 @@ type Block struct { oReader openpgpReader } +// ArmorCorrupt is returned if an armor is invalid. var ArmorCorrupt error = errors.StructuralError("armor invalid") const crc24Init = 0xb704ce diff --git a/openpgp/armor/armor_test.go b/openpgp/armor/armor_test.go index 9334e94e9..769172bcc 100644 --- a/openpgp/armor/armor_test.go +++ b/openpgp/armor/armor_test.go @@ -47,7 +47,10 @@ func TestDecodeEncode(t *testing.T) { if err != nil { t.Error(err) } - w.Close() + errClose := w.Close() + if errClose != nil { + t.Errorf("error closing the io.WriteCloser instance") + } if !bytes.Equal(buf.Bytes(), []byte(armorExample1)) { t.Errorf("got: %s\nwant: %s", string(buf.Bytes()), armorExample1) diff --git a/openpgp/armor/encode.go b/openpgp/armor/encode.go index 6f07582c3..da1c594bd 100644 --- a/openpgp/armor/encode.go +++ b/openpgp/armor/encode.go @@ -87,7 +87,6 @@ func (l *lineBreaker) Close() (err error) { return } } - return } @@ -115,7 +114,11 @@ func (e *encoding) Close() (err error) { if err != nil { return } - e.breaker.Close() + closeErr := e.breaker.Close() + if closeErr != nil { + return + } + var checksumBytes [3]byte checksumBytes[0] = byte(e.crc >> 16) diff --git a/openpgp/canonical_text.go b/openpgp/canonical_text.go index a94f6150c..19ec92af1 100644 --- a/openpgp/canonical_text.go +++ b/openpgp/canonical_text.go @@ -30,16 +30,21 @@ func writeCanonical(cw io.Writer, buf []byte, s *int) (int, error) { if c == '\r' { *s = 1 } else if c == '\n' { - cw.Write(buf[start:i]) - cw.Write(newline) + _, err1 := cw.Write(buf[start:i]) + _, err2 := cw.Write(newline) + if err1 != nil || err2 != nil { + panic("Error writing to io.Writer instance") + } start = i + 1 } case 1: *s = 0 } } - - cw.Write(buf[start:]) + _, err := cw.Write(buf[start:]) + if err != nil { + panic("Error writing to io.Writer instance") + } return len(buf), nil } diff --git a/openpgp/clearsign/clearsign.go b/openpgp/clearsign/clearsign.go index ad2963d43..229c0e986 100644 --- a/openpgp/clearsign/clearsign.go +++ b/openpgp/clearsign/clearsign.go @@ -222,7 +222,9 @@ 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) + if _, err = d.toHash.Write(crlf); err != nil { + return + } } d.isFirstLine = false } @@ -243,12 +245,16 @@ func (d *dashEscaper) Write(data []byte) (n int, err error) { if _, err = d.buffered.Write(dashEscape); err != nil { return } - d.toHash.Write(d.byteBuf) + if _, err = d.toHash.Write(d.byteBuf); err != nil { + return + } d.atBeginningOfLine = false } else if b == '\n' { // Nothing to do because we delay writing CRLF to the hash. } else { - d.toHash.Write(d.byteBuf) + if _, err = d.toHash.Write(d.byteBuf); err != nil { + return + } d.atBeginningOfLine = false } if err = d.buffered.WriteByte(b); err != nil { @@ -269,13 +275,17 @@ 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) + if _, err = d.toHash.Write(d.whitespace); err != nil { + return + } if _, err = d.buffered.Write(d.whitespace); err != nil { return } d.whitespace = d.whitespace[:0] } - d.toHash.Write(d.byteBuf) + if _, err = d.toHash.Write(d.byteBuf); err != nil { + return + } if err = d.buffered.WriteByte(b); err != nil { return } diff --git a/openpgp/ecdh/ecdh.go b/openpgp/ecdh/ecdh.go index 1c8cc65f2..9fbaef805 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,7 @@ func Encrypt(random io.Reader, pub *PublicKey, msg, curveOID, fingerprint []byte } +// Decrypt decrypts the given message with the given private key. 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 a7df5004f..e468672d7 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) @@ -141,4 +145,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 c0e8f6d72..ed8930151 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/key_generation.go b/openpgp/key_generation.go index d13255200..c54083d67 100644 --- a/openpgp/key_generation.go +++ b/openpgp/key_generation.go @@ -110,7 +110,7 @@ func NewEntity(name, comment, email string, config *packet.Config) (*Entity, err PrivateKey: privPrimary, Identities: make(map[string]*Identity), } - isPrimaryId := true + isPrimaryID := true e.Identities[uid.Id] = &Identity{ Name: uid.Id, UserId: uid, @@ -119,7 +119,7 @@ func NewEntity(name, comment, email string, config *packet.Config) (*Entity, err SigType: packet.SigTypePositiveCert, PubKeyAlgo: primarykeyAlgorithm, Hash: config.Hash(), - IsPrimaryId: &isPrimaryId, + IsPrimaryId: &isPrimaryID, FlagsValid: true, FlagSign: true, FlagCertify: true, diff --git a/openpgp/keys.go b/openpgp/keys.go index e0cfa0c73..007193d1f 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/keys_test.go b/openpgp/keys_test.go index b0b9744a3..d739cd0d1 100644 --- a/openpgp/keys_test.go +++ b/openpgp/keys_test.go @@ -488,7 +488,10 @@ func TestNewEntityPublicSerialization(t *testing.T) { t.Fatal(err) } serializedEntity := bytes.NewBuffer(nil) - entity.Serialize(serializedEntity) + err = entity.Serialize(serializedEntity) + if err != nil { + t.Fatal(err) + } _, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes()))) if err != nil { diff --git a/openpgp/read.go b/openpgp/read.go index 856979fb4..44876f30f 100644 --- a/openpgp/read.go +++ b/openpgp/read.go @@ -7,11 +7,9 @@ package openpgp // import "golang.org/x/crypto/openpgp" import ( "crypto" - _ "crypto/sha256" "hash" "io" "strconv" - "golang.org/x/crypto/openpgp/armor" "golang.org/x/crypto/openpgp/errors" "golang.org/x/crypto/openpgp/packet" @@ -158,7 +156,10 @@ FindKey: } if !pk.key.PrivateKey.Encrypted { if len(pk.encryptedKey.Key) == 0 { - pk.encryptedKey.Decrypt(pk.key.PrivateKey, config) + err := pk.encryptedKey.Decrypt(pk.key.PrivateKey, config) + if err != nil { + return nil, err + } } if len(pk.encryptedKey.Key) == 0 { continue @@ -281,11 +282,11 @@ FindLiteralData: // should be preprocessed (i.e. to normalize line endings). Thus this function // returns two hashes. The second should be used to hash the message itself and // performs any needed preprocessing. -func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, error) { - if !hashId.Available() { - return nil, nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashId))) +func hashForSignature(hashID crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, error) { + if !hashID.Available() { + return nil, nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashID))) } - h := hashId.New() + h := hashID.New() switch sigType { case packet.SigTypeBinary: @@ -372,7 +373,7 @@ func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader, config // CheckDetachedSignatureAndHash performs the same actions as // CheckDetachedSignature and checks that the expected hash functions were used. func CheckDetachedSignatureAndHash(keyring KeyRing, signed, signature io.Reader, expectedHashes []crypto.Hash, config *packet.Config) (signer *Entity, err error) { - var issuerKeyId uint64 + var issuerKeyID uint64 var hashFunc crypto.Hash var sigType packet.SignatureType var keys []Key @@ -394,11 +395,11 @@ func CheckDetachedSignatureAndHash(keyring KeyRing, signed, signature io.Reader, if sig.IssuerKeyId == nil { return nil, errors.StructuralError("signature doesn't have an issuer") } - issuerKeyId = *sig.IssuerKeyId + issuerKeyID = *sig.IssuerKeyId hashFunc = sig.Hash sigType = sig.SigType case *packet.SignatureV3: - issuerKeyId = sig.IssuerKeyId + issuerKeyID = sig.IssuerKeyId hashFunc = sig.Hash sigType = sig.SigType default: @@ -414,7 +415,7 @@ func CheckDetachedSignatureAndHash(keyring KeyRing, signed, signature io.Reader, } } - keys = keyring.KeysByIdUsage(issuerKeyId, packet.KeyFlagSign) + keys = keyring.KeysByIdUsage(issuerKeyID, packet.KeyFlagSign) if len(keys) > 0 { break } diff --git a/openpgp/read_test.go b/openpgp/read_test.go index 3b65af4cf..786be8ffb 100644 --- a/openpgp/read_test.go +++ b/openpgp/read_test.go @@ -102,7 +102,7 @@ func TestDSAHashTruncatation(t *testing.T) { } } -func TestGetKeyById(t *testing.T) { +func TestGetKeyByID(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) keys := kring.KeysById(0xa34d7e18c20c31bb) @@ -297,7 +297,7 @@ func TestSymmetricallyEncrypted(t *testing.T) { } } -func testDetachedSignature(t *testing.T, kring KeyRing, signature io.Reader, sigInput, tag string, expectedSignerKeyId uint64) { +func testDetachedSignature(t *testing.T, kring KeyRing, signature io.Reader, sigInput, tag string, expectedSignerKeyID uint64) { signed := bytes.NewBufferString(sigInput) config := &packet.Config{} signer, err := CheckDetachedSignature(kring, signed, signature, config) @@ -309,16 +309,16 @@ func testDetachedSignature(t *testing.T, kring KeyRing, signature io.Reader, sig t.Errorf("%s: signer is nil", tag) return } - if signer.PrimaryKey.KeyId != expectedSignerKeyId { - t.Errorf("%s: wrong signer got:%x want:%x", tag, signer.PrimaryKey.KeyId, expectedSignerKeyId) + if signer.PrimaryKey.KeyId != expectedSignerKeyID { + t.Errorf("%s: wrong signer got:%x want:%x", tag, signer.PrimaryKey.KeyId, expectedSignerKeyID) } } func TestDetachedSignature(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(testKeys1And2Hex)) - testDetachedSignature(t, kring, readerFromHex(detachedSignatureHex), signedInput, "binary", testKey1KeyId) - testDetachedSignature(t, kring, readerFromHex(detachedSignatureTextHex), signedInput, "text", testKey1KeyId) - testDetachedSignature(t, kring, readerFromHex(detachedSignatureV3TextHex), signedInput, "v3", testKey1KeyId) + testDetachedSignature(t, kring, readerFromHex(detachedSignatureHex), signedInput, "binary", testKey1KeyID) + testDetachedSignature(t, kring, readerFromHex(detachedSignatureTextHex), signedInput, "text", testKey1KeyID) + testDetachedSignature(t, kring, readerFromHex(detachedSignatureV3TextHex), signedInput, "v3", testKey1KeyID) incorrectSignedInput := signedInput + "X" config := &packet.Config{} @@ -333,17 +333,17 @@ func TestDetachedSignature(t *testing.T) { func TestDetachedSignatureDSA(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(dsaTestKeyHex)) - testDetachedSignature(t, kring, readerFromHex(detachedSignatureDSAHex), signedInput, "binary", testKey3KeyId) + testDetachedSignature(t, kring, readerFromHex(detachedSignatureDSAHex), signedInput, "binary", testKey3KeyID) } func TestMultipleSignaturePacketsDSA(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(dsaTestKeyHex)) - testDetachedSignature(t, kring, readerFromHex(missingHashFunctionHex+detachedSignatureDSAHex), signedInput, "binary", testKey3KeyId) + testDetachedSignature(t, kring, readerFromHex(missingHashFunctionHex+detachedSignatureDSAHex), signedInput, "binary", testKey3KeyID) } func TestDetachedSignatureP256(t *testing.T) { kring, _ := ReadKeyRing(readerFromHex(p256TestKeyHex)) - testDetachedSignature(t, kring, readerFromHex(detachedSignatureP256Hex), signedInput, "binary", testKeyP256KeyId) + testDetachedSignature(t, kring, readerFromHex(detachedSignatureP256Hex), signedInput, "binary", testKeyP256KeyID) } func testHashFunctionError(t *testing.T, signatureHex string) { @@ -483,9 +483,9 @@ func TestSignatureV3Message(t *testing.T) { return } -const testKey1KeyId = 0xA34D7E18C20C31BB -const testKey3KeyId = 0x338934250CCC0360 -const testKeyP256KeyId = 0xd44a2c495918513e +const testKey1KeyID = 0xA34D7E18C20C31BB +const testKey3KeyID = 0x338934250CCC0360 +const testKeyP256KeyID = 0xd44a2c495918513e const signedInput = "Signed message\nline 2\nline 3\n" const signedTextInput = "Signed message\r\nline 2\r\nline 3\r\n" diff --git a/openpgp/write.go b/openpgp/write.go index 0f6c12f4f..e72050978 100644 --- a/openpgp/write.go +++ b/openpgp/write.go @@ -78,7 +78,10 @@ func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.S if err != nil { return } - io.Copy(wrappedHash, message) + _, err = io.Copy(wrappedHash, message) + if err != nil { + return + } err = sig.Sign(h, signer.PrivateKey, config) if err != nil { @@ -164,7 +167,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. @@ -205,8 +208,8 @@ func writeAndSign(payload io.WriteCloser, candidateHashes []uint8, signed *Entit } var hash crypto.Hash - for _, hashId := range candidateHashes { - if h, ok := s2k.HashIdToHash(hashId); ok && h.Available() { + for _, hashID := range candidateHashes { + if h, ok := s2k.HashIdToHash(hashID); ok && h.Available() { hash = h break } @@ -214,8 +217,8 @@ func writeAndSign(payload io.WriteCloser, candidateHashes []uint8, signed *Entit // If the hash specified by config is a candidate, we'll use that. if configuredHash := config.Hash(); configuredHash.Available() { - for _, hashId := range candidateHashes { - if h, ok := s2k.HashIdToHash(hashId); ok && h == configuredHash { + for _, hashID := range candidateHashes { + if h, ok := s2k.HashIdToHash(hashID); ok && h == configuredHash { hash = h break } @@ -223,10 +226,10 @@ func writeAndSign(payload io.WriteCloser, candidateHashes []uint8, signed *Entit } if hash == 0 { - hashId := candidateHashes[0] - name, ok := s2k.HashIdToString(hashId) + hashID := candidateHashes[0] + name, ok := s2k.HashIdToString(hashID) if !ok { - name = "#" + strconv.Itoa(int(hashId)) + name = "#" + strconv.Itoa(int(hashID)) } return nil, errors.InvalidArgumentError("cannot encrypt because no candidate hash functions are compiled in. (Wanted " + name + " in this case.)") } diff --git a/openpgp/write_test.go b/openpgp/write_test.go index 18394bae1..999f82aa6 100644 --- a/openpgp/write_test.go +++ b/openpgp/write_test.go @@ -23,7 +23,7 @@ func TestSignDetached(t *testing.T) { t.Error(err) } - testDetachedSignature(t, kring, out, signedInput, "check", testKey1KeyId) + testDetachedSignature(t, kring, out, signedInput, "check", testKey1KeyID) } func TestSignTextDetached(t *testing.T) { @@ -35,7 +35,7 @@ func TestSignTextDetached(t *testing.T) { t.Error(err) } - testDetachedSignature(t, kring, out, signedInput, "check", testKey1KeyId) + testDetachedSignature(t, kring, out, signedInput, "check", testKey1KeyID) } func TestSignDetachedDSA(t *testing.T) { @@ -47,7 +47,7 @@ func TestSignDetachedDSA(t *testing.T) { t.Error(err) } - testDetachedSignature(t, kring, out, signedInput, "check", testKey3KeyId) + testDetachedSignature(t, kring, out, signedInput, "check", testKey3KeyID) } func TestSignDetachedP256(t *testing.T) { @@ -61,7 +61,7 @@ func TestSignDetachedP256(t *testing.T) { t.Error(err) } - testDetachedSignature(t, kring, out, signedInput, "check", testKeyP256KeyId) + testDetachedSignature(t, kring, out, signedInput, "check", testKeyP256KeyID) } func TestNewEntity(t *testing.T) { @@ -236,9 +236,9 @@ func TestEncryption(t *testing.T) { testTime, _ := time.Parse("2006-01-02", "2013-07-01") if test.isSigned { signKey, _ := kring[0].SigningKey(testTime) - expectedKeyId := signKey.PublicKey.KeyId - if md.SignedByKeyId != expectedKeyId { - t.Errorf("#%d: message signed by wrong key id, got: %v, want: %v", i, *md.SignedBy, expectedKeyId) + expectedKeyID := signKey.PublicKey.KeyId + if md.SignedByKeyId != expectedKeyID { + t.Errorf("#%d: message signed by wrong key id, got: %v, want: %v", i, *md.SignedBy, expectedKeyID) } if md.SignedBy == nil { t.Errorf("#%d: failed to find the signing Entity", i) @@ -252,9 +252,9 @@ func TestEncryption(t *testing.T) { } encryptKey, _ := kring[0].EncryptionKey(testTime) - expectedKeyId := encryptKey.PublicKey.KeyId - if len(md.EncryptedToKeyIds) != 1 || md.EncryptedToKeyIds[0] != expectedKeyId { - t.Errorf("#%d: expected message to be encrypted to %v, but got %#v", i, expectedKeyId, md.EncryptedToKeyIds) + expectedKeyID := encryptKey.PublicKey.KeyId + if len(md.EncryptedToKeyIds) != 1 || md.EncryptedToKeyIds[0] != expectedKeyID { + t.Errorf("#%d: expected message to be encrypted to %v, but got %#v", i, expectedKeyID, md.EncryptedToKeyIds) } if string(plaintext) != message { @@ -334,9 +334,9 @@ func TestSigning(t *testing.T) { testTime, _ := time.Parse("2006-01-02", "2013-07-01") signKey, _ := kring[0].SigningKey(testTime) - expectedKeyId := signKey.PublicKey.KeyId - if md.SignedByKeyId != expectedKeyId { - t.Errorf("#%d: message signed by wrong key id, got: %v, want: %v", i, *md.SignedBy, expectedKeyId) + expectedKeyID := signKey.PublicKey.KeyId + if md.SignedByKeyId != expectedKeyID { + t.Errorf("#%d: message signed by wrong key id, got: %v, want: %v", i, *md.SignedBy, expectedKeyID) } if md.SignedBy == nil { t.Errorf("#%d: failed to find the signing Entity", i) From 5e378cfae85f10335f19da5f7884117046108eca Mon Sep 17 00:00:00 2001 From: tal-botvinnik Date: Wed, 28 Aug 2019 12:01:43 -0400 Subject: [PATCH 2/7] MetaGoLinted aes, armor, canonical_text.go, clearsign, ecdh, keys.go, read.go, write.go --- openpgp/ecdh/x25519.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/openpgp/ecdh/x25519.go b/openpgp/ecdh/x25519.go index e468672d7..f00985e43 100644 --- a/openpgp/ecdh/x25519.go +++ b/openpgp/ecdh/x25519.go @@ -73,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 { @@ -105,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 { From d3868d13c9a0113985162d4013e5290fe530ed7c Mon Sep 17 00:00:00 2001 From: tal-botvinnik Date: Wed, 28 Aug 2019 12:18:59 -0400 Subject: [PATCH 3/7] MetaGoLinted errors, s2k --- openpgp/errors/errors.go | 6 ++++++ openpgp/s2k/s2k.go | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/openpgp/errors/errors.go b/openpgp/errors/errors.go index f05964ad6..37550c7ad 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/s2k/s2k.go b/openpgp/s2k/s2k.go index ae72e7b77..a59f31814 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 { From c5428b51f326958a70ab56c5c2e712b727bdce79 Mon Sep 17 00:00:00 2001 From: tal-botvinnik Date: Wed, 28 Aug 2019 12:30:47 -0400 Subject: [PATCH 4/7] Lint: Ignore redundante error checking in _test files --- openpgp/armor/armor_test.go | 5 +---- openpgp/ecdh/ecdh.go | 3 ++- openpgp/keys_test.go | 3 --- openpgp/read.go | 1 + 4 files changed, 4 insertions(+), 8 deletions(-) diff --git a/openpgp/armor/armor_test.go b/openpgp/armor/armor_test.go index 769172bcc..9334e94e9 100644 --- a/openpgp/armor/armor_test.go +++ b/openpgp/armor/armor_test.go @@ -47,10 +47,7 @@ func TestDecodeEncode(t *testing.T) { if err != nil { t.Error(err) } - errClose := w.Close() - if errClose != nil { - t.Errorf("error closing the io.WriteCloser instance") - } + w.Close() if !bytes.Equal(buf.Bytes(), []byte(armorExample1)) { t.Errorf("got: %s\nwant: %s", string(buf.Bytes()), armorExample1) diff --git a/openpgp/ecdh/ecdh.go b/openpgp/ecdh/ecdh.go index 9fbaef805..7b1b5b06c 100644 --- a/openpgp/ecdh/ecdh.go +++ b/openpgp/ecdh/ecdh.go @@ -94,7 +94,8 @@ func Encrypt(random io.Reader, pub *PublicKey, msg, curveOID, fingerprint []byte } -// Decrypt decrypts the given message with the given private key. +// 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/keys_test.go b/openpgp/keys_test.go index d739cd0d1..8a60cb88c 100644 --- a/openpgp/keys_test.go +++ b/openpgp/keys_test.go @@ -489,9 +489,6 @@ func TestNewEntityPublicSerialization(t *testing.T) { } serializedEntity := bytes.NewBuffer(nil) err = entity.Serialize(serializedEntity) - if err != nil { - t.Fatal(err) - } _, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes()))) if err != nil { diff --git a/openpgp/read.go b/openpgp/read.go index 44876f30f..7852a28ed 100644 --- a/openpgp/read.go +++ b/openpgp/read.go @@ -10,6 +10,7 @@ import ( "hash" "io" "strconv" + "golang.org/x/crypto/openpgp/armor" "golang.org/x/crypto/openpgp/errors" "golang.org/x/crypto/openpgp/packet" From 530f2ff6f44cd0da80679a04dc6b575620ff3c18 Mon Sep 17 00:00:00 2001 From: tal-botvinnik Date: Wed, 28 Aug 2019 13:05:24 -0400 Subject: [PATCH 5/7] Remove extra linebreak --- openpgp/armor/encode.go | 1 - 1 file changed, 1 deletion(-) diff --git a/openpgp/armor/encode.go b/openpgp/armor/encode.go index da1c594bd..2f1a4f0c7 100644 --- a/openpgp/armor/encode.go +++ b/openpgp/armor/encode.go @@ -119,7 +119,6 @@ func (e *encoding) Close() (err error) { return } - var checksumBytes [3]byte checksumBytes[0] = byte(e.crc >> 16) checksumBytes[1] = byte(e.crc >> 8) From 8c0275f3c0b637cf0c714ba17f1b9ab4acbbbede Mon Sep 17 00:00:00 2001 From: tal-botvinnik Date: Wed, 28 Aug 2019 13:45:04 -0400 Subject: [PATCH 6/7] Ignoring test file --- openpgp/keys_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openpgp/keys_test.go b/openpgp/keys_test.go index 8a60cb88c..b0b9744a3 100644 --- a/openpgp/keys_test.go +++ b/openpgp/keys_test.go @@ -488,7 +488,7 @@ func TestNewEntityPublicSerialization(t *testing.T) { t.Fatal(err) } serializedEntity := bytes.NewBuffer(nil) - err = entity.Serialize(serializedEntity) + entity.Serialize(serializedEntity) _, err = ReadEntity(packet.NewReader(bytes.NewBuffer(serializedEntity.Bytes()))) if err != nil { From 31d537d68f85a9173c1b3ca1f22dd20e73caf7d2 Mon Sep 17 00:00:00 2001 From: tal-botvinnik Date: Thu, 29 Aug 2019 06:34:38 -0400 Subject: [PATCH 7/7] Start linting openpgp/packet --- openpgp/packet/compressed.go | 1 + openpgp/packet/config.go | 10 ++++++++++ openpgp/packet/encrypted_key_test.go | 6 +++--- openpgp/packet/opaque.go | 5 ++++- openpgp/packet/packet.go | 8 ++++++-- openpgp/packet/private_key.go | 14 ++++++++++++++ openpgp/packet/public_key.go | 29 ++++++++++++++++------------ openpgp/packet/public_key_test.go | 14 +++++++------- openpgp/packet/public_key_v3.go | 13 +++++++------ openpgp/packet/public_key_v3_test.go | 14 +++++++------- openpgp/packet/reader.go | 1 + openpgp/packet/signature.go | 18 ++++++++--------- openpgp/packet/signature_v3.go | 4 ++-- openpgp/packet/userattribute.go | 1 + openpgp/packet/userid.go | 8 ++++---- openpgp/packet/userid_test.go | 20 +++++++++---------- openpgp/read.go | 1 + 17 files changed, 104 insertions(+), 63 deletions(-) diff --git a/openpgp/packet/compressed.go b/openpgp/packet/compressed.go index e8f0b5caa..0f2d2fc84 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 cb8df0707..bc49daf96 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_test.go b/openpgp/packet/encrypted_key_test.go index 167033d1c..dd50e1ac7 100644 --- a/openpgp/packet/encrypted_key_test.go +++ b/openpgp/packet/encrypted_key_test.go @@ -85,11 +85,11 @@ func TestDecryptingEncryptedKey(t *testing.T) { func TestEncryptingEncryptedKey(t *testing.T) { key := []byte{1, 2, 3, 4} const expectedKeyHex = "01020304" - const keyId = 0x2a67d68660df41c7 + const keyID = 0x2a67d68660df41c7 pub := &PublicKey{ PublicKey: &encryptedKeyPub, - KeyId: keyId, + KeyId: keyID, PubKeyAlgo: PubKeyAlgoRSA, } @@ -110,7 +110,7 @@ func TestEncryptingEncryptedKey(t *testing.T) { return } - if ek.KeyId != keyId || ek.Algo != PubKeyAlgoRSA { + if ek.KeyId != keyID || ek.Algo != PubKeyAlgoRSA { t.Errorf("unexpected EncryptedKey contents: %#v", ek) return } 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 ce6452708..5772627ef 100644 --- a/openpgp/packet/packet.go +++ b/openpgp/packet/packet.go @@ -312,7 +312,7 @@ const ( packetTypeCompressed packetType = 8 packetTypeSymmetricallyEncrypted packetType = 9 packetTypeLiteralData packetType = 11 - packetTypeUserId packetType = 13 + packetTypeUserID packetType = 13 packetTypePublicSubkey packetType = 14 packetTypeUserAttribute packetType = 17 packetTypeSymmetricallyEncryptedMDC packetType = 18 @@ -380,7 +380,7 @@ func Read(r io.Reader) (p Packet, err error) { err = errors.UnsupportedError("Symmetrically encrypted packets without MDC are not supported") case packetTypeLiteralData: p = new(LiteralData) - case packetTypeUserId: + case packetTypeUserID: p = new(UserId) case packetTypeUserAttribute: p = new(UserAttribute) @@ -404,6 +404,7 @@ func Read(r io.Reader) (p Packet, err error) { // signature. See RFC 4880, section 5.2.1. type SignatureType uint8 +// Signature types. const ( SigTypeBinary SignatureType = 0 SigTypeText = 1 @@ -423,6 +424,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 +464,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 +505,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 28e24d588..c74224d6e 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) diff --git a/openpgp/packet/public_key.go b/openpgp/packet/public_key.go index 81589d2b2..b778f063a 100644 --- a/openpgp/packet/public_key.go +++ b/openpgp/packet/public_key.go @@ -71,7 +71,7 @@ func NewRSAPublicKey(creationTime time.Time, pub *rsa.PublicKey) *PublicKey { e: new(encoding.MPI).SetBig(big.NewInt(int64(pub.E))), } - pk.setFingerPrintAndKeyId() + pk.setFingerprintAndKeyID() return pk } @@ -87,7 +87,7 @@ func NewDSAPublicKey(creationTime time.Time, pub *dsa.PublicKey) *PublicKey { y: new(encoding.MPI).SetBig(pub.Y), } - pk.setFingerPrintAndKeyId() + pk.setFingerprintAndKeyID() return pk } @@ -102,10 +102,11 @@ func NewElGamalPublicKey(creationTime time.Time, pub *elgamal.PublicKey) *Public y: new(encoding.MPI).SetBig(pub.Y), } - pk.setFingerPrintAndKeyId() + pk.setFingerprintAndKeyID() 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, @@ -119,10 +120,11 @@ func NewECDSAPublicKey(creationTime time.Time, pub *ecdsa.PublicKey) *PublicKey panic("unknown elliptic curve") } pk.oid = curveInfo.Oid - pk.setFingerPrintAndKeyId() + pk.setFingerprintAndKeyID() 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 @@ -150,10 +152,11 @@ func NewECDHPublicKey(creationTime time.Time, pub *ecdh.PublicKey) *PublicKey { panic("unknown elliptic curve") } pk.oid = curveInfo.Oid - pk.setFingerPrintAndKeyId() + pk.setFingerprintAndKeyID() 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{ @@ -165,7 +168,7 @@ func NewEdDSAPublicKey(creationTime time.Time, pub ed25519.PublicKey) *PublicKey p: encoding.NewMPI(append([]byte{0x40}, pub...)), } - pk.setFingerPrintAndKeyId() + pk.setFingerprintAndKeyID() return pk } @@ -201,11 +204,11 @@ func (pk *PublicKey) parse(r io.Reader) (err error) { return } - pk.setFingerPrintAndKeyId() + pk.setFingerprintAndKeyID() return } -func (pk *PublicKey) setFingerPrintAndKeyId() { +func (pk *PublicKey) setFingerprintAndKeyID() { // RFC 4880, section 12.2 fingerPrint := sha1.New() pk.SerializeSignaturePrefix(fingerPrint) @@ -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 @@ -737,9 +742,9 @@ func (pk *PublicKey) VerifyRevocationSignature(sig *Signature) (err error) { return pk.VerifySignature(h, sig) } -// userIdSignatureHash returns a Hash of the message that needs to be signed +// userIDSignatureHash returns a Hash of the message that needs to be signed // to assert that pk is a valid key for id. -func userIdSignatureHash(id string, pk *PublicKey, hashFunc crypto.Hash) (h hash.Hash, err error) { +func userIDSignatureHash(id string, pk *PublicKey, hashFunc crypto.Hash) (h hash.Hash, err error) { if !hashFunc.Available() { return nil, errors.UnsupportedError("hash function") } @@ -764,7 +769,7 @@ func userIdSignatureHash(id string, pk *PublicKey, hashFunc crypto.Hash) (h hash // VerifyUserIdSignature returns nil iff sig is a valid signature, made by this // public key, that id is the identity of pub. func (pk *PublicKey) VerifyUserIdSignature(id string, pub *PublicKey, sig *Signature) (err error) { - h, err := userIdSignatureHash(id, pub, sig.Hash) + h, err := userIDSignatureHash(id, pub, sig.Hash) if err != nil { return err } @@ -774,7 +779,7 @@ func (pk *PublicKey) VerifyUserIdSignature(id string, pub *PublicKey, sig *Signa // VerifyUserIdSignatureV3 returns nil iff sig is a valid signature, made by this // public key, that id is the identity of pub. func (pk *PublicKey) VerifyUserIdSignatureV3(id string, pub *PublicKey, sig *SignatureV3) (err error) { - h, err := userIdSignatureV3Hash(id, pub, sig.Hash) + h, err := userIDSignatureV3Hash(id, pub, sig.Hash) if err != nil { return err } diff --git a/openpgp/packet/public_key_test.go b/openpgp/packet/public_key_test.go index 26f52e022..5bda0729b 100644 --- a/openpgp/packet/public_key_test.go +++ b/openpgp/packet/public_key_test.go @@ -19,9 +19,9 @@ var pubKeyTests = []struct { hexFingerprint string creationTime time.Time pubKeyAlgo PublicKeyAlgorithm - keyId uint64 - keyIdString string - keyIdShort string + keyID uint64 + keyIDString string + keyIDShort string }{ {rsaPkDataHex, rsaFingerprintHex, time.Unix(0x4d3c5c10, 0), PubKeyAlgoRSA, 0xa34d7e18c20c31bb, "A34D7E18C20C31BB", "C20C31BB"}, {dsaPkDataHex, dsaFingerprintHex, time.Unix(0x4d432f89, 0), PubKeyAlgoDSA, 0x8e8fbe54062f19ed, "8E8FBE54062F19ED", "062F19ED"}, @@ -52,13 +52,13 @@ func TestPublicKeyRead(t *testing.T) { if !bytes.Equal(expectedFingerprint, pk.Fingerprint[:]) { t.Errorf("#%d: bad fingerprint got:%x want:%x", i, pk.Fingerprint[:], expectedFingerprint) } - if pk.KeyId != test.keyId { - t.Errorf("#%d: bad keyid got:%x want:%x", i, pk.KeyId, test.keyId) + if pk.KeyId != test.keyID { + t.Errorf("#%d: bad keyid got:%x want:%x", i, pk.KeyId, test.keyID) } - if g, e := pk.KeyIdString(), test.keyIdString; g != e { + if g, e := pk.KeyIdString(), test.keyIDString; g != e { t.Errorf("#%d: bad KeyIdString got:%q want:%q", i, g, e) } - if g, e := pk.KeyIdShortString(), test.keyIdShort; g != e { + if g, e := pk.KeyIdShortString(), test.keyIDShort; g != e { t.Errorf("#%d: bad KeyIdShortString got:%q want:%q", i, g, e) } } diff --git a/openpgp/packet/public_key_v3.go b/openpgp/packet/public_key_v3.go index dcce323ba..e05181d3b 100644 --- a/openpgp/packet/public_key_v3.go +++ b/openpgp/packet/public_key_v3.go @@ -47,7 +47,7 @@ func newRSAPublicKeyV3(creationTime time.Time, pub *rsa.PublicKey) *PublicKeyV3 e: new(encoding.MPI).SetBig(big.NewInt(int64(pub.E))), } - pk.setFingerPrintAndKeyId() + pk.setFingerprintAndKeyID() return pk } @@ -73,11 +73,11 @@ func (pk *PublicKeyV3) parse(r io.Reader) (err error) { return } - pk.setFingerPrintAndKeyId() + pk.setFingerprintAndKeyID() return } -func (pk *PublicKeyV3) setFingerPrintAndKeyId() { +func (pk *PublicKeyV3) setFingerprintAndKeyID() { // RFC 4880, section 12.2 fingerPrint := md5.New() fingerPrint.Write(pk.n.Bytes()) @@ -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 @@ -228,7 +229,7 @@ func (pk *PublicKeyV3) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (er // VerifyUserIdSignatureV3 returns nil iff sig is a valid signature, made by this // public key, that id is the identity of pub. func (pk *PublicKeyV3) VerifyUserIdSignatureV3(id string, pub *PublicKeyV3, sig *SignatureV3) (err error) { - h, err := userIdSignatureV3Hash(id, pk, sig.Hash) + h, err := userIDSignatureV3Hash(id, pk, sig.Hash) if err != nil { return err } @@ -245,9 +246,9 @@ func (pk *PublicKeyV3) VerifyKeySignatureV3(signed *PublicKeyV3, sig *SignatureV return pk.VerifySignatureV3(h, sig) } -// userIdSignatureV3Hash returns a Hash of the message that needs to be signed +// userIDSignatureV3Hash returns a Hash of the message that needs to be signed // to assert that pk is a valid key for id. -func userIdSignatureV3Hash(id string, pk signingKey, hfn crypto.Hash) (h hash.Hash, err error) { +func userIDSignatureV3Hash(id string, pk signingKey, hfn crypto.Hash) (h hash.Hash, err error) { if !hfn.Available() { return nil, errors.UnsupportedError("hash function") } diff --git a/openpgp/packet/public_key_v3_test.go b/openpgp/packet/public_key_v3_test.go index e06405904..e0af96c96 100644 --- a/openpgp/packet/public_key_v3_test.go +++ b/openpgp/packet/public_key_v3_test.go @@ -15,9 +15,9 @@ var pubKeyV3Test = struct { hexFingerprint string creationTime time.Time pubKeyAlgo PublicKeyAlgorithm - keyId uint64 - keyIdString string - keyIdShort string + keyID uint64 + keyIDString string + keyIDShort string }{ "103BECF5BD1E837C89D19E98487767F7", time.Unix(779753634, 0), @@ -46,13 +46,13 @@ func TestPublicKeyV3Read(t *testing.T) { if !bytes.Equal(expectedFingerprint, pk.Fingerprint[:]) { t.Errorf("#%d: bad fingerprint got:%x want:%x", i, pk.Fingerprint[:], expectedFingerprint) } - if pk.KeyId != test.keyId { - t.Errorf("#%d: bad keyid got:%x want:%x", i, pk.KeyId, test.keyId) + if pk.KeyId != test.keyID { + t.Errorf("#%d: bad keyid got:%x want:%x", i, pk.KeyId, test.keyID) } - if g, e := pk.KeyIdString(), test.keyIdString; g != e { + if g, e := pk.KeyIdString(), test.keyIDString; g != e { t.Errorf("#%d: bad KeyIdString got:%q want:%q", i, g, e) } - if g, e := pk.KeyIdShortString(), test.keyIdShort; g != e { + if g, e := pk.KeyIdShortString(), test.keyIDShort; g != e { t.Errorf("#%d: bad KeyIdShortString got:%q want:%q", i, g, e) } } diff --git a/openpgp/packet/reader.go b/openpgp/packet/reader.go index 34bc7c613..7e704d0fb 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 960094733..a3905d921 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 @@ -219,7 +219,7 @@ const ( issuerSubpacket signatureSubpacketType = 16 prefHashAlgosSubpacket signatureSubpacketType = 21 prefCompressionSubpacket signatureSubpacketType = 22 - primaryUserIdSubpacket signatureSubpacketType = 25 + primaryUserIDSubpacket signatureSubpacketType = 25 keyFlagsSubpacket signatureSubpacketType = 27 reasonForRevocationSubpacket signatureSubpacketType = 29 featuresSubpacket signatureSubpacketType = 30 @@ -330,7 +330,7 @@ func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (r } sig.PreferredCompression = make([]byte, len(subpacket)) copy(sig.PreferredCompression, subpacket) - case primaryUserIdSubpacket: + case primaryUserIDSubpacket: // 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) } } @@ -604,7 +604,7 @@ func unwrapECDSASig(b []byte) (r, s *big.Int, err error) { // Serialize to write it out. // If config is nil, sensible defaults will be used. func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey, config *Config) error { - h, err := userIdSignatureHash(id, pub, sig.Hash) + h, err := userIDSignatureHash(id, pub, sig.Hash) if err != nil { return err } @@ -715,9 +715,9 @@ func (sig *Signature) buildSubpackets() (subpackets []outputSubpacket) { subpackets = append(subpackets, outputSubpacket{true, creationTimeSubpacket, false, creationTime}) if sig.IssuerKeyId != nil { - keyId := make([]byte, 8) - binary.BigEndian.PutUint64(keyId, *sig.IssuerKeyId) - subpackets = append(subpackets, outputSubpacket{true, issuerSubpacket, false, keyId}) + keyID := make([]byte, 8) + binary.BigEndian.PutUint64(keyID, *sig.IssuerKeyId) + subpackets = append(subpackets, outputSubpacket{true, issuerSubpacket, false, keyID}) } if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 { @@ -754,7 +754,7 @@ func (sig *Signature) buildSubpackets() (subpackets []outputSubpacket) { } if sig.IsPrimaryId != nil && *sig.IsPrimaryId { - subpackets = append(subpackets, outputSubpacket{true, primaryUserIdSubpacket, false, []byte{1}}) + subpackets = append(subpackets, outputSubpacket{true, primaryUserIDSubpacket, false, []byte{1}}) } if len(sig.PreferredSymmetric) > 0 { diff --git a/openpgp/packet/signature_v3.go b/openpgp/packet/signature_v3.go index c6e8d72a6..e9ed2bac6 100644 --- a/openpgp/packet/signature_v3.go +++ b/openpgp/packet/signature_v3.go @@ -125,11 +125,11 @@ func (sig *SignatureV3) Serialize(w io.Writer) (err error) { // Write public key algorithm, hash ID, and hash value buf[0] = byte(sig.PubKeyAlgo) - hashId, ok := s2k.HashToHashId(sig.Hash) + hashID, ok := s2k.HashToHashId(sig.Hash) if !ok { return errors.UnsupportedError(fmt.Sprintf("hash function %v", sig.Hash)) } - buf[1] = hashId + buf[1] = hashID copy(buf[2:4], sig.HashTag[:]) if _, err = w.Write(buf[:4]); err != nil { return diff --git a/openpgp/packet/userattribute.go b/openpgp/packet/userattribute.go index d19ffbc78..250a3a0a7 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/packet/userid.go b/openpgp/packet/userid.go index d6bea7d4a..ea846e826 100644 --- a/openpgp/packet/userid.go +++ b/openpgp/packet/userid.go @@ -71,14 +71,14 @@ func (uid *UserId) parse(r io.Reader) (err error) { return } uid.Id = string(b) - uid.Name, uid.Comment, uid.Email = parseUserId(uid.Id) + uid.Name, uid.Comment, uid.Email = parseUserID(uid.Id) return } // Serialize marshals uid to w in the form of an OpenPGP packet, including // header. func (uid *UserId) Serialize(w io.Writer) error { - err := serializeHeader(w, packetTypeUserId, len(uid.Id)) + err := serializeHeader(w, packetTypeUserID, len(uid.Id)) if err != nil { return err } @@ -86,9 +86,9 @@ func (uid *UserId) Serialize(w io.Writer) error { return err } -// parseUserId extracts the name, comment and email from a user id string that +// parseUserID extracts the name, comment and email from a user id string that // is formatted as "Full Name (Comment) ". -func parseUserId(id string) (name, comment, email string) { +func parseUserID(id string) (name, comment, email string) { var n, c, e struct { start, end int } diff --git a/openpgp/packet/userid_test.go b/openpgp/packet/userid_test.go index 296819389..6649625db 100644 --- a/openpgp/packet/userid_test.go +++ b/openpgp/packet/userid_test.go @@ -8,7 +8,7 @@ import ( "testing" ) -var userIdTests = []struct { +var userIDTests = []struct { id string name, comment, email string }{ @@ -26,9 +26,9 @@ var userIdTests = []struct { {"René Descartes (العربي)", "René Descartes", "العربي", ""}, } -func TestParseUserId(t *testing.T) { - for i, test := range userIdTests { - name, comment, email := parseUserId(test.id) +func TestParseUserID(t *testing.T) { + for i, test := range userIDTests { + name, comment, email := parseUserID(test.id) if name != test.name { t.Errorf("%d: name mismatch got:%s want:%s", i, name, test.name) } @@ -41,7 +41,7 @@ func TestParseUserId(t *testing.T) { } } -var newUserIdTests = []struct { +var newUserIDTests = []struct { name, comment, email, id string }{ {"foo", "", "", "foo"}, @@ -53,8 +53,8 @@ var newUserIdTests = []struct { {"foo", "bar", "baz", "foo (bar) "}, } -func TestNewUserId(t *testing.T) { - for i, test := range newUserIdTests { +func TestNewUserID(t *testing.T) { + for i, test := range newUserIDTests { uid := NewUserId(test.name, test.comment, test.email) if uid == nil { t.Errorf("#%d: returned nil", i) @@ -66,7 +66,7 @@ func TestNewUserId(t *testing.T) { } } -var invalidNewUserIdTests = []struct { +var invalidNewUserIDTests = []struct { name, comment, email string }{ {"foo(", "", ""}, @@ -78,8 +78,8 @@ var invalidNewUserIdTests = []struct { {"", "", "baz\x00"}, } -func TestNewUserIdWithInvalidInput(t *testing.T) { - for i, test := range invalidNewUserIdTests { +func TestNewUserIDWithInvalidInput(t *testing.T) { + for i, test := range invalidNewUserIDTests { if uid := NewUserId(test.name, test.comment, test.email); uid != nil { t.Errorf("#%d: returned non-nil value: %#v", i, uid) } diff --git a/openpgp/read.go b/openpgp/read.go index 7852a28ed..34c262d10 100644 --- a/openpgp/read.go +++ b/openpgp/read.go @@ -7,6 +7,7 @@ package openpgp // import "golang.org/x/crypto/openpgp" import ( "crypto" + _ "crypto/sha256" "hash" "io" "strconv"