From 3e2271302c085ee7a901f58dbc969e4bb766ab98 Mon Sep 17 00:00:00 2001 From: Adam Langley Date: Sat, 25 Oct 2014 11:19:44 -0700 Subject: [PATCH] go.crypto/openpgp: don't corrupt encrypted private key when decryption fails. Since the decryption was done in place, if an incorrect key was given, the encrypted data would be corrupted. Fixes golang/go#8439. R=bradfitz CC=golang-codereviews https://golang.org/cl/115550043 --- openpgp/packet/private_key.go | 4 ++-- openpgp/packet/private_key_test.go | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/openpgp/packet/private_key.go b/openpgp/packet/private_key.go index 98cc14b..99b628f 100644 --- a/openpgp/packet/private_key.go +++ b/openpgp/packet/private_key.go @@ -196,8 +196,8 @@ func (pk *PrivateKey) Decrypt(passphrase []byte) error { block := pk.cipher.new(key) cfb := cipher.NewCFBDecrypter(block, pk.iv) - data := pk.encryptedData - cfb.XORKeyStream(data, data) + data := make([]byte, len(pk.encryptedData)) + cfb.XORKeyStream(data, pk.encryptedData) if pk.sha1Checksum { if len(data) < sha1.Size { diff --git a/openpgp/packet/private_key_test.go b/openpgp/packet/private_key_test.go index 35d8951..6a6197a 100644 --- a/openpgp/packet/private_key_test.go +++ b/openpgp/packet/private_key_test.go @@ -38,6 +38,12 @@ func TestPrivateKeyRead(t *testing.T) { continue } + err = privKey.Decrypt([]byte("wrong password")) + if err == nil { + t.Errorf("#%d: decrypted with incorrect key", i) + continue + } + err = privKey.Decrypt([]byte("testing")) if err != nil { t.Errorf("#%d: failed to decrypt: %s", i, err)