11using System ;
22using System . Diagnostics ;
3+ using System . IO ;
34using System . Linq ;
45using System . Runtime . InteropServices ;
56using System . Security . Cryptography ;
67using System . Text ;
78using System . Threading . Tasks ;
9+ using Certify . Models ;
810using Certify . Providers ;
11+ using Microsoft . AspNetCore . DataProtection ;
912
1013namespace 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