From ef54d75f7031ddaa24bd65c8c76b45f51c5eb12f Mon Sep 17 00:00:00 2001 From: Whit Waldo Date: Tue, 14 Jan 2025 17:38:28 -0600 Subject: [PATCH] Simplfying Crypto example (#1442) * Fixed bad console output showing encrypted bytes Signed-off-by: Whit Waldo * Simplified example so it doesn't require an Azure Key Vault instance and just uses a local set of keys Signed-off-by: Whit Waldo * Updated README to include instructions for generating the private key Signed-off-by: Whit Waldo * Added private RSA key to project for users that lack OpenSSL on their system - updated README to include warning calling out that this key shouldn't be used for anything but demonstration and testing purposes. Signed-off-by: Whit Waldo --------- Signed-off-by: Whit Waldo --- .../Components/azurekeyvault.yaml | 25 --------- .../Components/env-secretstore.yaml | 7 --- .../Components/local-storage.yaml | 11 ++++ .../EncryptDecryptFileStreamExample.cs | 12 ++--- .../Examples/EncryptDecryptStringExample.cs | 8 +-- examples/Client/Cryptography/Program.cs | 9 ++-- examples/Client/Cryptography/README.md | 15 ++++++ .../Cryptography/keys/rsa-private-key.pem | 52 +++++++++++++++++++ 8 files changed, 90 insertions(+), 49 deletions(-) delete mode 100644 examples/Client/Cryptography/Components/azurekeyvault.yaml delete mode 100644 examples/Client/Cryptography/Components/env-secretstore.yaml create mode 100644 examples/Client/Cryptography/Components/local-storage.yaml create mode 100644 examples/Client/Cryptography/keys/rsa-private-key.pem diff --git a/examples/Client/Cryptography/Components/azurekeyvault.yaml b/examples/Client/Cryptography/Components/azurekeyvault.yaml deleted file mode 100644 index 5932e0bc8..000000000 --- a/examples/Client/Cryptography/Components/azurekeyvault.yaml +++ /dev/null @@ -1,25 +0,0 @@ -apiVersion: dapr.io/v1alpha1 -kind: Component -metadata: - name: azurekeyvault -spec: - type: crypto.azure.keyvault - metadata: - - name: vaultName - value: "" - - name: azureEnvironment - value: AZUREPUBLICCLOUD - - name: azureTenantId - secretKeyRef: - name: read_azure_tenant_id - key: read_azure_tenant_id - - name: azureClientId - secretKeyRef: - name: read_azure_client_id - key: read_azure_client_id - - name: azureClientSecret - secretKeyRef: - name: read_azure_client_secret - key: read_azure_client_secret -auth: - secureStore: envvar-secret-store \ No newline at end of file diff --git a/examples/Client/Cryptography/Components/env-secretstore.yaml b/examples/Client/Cryptography/Components/env-secretstore.yaml deleted file mode 100644 index fb191414d..000000000 --- a/examples/Client/Cryptography/Components/env-secretstore.yaml +++ /dev/null @@ -1,7 +0,0 @@ -apiVersion: dapr.io/v1alpha1 -kind: Component -metadata: - name: envvar-secret-store -spec: - type: secretstores.local.env - version: v1 \ No newline at end of file diff --git a/examples/Client/Cryptography/Components/local-storage.yaml b/examples/Client/Cryptography/Components/local-storage.yaml new file mode 100644 index 000000000..4a6640fed --- /dev/null +++ b/examples/Client/Cryptography/Components/local-storage.yaml @@ -0,0 +1,11 @@ +apiVersion: dapr.io/v1alpha1 +kind: Component +metadata: + name: localstorage +spec: + type: crypto.dapr.localstorage + version: v1 + metadata: + - name: path + # Path is relative to the folder where the example is located + value: ./keys diff --git a/examples/Client/Cryptography/Examples/EncryptDecryptFileStreamExample.cs b/examples/Client/Cryptography/Examples/EncryptDecryptFileStreamExample.cs index aa9c404a7..19df06345 100644 --- a/examples/Client/Cryptography/Examples/EncryptDecryptFileStreamExample.cs +++ b/examples/Client/Cryptography/Examples/EncryptDecryptFileStreamExample.cs @@ -17,16 +17,13 @@ namespace Cryptography.Examples { - internal class EncryptDecryptFileStreamExample : Example + internal class EncryptDecryptFileStreamExample(string componentName, string keyName) : Example { public override string DisplayName => "Use Cryptography to encrypt and decrypt a file"; public override async Task RunAsync(CancellationToken cancellationToken) { using var client = new DaprClientBuilder().Build(); - const string componentName = "azurekeyvault"; // Change this to match the name of the component containing your vault - const string keyName = "myKey"; - // The name of the file we're using as an example const string fileName = "file.txt"; @@ -35,7 +32,6 @@ public override async Task RunAsync(CancellationToken cancellationToken) { Console.WriteLine(line); } - Console.WriteLine(); //Encrypt from a file stream and buffer the resulting bytes to an in-memory buffer await using var encryptFs = new FileStream(fileName, FileMode.Open); @@ -48,8 +44,8 @@ public override async Task RunAsync(CancellationToken cancellationToken) bufferedEncryptedBytes.Write(bytes.Span); } - Console.WriteLine($"Encrypted bytes: {Convert.ToBase64String(bufferedEncryptedBytes.GetSpan())}"); - Console.WriteLine(); + Console.WriteLine("Encrypted bytes:"); + Console.WriteLine(Convert.ToBase64String(bufferedEncryptedBytes.WrittenMemory.ToArray())); //We'll write to a temporary file via a FileStream var tempDecryptedFile = Path.GetTempFileName(); @@ -67,7 +63,7 @@ public override async Task RunAsync(CancellationToken cancellationToken) //Let's confirm the value as written to the file var decryptedValue = await File.ReadAllTextAsync(tempDecryptedFile, cancellationToken); - Console.WriteLine($"Decrypted value: "); + Console.WriteLine("Decrypted value: "); Console.WriteLine(decryptedValue); //And some cleanup to delete our temp file diff --git a/examples/Client/Cryptography/Examples/EncryptDecryptStringExample.cs b/examples/Client/Cryptography/Examples/EncryptDecryptStringExample.cs index a37ca1b8b..d29b24a60 100644 --- a/examples/Client/Cryptography/Examples/EncryptDecryptStringExample.cs +++ b/examples/Client/Cryptography/Examples/EncryptDecryptStringExample.cs @@ -17,17 +17,13 @@ namespace Cryptography.Examples { - internal class EncryptDecryptStringExample : Example + internal class EncryptDecryptStringExample(string componentName, string keyName) : Example { public override string DisplayName => "Using Cryptography to encrypt and decrypt a string"; public override async Task RunAsync(CancellationToken cancellationToken) { using var client = new DaprClientBuilder().Build(); - - const string componentName = "azurekeyvault"; //Change this to match the name of the component containing your vault - const string keyName = "myKey"; //Change this to match the name of the key in your Vault - const string plaintextStr = "This is the value we're going to encrypt today"; Console.WriteLine($"Original string value: '{plaintextStr}'"); @@ -40,7 +36,7 @@ public override async Task RunAsync(CancellationToken cancellationToken) Console.WriteLine($"Encrypted bytes: '{Convert.ToBase64String(encryptedBytesResult.Span)}'"); //Decrypt the string - var decryptedBytes = await client.DecryptAsync(componentName, encryptedBytesResult, keyName, new DecryptionOptions(), cancellationToken); + var decryptedBytes = await client.DecryptAsync(componentName, encryptedBytesResult, keyName, cancellationToken); Console.WriteLine($"Decrypted string: '{Encoding.UTF8.GetString(decryptedBytes.ToArray())}'"); } } diff --git a/examples/Client/Cryptography/Program.cs b/examples/Client/Cryptography/Program.cs index da81bef8f..5c63d7361 100644 --- a/examples/Client/Cryptography/Program.cs +++ b/examples/Client/Cryptography/Program.cs @@ -17,10 +17,13 @@ namespace Cryptography { class Program { + private const string ComponentName = "localstorage"; + private const string KeyName = "rsa-private-key.pem"; //This should match the name of your generated key - this sample expects an RSA symmetrical key. + private static readonly Example[] Examples = new Example[] { - new EncryptDecryptStringExample(), - new EncryptDecryptFileStreamExample() + new EncryptDecryptStringExample(ComponentName, KeyName), + new EncryptDecryptFileStreamExample(ComponentName, KeyName) }; static async Task Main(string[] args) @@ -34,7 +37,7 @@ static async Task Main(string[] args) return 0; } - Console.WriteLine("Hello, please choose a sample to run:"); + Console.WriteLine("Hello, please choose a sample to run by passing your selection's number into the arguments, e.g. 'dotnet run 0':"); for (var i = 0; i < Examples.Length; i++) { Console.WriteLine($"{i}: {Examples[i].DisplayName}"); diff --git a/examples/Client/Cryptography/README.md b/examples/Client/Cryptography/README.md index c0c884369..883cd2b2d 100644 --- a/examples/Client/Cryptography/README.md +++ b/examples/Client/Cryptography/README.md @@ -50,6 +50,21 @@ button. Ensuring that the "User, group or service principal" option is selected, Add to add this service principal to the list of members for the new role assignment and click Review + Assign twice to assign the role. This will take effect within a few seconds or minutes. This step ensures that while Dapr can authenticate as your service principal, that it also has permission to access and use the key in your Key Vault. +## Generating the Keys +This sample requires a private RSA key to be generated and placed in the `/keys` directory within the project. +If you have OpenSSL installed on your machine, you can generate the key by navigating first +into the project directory and then running the following command: + +```bash +# Generates a private RSA 40960-bit key named 'rsa-private-key.pem' +openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:4096 -out keys/rsa-private-key.pem +``` + +> **WARNING: This RSA key is included in this project strictly for demonstration and testing purposes.** +> - Do **NOT** use this key in any production environment or for any real-world applications. +> - This key is publicly available and should be considered compromised. +> - Generating and using your own secure keys is essential for maintaining security in your projects. + ## Running the example To run the sample locally, run this command in the DaprClient directory: diff --git a/examples/Client/Cryptography/keys/rsa-private-key.pem b/examples/Client/Cryptography/keys/rsa-private-key.pem new file mode 100644 index 000000000..f4508f7ae --- /dev/null +++ b/examples/Client/Cryptography/keys/rsa-private-key.pem @@ -0,0 +1,52 @@ +-----BEGIN PRIVATE KEY----- +MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQC0URLpxZCqDv7S +WfROh2Kei4VCEayNu/TK3NaD/QlIpip1rrsPKgTfTOZoRmkmG0Qj59srEJi2GEhL +xpjvRQpA/C/OS+KELU8AeGrqHw7uN/a99NkoAr+zYDCyY9yckPeC5wGxc0/Q6HQT +mWp+YcpR9wFO0PmTVlObssibagjjRNX7z/ZosecOOqjnAqlnYoHMavvoCD5fxM7y +cm7so0JWooXwVaZKgehBEBg1W5F0q5e9ssAQk3lY6IUd5sOskiylTNf/+3r1JU0j +YM8ik3a1/dyDALVXpLSfz7FM9VEj4QjiPF4UuXeBHPDFFiKWbiKfbjqvZ2Sz7Gl7 +c5rTk1Fozpr70E/wihrrv22Mxs0sEPdtemQgHXroQfRW8K4FhI0WHs7tR2gVxLHu +OAU9LzCngz4yITh1eixVDmm/B5ZtNVrTQmaY84vGqhrFp+asyFNiXbhUAcT7D/q6 +w/c4aQ635ntCFSPYpWvhKqrqVDsoanD/5AWfc3+6Ek2/GVMyEQq+9tnCMM10EVSX +8PsoAWHESDFude5zkHzn7IKy8mh6lfheEbBI5zN9z7WGexyiBgljmyUHXx6Pd8Uc +yxpLRm94kynkDXD9SapQLzXmz+D+X/OYeADMIDWlbdXiIb1+2Q62H1lo6n10KVP7 +oEr8BHvcMFY89kwK4lKscUupn8xkzwIDAQABAoICACDuu78Rc8Hzeivt/PZIuMTP +I5f1BWhffy571fwGP2dS3edfcc+rs3cbIuvBjFvG2BOcuYUsg0+isLWSQIVWvTAw +PwT1DBpq8gZad+Bpqr7sXrbD3NN3aQ64TzyNi5HW0jXI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