Fix encrypted image support

When encrypting images, the hash was being calculated using the
encrypted image body. This is invalid for MCUboot, the hash must be
calculated first from the plain body and afterwards this body must be
encrypted. This commit fixes the behavior.

Signed-off-by: Fabio Utzig <utzig@apache.org>
diff --git a/image/create.go b/image/create.go
index 129baaa..0217f2c 100644
--- a/image/create.go
+++ b/image/create.go
@@ -553,19 +553,28 @@
 	img.Header.ProtSz = calcProtSize(img.ProtTlvs)
 
 	// Followed by data.
+	var hashBytes []byte
+	var err error
 	if ic.PlainSecret != nil {
+		// For encrypted images, must calculate the hash with the plain
+		// body and encrypt the payload afterwards
+		img.Body = append(img.Body, ic.Body...)
+		hashBytes, err = img.CalcHash(ic.InitialHash)
+		if err != nil {
+			return img, err
+		}
 		encBody, err := sec.EncryptAES(ic.Body, ic.PlainSecret, ic.Nonce)
 		if err != nil {
 			return img, err
 		}
+		img.Body = nil
 		img.Body = append(img.Body, encBody...)
 	} else {
 		img.Body = append(img.Body, ic.Body...)
-	}
-
-	hashBytes, err := img.CalcHash(ic.InitialHash)
-	if err != nil {
-		return img, err
+		hashBytes, err = img.CalcHash(ic.InitialHash)
+		if err != nil {
+			return img, err
+		}
 	}
 
 	// Hash TLV.