Skip to content

Commit ef54d75

Browse files
authored
Simplfying Crypto example (#1442)
* Fixed bad console output showing encrypted bytes Signed-off-by: Whit Waldo <[email protected]> * 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 <[email protected]> * Updated README to include instructions for generating the private key Signed-off-by: Whit Waldo <[email protected]> * 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 <[email protected]> --------- Signed-off-by: Whit Waldo <[email protected]>
1 parent 01b4833 commit ef54d75

8 files changed

+90
-49
lines changed

examples/Client/Cryptography/Components/azurekeyvault.yaml

-25
This file was deleted.

examples/Client/Cryptography/Components/env-secretstore.yaml

-7
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
apiVersion: dapr.io/v1alpha1
2+
kind: Component
3+
metadata:
4+
name: localstorage
5+
spec:
6+
type: crypto.dapr.localstorage
7+
version: v1
8+
metadata:
9+
- name: path
10+
# Path is relative to the folder where the example is located
11+
value: ./keys

examples/Client/Cryptography/Examples/EncryptDecryptFileStreamExample.cs

+4-8
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,13 @@
1717

1818
namespace Cryptography.Examples
1919
{
20-
internal class EncryptDecryptFileStreamExample : Example
20+
internal class EncryptDecryptFileStreamExample(string componentName, string keyName) : Example
2121
{
2222
public override string DisplayName => "Use Cryptography to encrypt and decrypt a file";
2323
public override async Task RunAsync(CancellationToken cancellationToken)
2424
{
2525
using var client = new DaprClientBuilder().Build();
2626

27-
const string componentName = "azurekeyvault"; // Change this to match the name of the component containing your vault
28-
const string keyName = "myKey";
29-
3027
// The name of the file we're using as an example
3128
const string fileName = "file.txt";
3229

@@ -35,7 +32,6 @@ public override async Task RunAsync(CancellationToken cancellationToken)
3532
{
3633
Console.WriteLine(line);
3734
}
38-
Console.WriteLine();
3935

4036
//Encrypt from a file stream and buffer the resulting bytes to an in-memory buffer
4137
await using var encryptFs = new FileStream(fileName, FileMode.Open);
@@ -48,8 +44,8 @@ public override async Task RunAsync(CancellationToken cancellationToken)
4844
bufferedEncryptedBytes.Write(bytes.Span);
4945
}
5046

51-
Console.WriteLine($"Encrypted bytes: {Convert.ToBase64String(bufferedEncryptedBytes.GetSpan())}");
52-
Console.WriteLine();
47+
Console.WriteLine("Encrypted bytes:");
48+
Console.WriteLine(Convert.ToBase64String(bufferedEncryptedBytes.WrittenMemory.ToArray()));
5349

5450
//We'll write to a temporary file via a FileStream
5551
var tempDecryptedFile = Path.GetTempFileName();
@@ -67,7 +63,7 @@ public override async Task RunAsync(CancellationToken cancellationToken)
6763

6864
//Let's confirm the value as written to the file
6965
var decryptedValue = await File.ReadAllTextAsync(tempDecryptedFile, cancellationToken);
70-
Console.WriteLine($"Decrypted value: ");
66+
Console.WriteLine("Decrypted value: ");
7167
Console.WriteLine(decryptedValue);
7268

7369
//And some cleanup to delete our temp file

examples/Client/Cryptography/Examples/EncryptDecryptStringExample.cs

+2-6
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,13 @@
1717

1818
namespace Cryptography.Examples
1919
{
20-
internal class EncryptDecryptStringExample : Example
20+
internal class EncryptDecryptStringExample(string componentName, string keyName) : Example
2121
{
2222
public override string DisplayName => "Using Cryptography to encrypt and decrypt a string";
2323

2424
public override async Task RunAsync(CancellationToken cancellationToken)
2525
{
2626
using var client = new DaprClientBuilder().Build();
27-
28-
const string componentName = "azurekeyvault"; //Change this to match the name of the component containing your vault
29-
const string keyName = "myKey"; //Change this to match the name of the key in your Vault
30-
3127

3228
const string plaintextStr = "This is the value we're going to encrypt today";
3329
Console.WriteLine($"Original string value: '{plaintextStr}'");
@@ -40,7 +36,7 @@ public override async Task RunAsync(CancellationToken cancellationToken)
4036
Console.WriteLine($"Encrypted bytes: '{Convert.ToBase64String(encryptedBytesResult.Span)}'");
4137

4238
//Decrypt the string
43-
var decryptedBytes = await client.DecryptAsync(componentName, encryptedBytesResult, keyName, new DecryptionOptions(), cancellationToken);
39+
var decryptedBytes = await client.DecryptAsync(componentName, encryptedBytesResult, keyName, cancellationToken);
4440
Console.WriteLine($"Decrypted string: '{Encoding.UTF8.GetString(decryptedBytes.ToArray())}'");
4541
}
4642
}

examples/Client/Cryptography/Program.cs

+6-3
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,13 @@ namespace Cryptography
1717
{
1818
class Program
1919
{
20+
private const string ComponentName = "localstorage";
21+
private const string KeyName = "rsa-private-key.pem"; //This should match the name of your generated key - this sample expects an RSA symmetrical key.
22+
2023
private static readonly Example[] Examples = new Example[]
2124
{
22-
new EncryptDecryptStringExample(),
23-
new EncryptDecryptFileStreamExample()
25+
new EncryptDecryptStringExample(ComponentName, KeyName),
26+
new EncryptDecryptFileStreamExample(ComponentName, KeyName)
2427
};
2528

2629
static async Task<int> Main(string[] args)
@@ -34,7 +37,7 @@ static async Task<int> Main(string[] args)
3437
return 0;
3538
}
3639

37-
Console.WriteLine("Hello, please choose a sample to run:");
40+
Console.WriteLine("Hello, please choose a sample to run by passing your selection's number into the arguments, e.g. 'dotnet run 0':");
3841
for (var i = 0; i < Examples.Length; i++)
3942
{
4043
Console.WriteLine($"{i}: {Examples[i].DisplayName}");

examples/Client/Cryptography/README.md

+15
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,21 @@ button. Ensuring that the "User, group or service principal" option is selected,
5050
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
5151
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.
5252

53+
## Generating the Keys
54+
This sample requires a private RSA key to be generated and placed in the `/keys` directory within the project.
55+
If you have OpenSSL installed on your machine, you can generate the key by navigating first
56+
into the project directory and then running the following command:
57+
58+
```bash
59+
# Generates a private RSA 40960-bit key named 'rsa-private-key.pem'
60+
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:4096 -out keys/rsa-private-key.pem
61+
```
62+
63+
> **WARNING: This RSA key is included in this project strictly for demonstration and testing purposes.**
64+
> - Do **NOT** use this key in any production environment or for any real-world applications.
65+
> - This key is publicly available and should be considered compromised.
66+
> - Generating and using your own secure keys is essential for maintaining security in your projects.
67+
5368
## Running the example
5469

5570
To run the sample locally, run this command in the DaprClient directory:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
-----BEGIN PRIVATE KEY-----
2+
MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQC0URLpxZCqDv7S
3+
WfROh2Kei4VCEayNu/TK3NaD/QlIpip1rrsPKgTfTOZoRmkmG0Qj59srEJi2GEhL
4+
xpjvRQpA/C/OS+KELU8AeGrqHw7uN/a99NkoAr+zYDCyY9yckPeC5wGxc0/Q6HQT
5+
mWp+YcpR9wFO0PmTVlObssibagjjRNX7z/ZosecOOqjnAqlnYoHMavvoCD5fxM7y
6+
cm7so0JWooXwVaZKgehBEBg1W5F0q5e9ssAQk3lY6IUd5sOskiylTNf/+3r1JU0j
7+
YM8ik3a1/dyDALVXpLSfz7FM9VEj4QjiPF4UuXeBHPDFFiKWbiKfbjqvZ2Sz7Gl7
8+
c5rTk1Fozpr70E/wihrrv22Mxs0sEPdtemQgHXroQfRW8K4FhI0WHs7tR2gVxLHu
9+
OAU9LzCngz4yITh1eixVDmm/B5ZtNVrTQmaY84vGqhrFp+asyFNiXbhUAcT7D/q6
10+
w/c4aQ635ntCFSPYpWvhKqrqVDsoanD/5AWfc3+6Ek2/GVMyEQq+9tnCMM10EVSX
11+
8PsoAWHESDFude5zkHzn7IKy8mh6lfheEbBI5zN9z7WGexyiBgljmyUHXx6Pd8Uc
12+
yxpLRm94kynkDXD9SapQLzXmz+D+X/OYeADMIDWlbdXiIb1+2Q62H1lo6n10KVP7
13+
oEr8BHvcMFY89kwK4lKscUupn8xkzwIDAQABAoICACDuu78Rc8Hzeivt/PZIuMTP
14+
I5f1BWhffy571fwGP2dS3edfcc+rs3cbIuvBjFvG2BOcuYUsg0+isLWSQIVWv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