openpgp: support creating signatures compatible with 'gpg --sign'.

This is neither a '--clearsign' nor a '--detach-sign' which are already
supported.  Verification of these signatures is already supported by
ReadMessage.

The code shares a lot with standard encrypt/sign, so mostly a
refactoring of 'Encrypt' to allow use of the code path without
actually doing a signing.

Change-Id: I5bb7487134ffcf1189ed74e28dbbbe1c01b356d1
GitHub-Last-Rev: 01162222600a4a2a230a444387b33883faf596ec
GitHub-Pull-Request: golang/crypto#50
Reviewed-on: https://go-review.googlesource.com/116017
Reviewed-by: Filippo Valsorda <filippo@golang.org>
This commit is contained in:
Wilfried Teiken
2018-07-18 16:05:20 +00:00
committed by Filippo Valsorda
parent a49355c7e3
commit a214413485
2 changed files with 195 additions and 68 deletions
+89
View File
@@ -271,3 +271,92 @@ func TestEncryption(t *testing.T) {
}
}
}
var testSigningTests = []struct {
keyRingHex string
}{
{
testKeys1And2PrivateHex,
},
{
dsaElGamalTestKeysHex,
},
}
func TestSigning(t *testing.T) {
for i, test := range testSigningTests {
kring, _ := ReadKeyRing(readerFromHex(test.keyRingHex))
passphrase := []byte("passphrase")
for _, entity := range kring {
if entity.PrivateKey != nil && entity.PrivateKey.Encrypted {
err := entity.PrivateKey.Decrypt(passphrase)
if err != nil {
t.Errorf("#%d: failed to decrypt key", i)
}
}
for _, subkey := range entity.Subkeys {
if subkey.PrivateKey != nil && subkey.PrivateKey.Encrypted {
err := subkey.PrivateKey.Decrypt(passphrase)
if err != nil {
t.Errorf("#%d: failed to decrypt subkey", i)
}
}
}
}
signed := kring[0]
buf := new(bytes.Buffer)
w, err := Sign(buf, signed, nil /* no hints */, nil)
if err != nil {
t.Errorf("#%d: error in Sign: %s", i, err)
continue
}
const message = "testing"
_, err = w.Write([]byte(message))
if err != nil {
t.Errorf("#%d: error writing plaintext: %s", i, err)
continue
}
err = w.Close()
if err != nil {
t.Errorf("#%d: error closing WriteCloser: %s", i, err)
continue
}
md, err := ReadMessage(buf, kring, nil /* no prompt */, nil)
if err != nil {
t.Errorf("#%d: error reading message: %s", i, err)
continue
}
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)
}
if md.SignedBy == nil {
t.Errorf("#%d: failed to find the signing Entity", i)
}
plaintext, err := ioutil.ReadAll(md.UnverifiedBody)
if err != nil {
t.Errorf("#%d: error reading contents: %v", i, err)
continue
}
if string(plaintext) != message {
t.Errorf("#%d: got: %q, want: %q", i, plaintext, message)
}
if md.SignatureError != nil {
t.Errorf("#%d: signature error: %q", i, md.SignatureError)
}
if md.Signature == nil {
t.Error("signature missing")
}
}
}