-
Notifications
You must be signed in to change notification settings - Fork 853
/
UserCrypto.cs
227 lines (195 loc) · 8.37 KB
/
UserCrypto.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/*******************************************************************************
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using Amazon.Util;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Runtime.Internal.Settings
{
public static class UserCrypto
{
public static string Decrypt(string encrypted)
{
List<Byte> dataIn = new List<byte>();
for (int i = 0; i < encrypted.Length; i = i + 2)
{
byte data = Convert.ToByte(encrypted.Substring(i, 2), 16);
dataIn.Add(data);
}
CryptProtectFlags flags = CryptProtectFlags.CRYPTPROTECT_UI_FORBIDDEN;
DATA_BLOB encryptedBlob = ConvertData(dataIn.ToArray());
DATA_BLOB unencryptedBlob = new DATA_BLOB();
DATA_BLOB dataOption = new DATA_BLOB();
try
{
CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT();
if (!CryptUnprotectData(ref encryptedBlob, "psw", ref dataOption, IntPtr.Zero, ref prompt, flags, ref unencryptedBlob))
{
int errCode = Marshal.GetLastWin32Error();
throw new AmazonClientException("CryptProtectData failed. Error Code: " + errCode);
}
byte[] outData = new byte[unencryptedBlob.cbData];
Marshal.Copy(unencryptedBlob.pbData, outData, 0, outData.Length);
string unencrypted = Encoding.Unicode.GetString(outData);
return unencrypted;
}
finally
{
if (encryptedBlob.pbData != IntPtr.Zero)
Marshal.FreeHGlobal(encryptedBlob.pbData);
if (unencryptedBlob.pbData != IntPtr.Zero)
Marshal.FreeHGlobal(unencryptedBlob.pbData);
}
}
public static string Encrypt(string unencrypted)
{
CryptProtectFlags flags = CryptProtectFlags.CRYPTPROTECT_UI_FORBIDDEN;
DATA_BLOB unencryptedBlob = ConvertData(Encoding.Unicode.GetBytes(unencrypted));
DATA_BLOB encryptedBlob = new DATA_BLOB();
DATA_BLOB dataOption = new DATA_BLOB();
try
{
CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT();
if (!CryptProtectData(ref unencryptedBlob, "psw", ref dataOption, IntPtr.Zero, ref prompt, flags, ref encryptedBlob))
{
int errCode = Marshal.GetLastWin32Error();
throw new AmazonClientException("CryptProtectData failed. Error Code: " + errCode);
}
byte[] outData = new byte[encryptedBlob.cbData];
Marshal.Copy(encryptedBlob.pbData, outData, 0, outData.Length);
StringBuilder encrypted = new StringBuilder();
for (int i = 0; i <= outData.Length - 1; i++)
{
encrypted.Append(
Convert.ToString(outData[i], 16).PadLeft(2, '0').ToUpper(CultureInfo.InvariantCulture));
}
string encryptedPassword = encrypted.ToString().ToUpper(CultureInfo.InvariantCulture);
return encryptedPassword;
}
finally
{
if (unencryptedBlob.pbData != IntPtr.Zero)
Marshal.FreeHGlobal(unencryptedBlob.pbData);
if (encryptedBlob.pbData != IntPtr.Zero)
Marshal.FreeHGlobal(encryptedBlob.pbData);
}
}
static DATA_BLOB ConvertData(byte[] data)
{
DATA_BLOB blob = new DATA_BLOB();
blob.pbData = Marshal.AllocHGlobal(data.Length);
blob.cbData = data.Length;
Marshal.Copy(data, 0, blob.pbData, data.Length);
return blob;
}
#region PInvoke Declarations
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct DATA_BLOB
{
public int cbData;
public IntPtr pbData;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct CRYPTPROTECT_PROMPTSTRUCT
{
public int cbSize;
public CryptProtectPromptFlags dwPromptFlags;
public IntPtr hwndApp;
public String szPrompt;
}
[Flags]
private enum CryptProtectPromptFlags
{
// prompt on unprotect
CRYPTPROTECT_PROMPT_ON_UNPROTECT = 0x1,
// prompt on protect
CRYPTPROTECT_PROMPT_ON_PROTECT = 0x2
}
[Flags]
private enum CryptProtectFlags
{
// for remote-access situations where ui is not an option
// if UI was specified on protect or unprotect operation, the call
// will fail and GetLastError() will indicate ERROR_PASSWORD_RESTRICTION
CRYPTPROTECT_UI_FORBIDDEN = 0x1,
// per machine protected data -- any user on machine where CryptProtectData
// took place may CryptUnprotectData
CRYPTPROTECT_LOCAL_MACHINE = 0x4,
// force credential synchronize during CryptProtectData()
// Synchronize is only operation that occurs during this operation
CRYPTPROTECT_CRED_SYNC = 0x8,
// Generate an Audit on protect and unprotect operations
CRYPTPROTECT_AUDIT = 0x10,
// Protect data with a non-recoverable key
CRYPTPROTECT_NO_RECOVERY = 0x20,
// Verify the protection of a protected blob
CRYPTPROTECT_VERIFY_PROTECTION = 0x40
}
[DllImport("Crypt32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CryptProtectData(
ref DATA_BLOB pDataIn,
String szDataDescr,
ref DATA_BLOB pOptionalEntropy,
IntPtr pvReserved,
ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct,
CryptProtectFlags dwFlags,
ref DATA_BLOB pDataOut
);
[DllImport("Crypt32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CryptUnprotectData(
ref DATA_BLOB pDataIn,
String szDataDescr,
ref DATA_BLOB pOptionalEntropy,
IntPtr pvReserved,
ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct,
CryptProtectFlags dwFlags,
ref DATA_BLOB pDataOut
);
static bool? _isUserCryptAvailable;
public static bool IsUserCryptAvailable
{
get
{
if(!_isUserCryptAvailable.HasValue)
{
try
{
Encrypt("test");
_isUserCryptAvailable = true;
}
catch(Exception e)
{
var logger = Logger.GetLogger(typeof(UserCrypto));
logger.InfoFormat("UserCrypto is not supported. This may be due to use of a non-Windows operating system or Windows Nano Server, or the current user account may not have its profile loaded. {0}", e.Message);
_isUserCryptAvailable = false;
}
}
return _isUserCryptAvailable.Value;
}
}
#endregion
}
}