github.com/code-to-go/safepool.lib@v0.0.0-20221205180519-ee25e63c226e/security/tink_test.go (about)

     1  package security
     2  
     3  import (
     4  	"encoding/base64"
     5  	"fmt"
     6  	"log"
     7  	"testing"
     8  
     9  	"github.com/google/tink/go/keyset"
    10  	"github.com/google/tink/go/signature"
    11  )
    12  
    13  func TestSignature(t *testing.T) {
    14  	kh, err := keyset.NewHandle(signature.ECDSAP256KeyTemplate()) // Other key templates can also be used.
    15  	if err != nil {
    16  		log.Fatal(err)
    17  	}
    18  
    19  	// TODO: save the private keyset to a pool location. DO NOT hardcode it in source code.
    20  	// Consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault.
    21  	// See https://github.com/google/tink/blob/master/docs/GOLANG-HOWTO.md#storing-and-loading-existing-keysets.
    22  
    23  	s, err := signature.NewSigner(kh)
    24  	if err != nil {
    25  		log.Fatal(err)
    26  	}
    27  
    28  	msg := []byte("this data needs to be signed")
    29  	sig, err := s.Sign(msg)
    30  	if err != nil {
    31  		log.Fatal(err)
    32  	}
    33  
    34  	pubkh, err := kh.Public()
    35  	if err != nil {
    36  		log.Fatal(err)
    37  	}
    38  
    39  	// TODO: share the public with the verifier.
    40  
    41  	v, err := signature.NewVerifier(pubkh)
    42  	if err != nil {
    43  		log.Fatal(err)
    44  	}
    45  
    46  	if err := v.Verify(sig, msg); err != nil {
    47  		log.Fatal(err)
    48  	}
    49  
    50  	fmt.Printf("Message: %s\n", msg)
    51  	fmt.Printf("Signature: %s\n", base64.StdEncoding.EncodeToString(sig))
    52  
    53  }