我正在为我的Azure项目使用加密技术,我遇到了RsaKey的问题。当用户注册应用程序时,会创建一个RsaKey并将其与用户关联。这是代码:
string storageConnectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");
CloudStorageAccount storageAccount;
try
{
storageAccount = CloudStorageAccount.Parse(storageConnectionString);
}
catch (FormatException)
{
Console.WriteLine("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the sample.");
Console.WriteLine("Press any key to exit");
Console.ReadLine();
throw;
}
catch (ArgumentException)
{
Console.WriteLine("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the sample.");
Console.WriteLine("Press any key to exit");
Console.ReadLine();
throw;
}
CloudTableClient client = storageAccount.CreateCloudTableClient();
CloudTable table = client.GetTableReference(tableName);
RsaKey key = new RsaKey(item.PartitionKey);
TableRequestOptions insertOptions = new TableRequestOptions()
{
EncryptionPolicy = new TableEncryptionPolicy(key, null)
};
table.Execute(TableOperation.Insert(item), insertOptions, null);
在此之后我必须使RsaKey持久化,然后将其存储在用户容器中的专用blob中。由于RsaKey不是Serializable,我使用Json字符串的一些“技巧”。代码如下:
string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(key);
using (var stream = new MemoryStream(Encoding.Default.GetBytes(jsonString), false))
{
blob.UploadFileToBlob(item.PartitionKey, "key", stream); // this method creates a blob called "key" in the container named [item.PartitionKey] and stores the stream
}
注册后,我当然需要使用RsaKey来执行某些操作,比如访问一些隐藏字段,可以访问其他blob中的某些特殊文件等。在这种情况下,我在这个例子中做了什么:
User user = GetUser();
Resolver res = new Resolver();
res.Add(user.PartitionKey);
TableRequestOptions retrieveOptions = new TableRequestOptions()
{
EncryptionPolicy = new TableEncryptionPolicy(null, res)
};
// Retrieve Entity
string storageConnectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");
CloudStorageAccount storageAccount;
try
{
storageAccount = CloudStorageAccount.Parse(storageConnectionString);
}
catch (FormatException)
{
Console.WriteLine("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the sample.");
Console.WriteLine("Press any key to exit");
Console.ReadLine();
throw;
}
catch (ArgumentException)
{
Console.WriteLine("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the sample.");
Console.WriteLine("Press any key to exit");
Console.ReadLine();
throw;
}
CloudTableClient client = storageAccount.CreateCloudTableClient();
CloudTable table = client.GetTableReference("user");
TableOperation operation = TableOperation.Retrieve(user.PartitionKey, user.RowKey);
TableResult result;
try
{
result = table.Execute(operation, retrieveOptions, null);
}
catch (Exception e) { }
Resolver是一个实现IKeyResolver的类,它必须定义ResolveKeyAsync
方法来执行检索操作。以下是此类的代码:
public class Resolver: IKeyResolver
{
TableUtility table;
BlobUtility blob;
string container;
public Resolver()
{
table = new TableUtility();
blob = new BlobUtility();
}
public void Add(string container){
this.container= container;
}
public async Task<IKey> ResolveKeyAsync(string kid, CancellationToken token)
{
IKey result;
string jsonString = blob.BlobToText(container, "key"); // this method goes to the blob "key" in the container named [container] and download the content of the blob using a MemoryStream
var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
result = Newtonsoft.Json.JsonConvert.DeserializeObject<RsaKey>(jsonString);
return await Task.FromResult(result);
}
}
实际上我的问题是反序列化的RsaKey与前一个不同。尽管jsonString
已正确设置属性,但result
的“Kid”字段不同,可能导致反序列化操作中的隐式实例化(并且可能创建了一个新的Kid)。因此,我尝试使用我存储的相同Kid(RsaKey key = new RsaKey(partitionKey)
)创建一个新的RsaKey,但检索操作失败(TableResult result
仍为null
)。你有什么建议?也许我必须改变持久性机制?
修改
当我尝试在try / catch块中执行table.Execute(operation, retrieveOptions, null);
时(使用RsaKey key = new RsaKey(partitionKey)
实例化RsaKey),这是抛出的异常:
Microsoft.WindowsAzure.Storage.StorageException was caught
_HResult=-2146233088
_message=Decryption logic threw error. Please check the inner exception for more details.
HResult=-2146233088
IsTransient=false
Message=Decryption logic threw error. Please check the inner exception for more details.
Source=Microsoft.WindowsAzure.Storage
IsRetryable=false
StackTrace:
in Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 820
in Microsoft.WindowsAzure.Storage.Table.TableOperation.Execute(CloudTableClient client, CloudTable table, TableRequestOptions requestOptions, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Table\TableOperation.cs:line 41
in Microsoft.WindowsAzure.Storage.Table.CloudTable.Execute(TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Table\CloudTable.cs:line 53
in WebRole.Controllers.AccountController.IsProfileCompleted() in c:\Users\HP\Source\Repos\scalablepredictor\WebRole\Controllers\AccountController.cs:line 343
InnerException: System.AggregateException
_HResult=-2146233088
_message=One or more errors occured.
HResult=-2146233088
IsTransient=false
Message=One or more errors occured.
Source=mscorlib
StackTrace:
in System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
in Microsoft.WindowsAzure.Storage.Table.TableEncryptionPolicy.DecryptMetadataAndReturnCEK(String partitionKey, String rowKey, EntityProperty encryptionKeyProperty, EntityProperty propertyDetailsProperty, EncryptionData& encryptionData) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Table\TableEncryptionPolicy.cs:line 205
InnerException: System.Security.Cryptography.CryptographicException
_HResult=-2146233296
_message=Error occurred while decoding OAEP padding.
HResult=-2146233296
IsTransient=false
Message=Error occurred while decoding OAEP padding.
Source=mscorlib
StackTrace:
in System.Security.Cryptography.RSACryptoServiceProvider.DecryptKey(SafeKeyHandle pKeyContext, Byte[] pbEncryptedKey, Int32 cbEncryptedKey, Boolean fOAEP, ObjectHandleOnStack ohRetDecryptedKey)
in System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(Byte[] rgb, Boolean fOAEP)
in Microsoft.Azure.KeyVault.Cryptography.Algorithms.RsaOaep.RsaOaepDecryptor.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
in Microsoft.Azure.KeyVault.RsaKey.<UnwrapKeyAsync>d__6.MoveNext()
InnerException: