From 62071cde4232c4dde2564fdc3ba6e70bd1edf7c4 Mon Sep 17 00:00:00 2001 From: Dimitri John Ledkov Date: Fri, 13 Sep 2024 10:59:50 -0500 Subject: [PATCH] Upgrade to new hash-agnostic APIs for sign and verify And also prepare for a future switch to SHA256 --- pkg/build/sign.go | 17 ++++++++++------- pkg/sign/apk_test.go | 22 +++++++++++----------- 2 files changed, 21 insertions(+), 18 deletions(-) diff --git a/pkg/build/sign.go b/pkg/build/sign.go index e8ce72ad6..9d648b142 100644 --- a/pkg/build/sign.go +++ b/pkg/build/sign.go @@ -5,8 +5,7 @@ import ( "bytes" "context" - //nolint:gosec - "crypto/sha1" + "crypto" "fmt" "os" "path/filepath" @@ -74,18 +73,22 @@ type KeyApkSigner struct { KeyPassphrase string } +const melangeApkDigest = crypto.SHA1 + +// const melangeApkDigest = crypto.SHA256 + func (s KeyApkSigner) Sign(control []byte) ([]byte, error) { - //nolint:gosec - digest := sha1.New() - _, err := digest.Write(control) + controlDigest, err := sign.HashData(control, melangeApkDigest) if err != nil { return nil, err } - - return sign.RSASignSHA1Digest(digest.Sum(nil), s.KeyFile, s.KeyPassphrase) + return sign.RSASignDigest(controlDigest, melangeApkDigest, s.KeyFile, s.KeyPassphrase) } func (s KeyApkSigner) SignatureName() string { + if melangeApkDigest == crypto.SHA256 { + return fmt.Sprintf(".SIGN.RSA256.%s.pub", filepath.Base(s.KeyFile)) + } return fmt.Sprintf(".SIGN.RSA.%s.pub", filepath.Base(s.KeyFile)) } diff --git a/pkg/sign/apk_test.go b/pkg/sign/apk_test.go index 833466ec8..45fb0538f 100644 --- a/pkg/sign/apk_test.go +++ b/pkg/sign/apk_test.go @@ -19,7 +19,7 @@ import ( "bytes" "compress/gzip" "context" - "crypto/sha1" + "crypto" "fmt" "io" "os" @@ -54,26 +54,26 @@ func TestAPK(t *testing.T) { if err != nil { t.Fatal(err) } - if sigName != ".SIGN.RSA."+testPubkey { + melangeApkDigest := crypto.SHA1 + prefix := ".SIGN.RSA." + // melangeApkDigest := crypto.SHA256 + // prefix := ".SIGN.RSA256." + if sigName != prefix+testPubkey { t.Fatalf("unexpected signature name %s", sigName) } - //nolint:gosec we do have to use SHA1 here - digest := computeSHA1Digest(controlData) + digest, err := signature.HashData(controlData, melangeApkDigest) + if err != nil { + t.Fatal(err) + } pubKey, err := os.ReadFile("testdata/" + testPubkey) if err != nil { t.Fatal(err) } - if err := signature.RSAVerifySHA1Digest(digest, sig, pubKey); err != nil { + if err := signature.RSAVerifyDigest(digest, melangeApkDigest, sig, pubKey); err != nil { t.Fatal(err) } } -func computeSHA1Digest(data []byte) []byte { - digest := sha1.New() - _, _ = digest.Write(data) - return digest.Sum(nil) -} - func parseAPK(ctx context.Context, apkPath string) (control []byte, sigName string, sig []byte, err error) { apkr, err := os.Open(apkPath) if err != nil {