github.com/hairyhenderson/gomplate/v3@v3.11.7/internal/tests/integration/crypto_test.go (about)

     1  package integration
     2  
     3  import (
     4  	"crypto/rand"
     5  	"crypto/rsa"
     6  	"crypto/x509"
     7  	"encoding/pem"
     8  	"testing"
     9  
    10  	"gotest.tools/v3/fs"
    11  )
    12  
    13  func genTestKeys() (string, string) {
    14  	rsaPriv, _ := rsa.GenerateKey(rand.Reader, 4096)
    15  	rsaPub := rsaPriv.PublicKey
    16  	privBlock := &pem.Block{
    17  		Type:  "RSA PRIVATE KEY",
    18  		Bytes: x509.MarshalPKCS1PrivateKey(rsaPriv),
    19  	}
    20  	testPrivKey := string(pem.EncodeToMemory(privBlock))
    21  
    22  	b, _ := x509.MarshalPKIXPublicKey(&rsaPub)
    23  	pubBlock := &pem.Block{
    24  		Type:  "PUBLIC KEY",
    25  		Bytes: b,
    26  	}
    27  	testPubKey := string(pem.EncodeToMemory(pubBlock))
    28  	return testPrivKey, testPubKey
    29  }
    30  
    31  func setupCryptoTest(t *testing.T) *fs.Dir {
    32  	testPrivKey, testPubKey := genTestKeys()
    33  
    34  	tmpDir := fs.NewDir(t, "gomplate-inttests",
    35  		fs.WithFile("testPrivKey", testPrivKey),
    36  		fs.WithFile("testPubKey", testPubKey),
    37  	)
    38  	t.Cleanup(tmpDir.Remove)
    39  
    40  	return tmpDir
    41  }
    42  
    43  func TestCrypto_RSACrypt(t *testing.T) {
    44  	tmpDir := setupCryptoTest(t)
    45  	o, e, err := cmd(t,
    46  		"--experimental",
    47  		"-i", `{{ crypto.RSAGenerateKey 2048 -}}`,
    48  		"-o", `key.pem`).
    49  		withDir(tmpDir.Path()).run()
    50  	assertSuccess(t, o, e, err, "")
    51  
    52  	o, e, err = cmd(t,
    53  		"--experimental",
    54  		"-c", "privKey=./key.pem?type=text/plain",
    55  		"-i", `{{ $pub := crypto.RSADerivePublicKey .privKey -}}
    56  {{ $enc := "hello" | crypto.RSAEncrypt $pub -}}
    57  {{ crypto.RSADecryptBytes .privKey $enc | conv.ToString }}
    58  {{ crypto.RSADecrypt .privKey $enc }}
    59  `).
    60  		withDir(tmpDir.Path()).run()
    61  	assertSuccess(t, o, e, err, "hello\nhello\n")
    62  }