Skip to content
Snippets Groups Projects
Unverified Commit c4b1a394 authored by dlorenc's avatar dlorenc Committed by GitHub
Browse files

Do some refactoring to prefer sha256.Sum256 when we already have data in memory. (#317)


This saves an if err != nil... check.

Signed-off-by: default avatarDan Lorenc <dlorenc@google.com>
parent 7eaa4abd
No related branches found
No related tags found
No related merge requests found
......@@ -100,11 +100,7 @@ func NewAPI() (*API, error) {
if err != nil {
return nil, errors.Wrap(err, "marshalling public key")
}
hasher := sha256.New()
if _, err = hasher.Write(b); err != nil {
return nil, errors.Wrap(err, "computing hash of public key")
}
pubkeyHashBytes := hasher.Sum(nil)
pubkeyHashBytes := sha256.Sum256(b)
pubkey := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
......@@ -141,7 +137,7 @@ func NewAPI() (*API, error) {
logClient: logClient,
logID: tLogID,
pubkey: string(pubkey),
pubkeyHash: hex.EncodeToString(pubkeyHashBytes),
pubkeyHash: hex.EncodeToString(pubkeyHashBytes[:]),
signer: rekorSigner,
certChain: certChain,
certChainPem: string(certChainPem),
......
......@@ -61,13 +61,9 @@ func SearchIndexHandler(params index.SearchIndexParams) middleware.Responder {
return handleRekorAPIError(params, http.StatusInternalServerError, err, failedToGenerateCanonicalKey)
}
hasher := sha256.New()
if _, err := hasher.Write(canonicalKey); err != nil {
return handleRekorAPIError(params, http.StatusInternalServerError, err, failedToGenerateCanonicalKey)
}
keyHash := hasher.Sum(nil)
keyHash := sha256.Sum256(canonicalKey)
var resultUUIDs []string
if err := redisClient.Do(httpReqCtx, radix.Cmd(&resultUUIDs, "LRANGE", strings.ToLower(hex.EncodeToString(keyHash)), "0", "-1")); err != nil {
if err := redisClient.Do(httpReqCtx, radix.Cmd(&resultUUIDs, "LRANGE", strings.ToLower(hex.EncodeToString(keyHash[:])), "0", "-1")); err != nil {
return handleRekorAPIError(params, http.StatusInternalServerError, err, redisUnexpectedResult)
}
result = append(result, resultUUIDs...)
......
......@@ -18,8 +18,8 @@ package signer
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/sha256"
"crypto/x509"
"testing"
)
......@@ -49,11 +49,10 @@ func TestMemory(t *testing.T) {
if !ok {
t.Fatalf("ecdsa public key: %v", err)
}
h := crypto.SHA256.New()
if _, err := h.Write(payload); err != nil {
t.Fatalf("writing payload: %v", err)
}
if !ecdsa.VerifyASN1(pk, h.Sum(nil), signature) {
h := sha256.Sum256(payload)
if !ecdsa.VerifyASN1(pk, h[:], signature) {
t.Fatalf("unable to verify signature")
}
......@@ -63,7 +62,7 @@ func TestMemory(t *testing.T) {
if !ok {
t.Fatalf("cert ecdsa public key: %v", err)
}
if !ecdsa.VerifyASN1(pkCert, h.Sum(nil), signature) {
if !ecdsa.VerifyASN1(pkCert, h[:], signature) {
t.Fatalf("unable to verify signature")
}
// verify that the cert chain is configured for timestamping
......
......@@ -84,12 +84,8 @@ func (v V001Entry) IndexKeys() []string {
if err != nil {
log.Logger.Error(err)
} else {
hasher := sha256.New()
if _, err := hasher.Write(key); err != nil {
log.Logger.Error(err)
} else {
result = append(result, strings.ToLower(hex.EncodeToString(hasher.Sum(nil))))
}
keyHash := sha256.Sum256(key)
result = append(result, strings.ToLower(hex.EncodeToString(keyHash[:])))
}
if v.JARModel.Archive.Hash != nil {
......
......@@ -54,9 +54,8 @@ func TestCrossFieldValidation(t *testing.T) {
jarBytes, _ := ioutil.ReadFile("../../../../tests/test.jar")
h := sha256.New()
_, _ = h.Write(jarBytes)
dataSHA := hex.EncodeToString(h.Sum(nil))
h := sha256.Sum256(jarBytes)
dataSHA := hex.EncodeToString(h[:])
testServer := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
......
......@@ -77,12 +77,8 @@ func (v V001Entry) IndexKeys() []string {
if err != nil {
log.Logger.Error(err)
} else {
hasher := sha256.New()
if _, err := hasher.Write(key); err != nil {
log.Logger.Error(err)
} else {
result = append(result, strings.ToLower(hex.EncodeToString(hasher.Sum(nil))))
}
keyHash := sha256.Sum256(key)
result = append(result, strings.ToLower(hex.EncodeToString(keyHash[:])))
}
result = append(result, v.keyObj.EmailAddresses()...)
......
......@@ -57,9 +57,8 @@ func TestCrossFieldValidation(t *testing.T) {
keyBytes, _ := ioutil.ReadFile("../../../../tests/test_public_key.key")
dataBytes, _ := ioutil.ReadFile("../../../../tests/test_file.txt")
h := sha256.New()
_, _ = h.Write(dataBytes)
dataSHA := hex.EncodeToString(h.Sum(nil))
h := sha256.Sum256(dataBytes)
dataSHA := hex.EncodeToString(h[:])
testServer := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
......
......@@ -81,12 +81,8 @@ func (v V001Entry) IndexKeys() []string {
if err != nil {
log.Logger.Error(err)
} else {
hasher := sha256.New()
if _, err := hasher.Write(key); err != nil {
log.Logger.Error(err)
} else {
result = append(result, strings.ToLower(hex.EncodeToString(hasher.Sum(nil))))
}
keyHash := sha256.Sum256(key)
result = append(result, strings.ToLower(hex.EncodeToString(keyHash[:])))
}
result = append(result, v.keyObj.EmailAddresses()...)
......
......@@ -56,9 +56,8 @@ func TestCrossFieldValidation(t *testing.T) {
keyBytes, _ := ioutil.ReadFile("../../../../tests/test_rpm_public_key.key")
dataBytes, _ := ioutil.ReadFile("../../../../tests/test.rpm")
h := sha256.New()
_, _ = h.Write(dataBytes)
dataSHA := hex.EncodeToString(h.Sum(nil))
h := sha256.Sum256(dataBytes)
dataSHA := hex.EncodeToString(h[:])
testServer := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
......
......@@ -18,6 +18,7 @@ package util
import (
"context"
"crypto"
"crypto/sha256"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
......@@ -51,14 +52,10 @@ type SigningCertificateV2 struct {
}
func createSigningCertificate(certificate *x509.Certificate) ([]byte, error) {
h := crypto.SHA256.New() // TODO: Get from certificate, defaults to 256
_, err := h.Write(certificate.Raw)
if err != nil {
return nil, fmt.Errorf("failed to create hash")
}
h := sha256.Sum256(certificate.Raw) // TODO: Get from certificate, defaults to 256
signingCert := SigningCertificateV2{
Certs: []EssCertIDv2{{
CertHash: h.Sum(nil),
CertHash: h[:],
IssuerNameAndSerial: IssuerNameAndSerial{
IssuerName: GeneralName{Name: asn1.RawValue{Tag: 4, Class: 2, IsCompound: true, Bytes: certificate.RawIssuer}},
SerialNumber: certificate.SerialNumber,
......@@ -174,11 +171,9 @@ func CreateRfc3161Response(ctx context.Context, req pkcs9.TimeStampReq, certChai
}
// TODO: Does this need to match the hash algorithm in the request?
h := crypto.SHA256.New()
alg, _ := x509tools.PkixDigestAlgorithm(crypto.SHA256)
contentInfoBytes, _ := contentInfo.Bytes()
h.Write(contentInfoBytes)
digest := h.Sum(nil)
h := sha256.Sum256(contentInfoBytes)
// Create SignerInfo and signature.
signingCert, err := createSigningCertificate(certChain[0])
......@@ -189,7 +184,7 @@ func CreateRfc3161Response(ctx context.Context, req pkcs9.TimeStampReq, certChai
if err := attributes.Add(pkcs7.OidAttributeContentType, contentInfo.ContentType); err != nil {
return nil, err
}
if err := attributes.Add(pkcs7.OidAttributeMessageDigest, digest); err != nil {
if err := attributes.Add(pkcs7.OidAttributeMessageDigest, h[:]); err != nil {
return nil, err
}
if err := attributes.Add(asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 16, 2, 47}, signingCert); err != nil {
......
......@@ -20,7 +20,6 @@ package e2e
import (
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/sha256"
"crypto/x509"
......@@ -192,15 +191,13 @@ func TestGet(t *testing.T) {
out = runCli(t, "search", "--public-key", pubPath)
outputContains(t, out, uuid)
hash := sha256.New()
artifactBytes, err := ioutil.ReadFile(artifactPath)
if err != nil {
t.Error(err)
}
hash.Write(artifactBytes)
sha := hash.Sum(nil)
sha := sha256.Sum256(artifactBytes)
out = runCli(t, "search", "--sha", fmt.Sprintf("sha256:%s", hex.EncodeToString(sha)))
out = runCli(t, "search", "--sha", fmt.Sprintf("sha256:%s", hex.EncodeToString(sha[:])))
outputContains(t, out, uuid)
}
......@@ -468,13 +465,8 @@ func TestSignedEntryTimestamp(t *testing.T) {
}
// verify the signature against the public key
h := crypto.SHA256.New()
if _, err := h.Write(canonicalized); err != nil {
t.Fatal(err)
}
sum := h.Sum(nil)
if !ecdsa.VerifyASN1(rekorPubKey, sum, []byte(sig)) {
h := sha256.Sum256(canonicalized)
if !ecdsa.VerifyASN1(rekorPubKey, h[:], []byte(sig)) {
t.Fatal("unable to verify")
}
}
......@@ -522,12 +514,8 @@ func TestTimestampResponseCLI(t *testing.T) {
}
// Now try with the digest.
h := crypto.SHA256.New()
if _, err := h.Write(payload); err != nil {
t.Fatalf("error creating digest")
}
digest := h.Sum(nil)
hexDigest := hex.EncodeToString(digest)
h := sha256.Sum256(payload)
hexDigest := hex.EncodeToString(h[:])
out = runCli(t, "timestamp", "--artifact-hash", hexDigest, "--out", responsePath)
outputContains(t, out, "Wrote response to")
cmd = exec.Command("openssl", "ts", "-verify", "-digest", hexDigest, "-in", responsePath, "-CAfile", CAPath)
......
......@@ -131,10 +131,8 @@ func init() {
}
func SignX509Cert(b []byte) ([]byte, error) {
h := sha256.New()
h.Write(b)
dgst := h.Sum(nil)
signature, err := certPrivateKey.Sign(rand.Reader, dgst, crypto.SHA256)
dgst := sha256.Sum256(b)
signature, err := certPrivateKey.Sign(rand.Reader, dgst[:], crypto.SHA256)
return signature, err
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment