# A key pair for a test — Crypto.NewRsaKeyPair

> Make an RSA key pair inside a test, so code that signs (a JWT for a GitHub App, a Snowflake or Google service account) can be tested without a private key committed anywhere. The public half is PEM text; the private half signs, can be a secret's value for the test, and never leaves memory.

<!-- id: function-crypto-keypair · area: function · stability: stable · html: https://osysharp.com/reference/function/crypto-keypair/ -->

## Summary        {#summary}
Signing code needs a private key to run, and a test has none: a real key must not be committed, and a fake one that
does not parse makes `Crypto.SignRs256` throw. `Crypto.NewRsaKeyPair(2048)` makes a real key pair in memory, for the
length of the test. The test signs with the private half, or hands it to the secret the code under test reads, and
then checks the signature with the public half, exactly as the service on the other end would.

The private half never leaves memory. It cannot become text, be logged, be stored, be written to a file, be returned
or be sent anywhere. The compiler refuses each of those, and anything it cannot see is refused when the test runs.

## Signature      {#signature}
```osy syntax
var keys = Crypto.NewRsaKeyPair(bits: int);          // 2048, 3072 or 4096 — test code only

keys.PublicKeyPem                                    // string: "-----BEGIN PUBLIC KEY-----…"
keys.PrivateKey                                      // the private half: it signs, and nothing else

Crypto.SignRs256(keys.PrivateKey, data: byte[])      // → byte[], RS256 (RSASSA-PKCS1-v1_5 + SHA-256)
Secret.<Name>.Stub(keys.PrivateKey);                 // the secret's value for the rest of the test
Secret.<Keyed>.StubFor(id, keys.PrivateKey);         // one id of a keyed secret, for the rest of the test
```

## Description    {#description}
**It is for test code.** `Crypto.NewRsaKeyPair` compiles in a `[Test]`, a `[TestFixture]` and any function in a
`.test.osy` file, and runs only when a test runs. Anywhere else it is `GENERATED_KEY_TEST_ONLY`: an app's real key is
issued by the service that trusts it, given to a declared secret with `osy secret set AppKey --file key.pem`, and
signed with through `Crypto.SignRs256(Secret.AppKey, data)` ([Asymmetric signing — Crypto.SignRs256, VerifyRs256, SignEs256, VerifyEs256](https://osysharp.com/reference/function/crypto-sign/)).

**Hold it in a `var`.** The pair and its private half have no type name to write, so no field, parameter or return
type can carry one. Hold the pair in a local, and read its two members where you need them:

| Member | Type | What it is for |
|---|---|---|
| `keys.PublicKeyPem` | `string` | The public half as a PEM. Give it to `Crypto.VerifyRs256`, compare it, store it, send it: it is public. |
| `keys.PrivateKey` | the private half | Signs. Pass it to `Crypto.SignRs256`, or to a secret for the test. |

**The private half goes to three places, and the compiler refuses every other.** It may be held in a local, signed
with (`Crypto.SignRs256(keys.PrivateKey, data)`), and given to a secret for the test (`Secret.X.Stub(…)` or
`Secret.X.StubFor(id, …)`). Every other use is `GENERATED_KEY_ESCAPES`: interpolation, `+` with a string,
`ToString()`, `Convert.ToString`, a log line, `JsonSerializer.Serialize`, an object's or entity's field, a list, a
function argument, a return value, a tuple, a lambda's result, a file, a request, an exception, and an assertion's
operand (a failing assertion prints its operands). A `Func` or `Action` lambda may not capture it either, even one that
only signs with it: a function value carries what it captures wherever it goes. Sign in the test's own body, or stub
the secret and let the code under test sign. A stub's own lambda is the exception, because it stays in the test's stub
table: a fake service may sign its answer with
`Http.Get.Stub((url, headers) => new HttpResponse { StatusCode = 200, Body = Convert.ToBase64String(Crypto.SignRs256(keys.PrivateKey, Text.ToBytes(url))) })`.
The list is closed on purpose. A place that is not on it is refused, including
one that is added to the language later.

**Give it to the code under test through its secret.** The code you are testing reads its key from a secret
(`Crypto.SignRs256(Secret.AppKey, …)`), and that is the code the test should run. `Secret.AppKey.Stub(keys.PrivateKey)`
makes that read answer the generated key for the rest of the test, in the test body and in every server call the test
causes. For a [keyed secret](https://osysharp.com/reference/function/secret-read/), `Secret.X.StubFor(id, keys.PrivateKey)` does the same for one id.
`Secret.X.IsSetFor(id)` answers `true` while the key is held, `Secret.X.SetIds()` lists the id, and
`Secret.X.RetireFor(id)` lets it go. The key is held in memory only. It is never written to the secret store, so it is
never encrypted, kept or listed by `osy secret`. A text value for a keyed secret goes through the door instead, as in
the app: `Secret.X.SetFor(id, "test-value")`.

**A package's tests app stubs the package's keyed secret the same way.** When the keyed secret is declared by a
package the app composes and grants (`use Acme.GitHub { secret "GitHubAppKey"; }`), a test of the app may still write
`Secret.GitHubAppKey.StubFor(id, keys.PrivateKey)` or `Secret.GitHubAppKey.SetFor(id, "test-value")`, and the
package's own code reads that id's value. Only these test verbs are allowed, and only in test code. The app's own
code still cannot name the package's secret.

**At run time, it refuses to become text.** The code under test reads a stubbed secret as a `string`, so the compiler
cannot follow the key into it. If that code puts the key into text (`"Bearer " + Secret.AppKey`), logs it, writes it to
JSON or holds it across a suspension (a browser call or a workflow wait), the test fails with
`GENERATED_KEY_LEFT_MEMORY`. The message never contains the key, because there is no text of the key anywhere in the
process. A trace or `osy inspect` shows a local holding one as unreadable.

**Every call makes a fresh key.** Make the pair once, at the top of the test or in a `[TestFixture]`, and use that
pair. 2048 bits is what GitHub Apps, Google service accounts and Snowflake issue; 3072 and 4096 are accepted and are
slower to make. Any other size is refused.

## Examples       {#examples}
The code under test reads its key from a secret. The test stubs that secret with a generated key and checks the
signature with the public half:

```osy title="sign with the code under test, verify with the public half" run app=function-crypto-keypair
app.Secrets = [
  new Secret("AppKey"),
  new Secret("InstallKey") { Keyed = true, MayWrite = MayManageInstallKey }
];

policy MayManageInstallKey(string id) => true;

string B64Url(byte[] b) {
  return Convert.ToBase64String(b).Replace("+", "-").Replace("/", "_").Replace("=", "");
}

// The code under test: it signs with the app's key, read from its secret.
string SignedToken(string subject) {
  var signingInput = B64Url(Text.ToBytes("{\"alg\":\"RS256\"}")) + "." + B64Url(Text.ToBytes("{\"sub\":\"" + subject + "\"}"));
  return signingInput + "." + B64Url(Crypto.SignRs256(Secret.AppKey, Text.ToBytes(signingInput)));
}

[Test]
void the_token_verifies_with_the_public_half() {
  var keys = Crypto.NewRsaKeyPair(2048);
  Secret.AppKey.Stub(keys.PrivateKey);

  var parts = SignedToken("ada").Split(".");
  var signature = parts[2].Replace("-", "+").Replace("_", "/");
  while (signature.Length % 4 != 0) { signature = signature + "="; }
  Assert.True(Crypto.VerifyRs256(keys.PublicKeyPem, Text.ToBytes(parts[0] + "." + parts[1]),
    Convert.FromBase64String(signature)));
}
```

The same for one id of a keyed secret, and the test signing directly:

```osy title="a keyed secret's id answers a held key" run app=function-crypto-keypair
string SignFor(string id, string data) {
  return Convert.ToBase64String(Crypto.SignRs256(Secret.InstallKey.For(id), Text.ToBytes(data)));
}

[Test]
void one_installation_signs_with_its_held_key() {
  var keys = Crypto.NewRsaKeyPair(2048);
  Secret.InstallKey.StubFor("install-1", keys.PrivateKey);
  Assert.True(Secret.InstallKey.IsSetFor("install-1"));

  var signature = Convert.FromBase64String(SignFor("install-1", "hello"));
  Assert.True(Crypto.VerifyRs256(keys.PublicKeyPem, Text.ToBytes("hello"), signature));

  var direct = Crypto.SignRs256(keys.PrivateKey, Text.ToBytes("hello"));
  Assert.True(Crypto.VerifyRs256(keys.PublicKeyPem, Text.ToBytes("hello"), direct));

  Assert.True(Secret.InstallKey.RetireFor("install-1"));
  Assert.False(Secret.InstallKey.IsSetFor("install-1"));
}
```

Code under test that puts the key into text fails the test with `GENERATED_KEY_LEFT_MEMORY`, and the message carries
no part of the key:

```osy title="the key refuses to become text at run time" run app=function-crypto-keypair
string BearerHeader() {
  return "Bearer " + Secret.AppKey;
}

[Test]
void the_key_never_becomes_a_header() {
  var keys = Crypto.NewRsaKeyPair(2048);
  Secret.AppKey.Stub(keys.PrivateKey);
  var fault = Assert.Throws<Exception>(() => BearerHeader());
  Assert.StartsWith("GENERATED_KEY_LEFT_MEMORY", fault.Message);
}
```

## See also       {#see-also}
- [Asymmetric signing — Crypto.SignRs256, VerifyRs256, SignEs256, VerifyEs256](https://osysharp.com/reference/function/crypto-sign/) — `Crypto.SignRs256` and `VerifyRs256` with a real key read from a secret
- [Outbound calls in a test](https://osysharp.com/reference/testing/outbound-calls/) — `Secret.X.Stub`, and stubbing the service the signed request goes to
- [reading a secret's value (Secret.Name)](https://osysharp.com/reference/function/secret-read/) — declaring a secret, and keyed secrets' `For`, `IsSetFor` and `RetireFor`
