Skip to content

Commit

Permalink
Add HPKE Go private key import to testutil/hybrid/.
Browse files Browse the repository at this point in the history
NOKEYCHECK=True
PiperOrigin-RevId: 456638268
  • Loading branch information
cindylindeed authored and copybara-github committed Jun 22, 2022
1 parent 122c5e8 commit 0dbbdd4
Show file tree
Hide file tree
Showing 3 changed files with 293 additions and 0 deletions.
38 changes: 38 additions & 0 deletions go/testutil/hybrid/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")

package(default_visibility = ["//:__subpackages__"]) # keep

go_library(
name = "hybrid",
testonly = 1,
srcs = ["private_key.go"],
importpath = "github.com/google/tink/go/testutil/hybrid",
deps = [
"//insecurecleartextkeyset",
"//keyset",
"//proto/hpke_go_proto",
"//proto/tink_go_proto",
"@org_golang_google_protobuf//proto",
],
)

go_test(
name = "hybrid_test",
srcs = ["private_key_test.go"],
deps = [
":hybrid",
"//hybrid",
"//insecurecleartextkeyset",
"//keyset",
"//proto/hpke_go_proto",
"//proto/tink_go_proto",
"//subtle/random",
"@org_golang_google_protobuf//proto",
],
)

alias(
name = "go_default_library",
actual = ":hybrid",
visibility = ["//visibility:public"],
)
124 changes: 124 additions & 0 deletions go/testutil/hybrid/private_key.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

// Package hybrid provides HybridEncrypt/Decrypt primitive-specific test
// utilities.
package hybrid

import (
"errors"
"fmt"

"google.golang.org/protobuf/proto"
"github.com/google/tink/go/insecurecleartextkeyset"
"github.com/google/tink/go/keyset"
hpkepb "github.com/google/tink/go/proto/hpke_go_proto"
tinkpb "github.com/google/tink/go/proto/tink_go_proto"
)

const (
// HPKE key lengths from
// https://www.rfc-editor.org/rfc/rfc9180.html#section-7.1.
hpkeX25519HKDFSHA256PrivKeyLen = 32
hpkeX25519HKDFSHA256PubKeyLen = 32

hpkePrivateKeyTypeURL = "type.googleapis.com/google.crypto.tink.HpkePrivateKey"
)

// KeysetHandleFromSerializedPrivateKey returns a keyset handle containing a
// primary key that has the specified privKeyBytes and pubKeyBytes and matches
// template.
//
// Supported templates include:
// - DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_CHACHA20_POLY1305_Raw_Key_Template,
// which requires privKeyBytes and pubKeyBytes to be the KEM-encoding of the
// private and public key, respectively, i.e. SerializePrivateKey and
// SerializePublicKey in
// https://www.rfc-editor.org/rfc/rfc9180.html#section-7.1.1.
func KeysetHandleFromSerializedPrivateKey(privKeyBytes, pubKeyBytes []byte, template *tinkpb.KeyTemplate) (*keyset.Handle, error) {
params, err := hpkeParamsFromTemplate(template)
if err != nil {
return nil, fmt.Errorf("failed to verify key template: %v", err)
}
if len(privKeyBytes) != hpkeX25519HKDFSHA256PrivKeyLen {
return nil, fmt.Errorf("privKeyBytes length is %d but should be %d", len(privKeyBytes), hpkeX25519HKDFSHA256PrivKeyLen)
}
if len(pubKeyBytes) != hpkeX25519HKDFSHA256PubKeyLen {
return nil, fmt.Errorf("pubKeyBytes length is %d but should be %d", len(pubKeyBytes), hpkeX25519HKDFSHA256PubKeyLen)
}

privKey := &hpkepb.HpkePrivateKey{
Version: 0,
PrivateKey: privKeyBytes,
PublicKey: &hpkepb.HpkePublicKey{
Version: 0,
Params: params,
PublicKey: pubKeyBytes,
},
}
serializedPrivKey, err := proto.Marshal(privKey)
if err != nil {
return nil, fmt.Errorf("failed to marshal HpkePrivateKey %v: %v", privKey, err)
}
ks := &tinkpb.Keyset{
PrimaryKeyId: 1,
Key: []*tinkpb.Keyset_Key{
{
KeyData: &tinkpb.KeyData{
TypeUrl: hpkePrivateKeyTypeURL,
Value: serializedPrivKey,
KeyMaterialType: tinkpb.KeyData_ASYMMETRIC_PRIVATE,
},
Status: tinkpb.KeyStatusType_ENABLED,
KeyId: 1,
OutputPrefixType: tinkpb.OutputPrefixType_RAW,
},
},
}

return insecurecleartextkeyset.Read(&keyset.MemReaderWriter{Keyset: ks})
}

