Cryptography service now handles random byte generation

Protected strings are now protected in memory
This commit is contained in:
Geoffroy BONNEVILLE
2020-05-18 14:14:28 +02:00
parent ceaf7dabd3
commit 9126307b4c
22 changed files with 134 additions and 105 deletions

View File

@@ -1,4 +1,5 @@
using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.DataProtection;
@@ -10,24 +11,34 @@ namespace ModernKeePass.Infrastructure.UWP
{
public async Task<string> Protect(string value)
{
// Create a DataProtectionProvider object for the specified descriptor.
var provider = new DataProtectionProvider();
if (string.IsNullOrEmpty(value)) return value;
try
{
// Create a DataProtectionProvider object for the specified descriptor.
var provider = new DataProtectionProvider("LOCAL=user");
// Encode the plaintext input message to a buffer.
var buffMsg = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8);
// Encode the plaintext input message to a buffer.
var buffMsg = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8);
// Encrypt the message.
var buffProtected = await provider.ProtectAsync(buffMsg).AsTask().ConfigureAwait(false);
// Encode buffer to Base64
var protectedValue = CryptographicBuffer.EncodeToBase64String(buffProtected);
// Encrypt the message.
var buffProtected = await provider.ProtectAsync(buffMsg);
// Encode buffer to Base64
var stringProtected = CryptographicBuffer.EncodeToBase64String(buffProtected);
// Return the encrypted string.
return stringProtected;
// Return the encrypted string.
return protectedValue;
}
catch (Exception e)
{
return string.Empty;
}
}
public async Task<string> UnProtect(string value)
{
if (string.IsNullOrEmpty(value)) return value;
// Create a DataProtectionProvider object.
var provider = new DataProtectionProvider();
@@ -35,13 +46,18 @@ namespace ModernKeePass.Infrastructure.UWP
var buffProtected = CryptographicBuffer.DecodeFromBase64String(value);
// Decrypt the protected message specified on input.
var buffUnprotected = await provider.UnprotectAsync(buffProtected);
var buffUnprotected = await provider.UnprotectAsync(buffProtected).AsTask().ConfigureAwait(false);
// Convert the unprotected message from an IBuffer object to a string.
var strClearText = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffUnprotected);
var clearText = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffUnprotected);
// Return the plaintext string.
return strClearText;
return clearText;
}
public byte[] Random(uint length)
{
return CryptographicBuffer.GenerateRandom(length).ToArray();
}
}
}