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);
}
}