// hpkeParamsFromTemplate returns HPKE params after verifying that template is
// supported.
//
// Supported templates include:
// - DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_CHACHA20_POLY1305_Raw_Key_Template.
func hpkeParamsFromTemplate(template *tinkpb.KeyTemplate) (*hpkepb.HpkeParams, error) {
if template.GetTypeUrl() != hpkePrivateKeyTypeURL {
return nil, fmt.Errorf("not key type URL %s", hpkePrivateKeyTypeURL)
}
if template.GetOutputPrefixType() != tinkpb.OutputPrefixType_RAW {
return nil, errors.New("not raw output prefix type")
}
keyFormat := &hpkepb.HpkeKeyFormat{}
if err := proto.Unmarshal(template.GetValue(), keyFormat); err != nil {
return nil, fmt.Errorf("failed to unmarshal HpkeKeyFormat(%v): %v", template.GetValue(), err)
}

params := keyFormat.GetParams()
if kem := params.GetKem(); kem != hpkepb.HpkeKem_DHKEM_X25519_HKDF_SHA256 {
return nil, fmt.Errorf("HPKE KEM %s not supported", kem)
}
if kdf := params.GetKdf(); kdf != hpkepb.HpkeKdf_HKDF_SHA256 {
return nil, fmt.Errorf("HPKE KDF %s not supported", kdf)
}
if aead := params.GetAead(); aead != hpkepb.HpkeAead_CHACHA20_POLY1305 {
return nil, fmt.Errorf("HPKE AEAD %s not supported", aead)
}

return params, nil
}
131 changes: 131 additions & 0 deletions go/testutil/hybrid/private_key_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

package hybrid_test

import (
"bytes"
"testing"

"google.golang.org/protobuf/proto"
"github.com/google/tink/go/hybrid"
"github.com/google/tink/go/insecurecleartextkeyset"
"github.com/google/tink/go/keyset"
"github.com/google/tink/go/subtle/random"
testutilhybrid "github.com/google/tink/go/testutil/hybrid"
hpkepb "github.com/google/tink/go/proto/hpke_go_proto"
tinkpb "github.com/google/tink/go/proto/tink_go_proto"
)

