Skip to content

Commit 06e6ce4

Browse files
Implement non-windows data protection
1 parent 2ad254f commit 06e6ce4

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

src/Certify.Shared/Management/CredentialsUtil.cs

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
using System;
22
using System.Diagnostics;
3+
using System.IO;
34
using System.Linq;
45
using System.Runtime.InteropServices;
56
using System.Security.Cryptography;
67
using System.Text;
78
using System.Threading.Tasks;
9+
using Certify.Models;
810
using Certify.Providers;
11+
using Microsoft.AspNetCore.DataProtection;
912

1013
namespace Certify.Management
1114
{
@@ -52,6 +55,7 @@ public static string Protect(
5255

5356
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
5457
{
58+
// protect using DAPI
5559
if (scope == null)
5660
{
5761
scope = DataProtectionScope.CurrentUser;
@@ -66,13 +70,12 @@ public static string Protect(
6670
}
6771
else
6872
{
69-
#if RELEASE
70-
Trace.Assert(true, "Using dummy encryption, not suitable for production use.");
71-
#endif
72-
Trace.WriteLine("Using dummy encryption, not suitable for production use.");
73+
// protect using platform data protection provider
7374

74-
// TODO: dummy implementation, require alternative implementation for non-windows
75-
return Convert.ToBase64String(Encoding.UTF8.GetBytes(clearText).Reverse().ToArray());
75+
var protector = GetDataProtector();
76+
var clearBytes = Encoding.UTF8.GetBytes(clearText);
77+
var protectedBytes = protector.Protect(clearBytes);
78+
return Convert.ToBase64String(protectedBytes);
7679
}
7780
}
7881

@@ -111,11 +114,19 @@ public static string Unprotect(
111114
}
112115
else
113116
{
114-
Debug.WriteLine("Using dummy encryption, not suitable for production use.");
115-
// TODO: dummy implementation, implement alternative implementation for non-windows
116-
var bytes = Convert.FromBase64String(encryptedText);
117-
return Encoding.UTF8.GetString(bytes.Reverse().ToArray());
117+
// protect using platform data protection provider
118+
var protector = GetDataProtector();
119+
var encryptedBytes = Convert.FromBase64String(encryptedText);
120+
var clearBytes = protector.Unprotect(encryptedBytes);
121+
return Encoding.UTF8.GetString(clearBytes);
118122
}
119123
}
124+
125+
private static IDataProtector GetDataProtector()
126+
{
127+
var keyDirectory = EnvironmentUtil.CreateAppDataPath("credentials");
128+
var dataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(keyDirectory));
129+
return dataProtectionProvider.CreateProtector("StoredCredentials");
130+
}
120131
}
121132
}

0 commit comments

Comments
 (0)