Reputation: 561
How can I store an object of class RsaSecurityKey https://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.rsasecuritykey(v=vs.110).aspx in a relational database (like Postgres)?
I have to create RsaSecurityKey (first time) and store the key in db and use it in Identity Server (using IdentityServer4 library) for signing Jwt tokens.
Upvotes: 2
Views: 1424
Reputation: 387
Instead of storing the key, you can store the parameters that create the key. The Original RSAParameters won't serialize correctly, this question how to do make it possible. The example below using a file instead of db to store the parameters, but you get the idea.
RSAParameters param;
try{
var json = File.ReadAllText(paramFile);
param = JsonConvert.DeserializeObject<RSAParameters>(json);
}catch(Exception _)
{
param = new RSACryptoServiceProvider(2048).ExportParameters(true);
var jsonString = JsonConvert.SerializeObject(param);
File.WriteAllText(paramFile, jsonString);
}
var securityKey = new RsaSecurityKey(param);
Upvotes: 0
Reputation: 18492
In IdentityServer we serialize the whole RSA key to a JSON object.
You could use the same technique to store the key in a database.
Upvotes: 2
Reputation: 1197
I'm not sure that you will ever be able to store objects of that type to the DB as-is, since they're not serializable - eg: if you try to use the .NET BinaryFormatter
to turn it into a byte array it will fail with a SerializationException
.
A bit of googling shows that there are others that have also run into this issue, eg in the AzureAD project:
https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/591
If you follow the pull request in that issue, there is source code which seems to do what you're looking for. Note: make sure you understand the license if you intend to use it.
Upvotes: 2