func TestKeysetHandleFromSerializedPrivateKey(t *testing.T) {
// Obtain private and public key handles via key template.
keyTemplate := hybrid.DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_CHACHA20_POLY1305_Raw_Key_Template()
privHandle, err := keyset.NewHandle(keyTemplate)
if err != nil {
t.Fatalf("NewHandle(%v) err = %v, want nil", keyTemplate, err)
}
pubHandle, err := privHandle.Public()
if err != nil {
t.Fatalf("Public() err = %v, want nil", err)
}

// Get private, public key bytes and construct a private key handle.
privKeyBytes, pubKeyBytes := privPubKeyBytes(t, privHandle)
gotprivHandle, err := testutilhybrid.KeysetHandleFromSerializedPrivateKey(privKeyBytes, pubKeyBytes, keyTemplate)
if err != nil {
t.Errorf("KeysetHandleFromSerializedPrivateKey(%v, %v, %v) err = %v, want nil", privKeyBytes, pubKeyBytes, keyTemplate, err)
}

plaintext := random.GetRandomBytes(200)
ctxInfo := random.GetRandomBytes(100)

// Encrypt with original public key handle.
enc, err := hybrid.NewHybridEncrypt(pubHandle)
if err != nil {
t.Fatalf("NewHybridEncrypt(%v) err = %v, want nil", pubHandle, err)
}
ciphertext, err := enc.Encrypt(plaintext, ctxInfo)
if err != nil {
t.Fatalf("Encrypt(%x, %x) err = %v, want nil", plaintext, ctxInfo, err)
}

// Decrypt with private key handle constructed from key bytes.
dec, err := hybrid.NewHybridDecrypt(gotprivHandle)
if err != nil {
t.Fatalf("NewHybridDecrypt(%v) err = %v, want nil", gotprivHandle, err)
}
gotPlaintext, err := dec.Decrypt(ciphertext, ctxInfo)
if err != nil {
t.Fatalf("Decrypt(%x, %x) err = %v, want nil", ciphertext, ctxInfo, err)
}
if !bytes.Equal(gotPlaintext, plaintext) {
t.Errorf("Decrypt(%x, %x) = %x, want %x", ciphertext, ctxInfo, gotPlaintext, plaintext)
}
}

func TestKeysetHandleFromSerializedPrivateKeyInvalidTemplateFails(t *testing.T) {
keyTemplate := hybrid.DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_CHACHA20_POLY1305_Raw_Key_Template()
privHandle, err := keyset.NewHandle(keyTemplate)
if err != nil {
t.Fatalf("NewHandle(%v) err = %v, want nil", keyTemplate, err)
}
privKeyBytes, pubKeyBytes := privPubKeyBytes(t, privHandle)

tests := []struct {
name string
template *tinkpb.KeyTemplate
}{
{"AES_128_GCM", hybrid.DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_128_GCM_Key_Template()},
{"AES_128_GCM_Raw", hybrid.DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_128_GCM_Raw_Key_Template()},
{"AES_256_GCM", hybrid.DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_256_GCM_Key_Template()},
{"AES_256_GCM_Raw", hybrid.DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_256_GCM_Raw_Key_Template()},
{"CHACHA20_POLY1305", hybrid.DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_CHACHA20_POLY1305_Key_Template()},
{"invalid type URL", &tinkpb.KeyTemplate{
TypeUrl: "type.googleapis.com/google.crypto.tink.EciesAeadHkdfPrivateKey",
Value: keyTemplate.GetValue(),
OutputPrefixType: tinkpb.OutputPrefixType_RAW,
}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if _, err := testutilhybrid.KeysetHandleFromSerializedPrivateKey(privKeyBytes, pubKeyBytes, test.template); err == nil {
t.Errorf("KeysetHandleFromSerializedPrivateKey(%v, %v, %v) err = nil, want error", privKeyBytes, pubKeyBytes, test.template)
}
})
}
}

func privPubKeyBytes(t *testing.T, handle *keyset.Handle) ([]byte, []byte) {
t.Helper()

// Write Handle to MemReaderWriter.
got := &keyset.MemReaderWriter{}
if err := insecurecleartextkeyset.Write(handle, got); err != nil {
t.Fatalf("Write(%v) err = %v, want nil", handle, err)
}
if len(got.Keyset.GetKey()) != 1 {
t.Fatalf("len(gotPriv.Keyset) = %d", len(got.Keyset.GetKey()))
}

// Extract HpkePrivateKey from MemReaderWriter.
serializedPrivKey := got.Keyset.GetKey()[0].GetKeyData().GetValue()
privKey := &hpkepb.HpkePrivateKey{}
if err := proto.Unmarshal(serializedPrivKey, privKey); err != nil {
t.Fatalf("Unmarshal(%v) = err %v, want nil", serializedPrivKey, err)
}

return privKey.GetPrivateKey(), privKey.GetPublicKey().GetPublicKey()
}

0 comments on commit 0dbbdd4

Please sign in to comment.