Use Elliptic Curve Cryptography (ECDsaCng) without a Key Storage Provider (KSP) - c#

The short version: CngKey.Import throws an exception, even though new ECDsaCng() doesn't.
(EDIT: More narrowed-down question: CngKey.Import(...); succeeds on PC but fails on Web host .)
The long version:
In some scenarios there are permission restrictions and CngKey.Import (which is used to "load" the CngKeyBlobFormat.EccPrivateBlob into the ECDsaCng) throws a CryptographicException.
On the other hand the following does work:
ECDsaCng dsa = new ECDsaCng();
So I assume the problem lies in the attempt to import the key into the KSP.
So far I haven't found a way to transform the EccPrivateBlob into an ECDsaCng, not by the CngKey.Create method, nor by the CngKey.Open method, or any other way.
So how can it be done (without the KSP)?
The error itself:
System.Security.Cryptography.CryptographicException: An internal error
occurred. at
System.Security.Cryptography.NCryptNative.OpenStorageProvider(String
providerName) at System.Security.Cryptography.CngKey.Import(Byte[]
keyBlob, CngKeyBlobFormat format, CngProvider provider) at ...

Related

how to get Android MediaPlayer to recognize audio/aacp correctly?

I have the following problem:
if I hand over an uri with the Content Type audio/aacp to the MediaPlayer for Android, the MediaPlayer won't recognize the content type as it should and throws an exception.
How can I change it so the MediaPlayer recognizes and uses this content type correctly?
Just as a side note i still have uris with different "Content Types" which it recognizes correctly. (and i obviously still need that working)
here is some of my code (i'm not sure if that is helpful or not):
readonly MediaPlayer player;
internal StreamingAudioPlayer(System.Uri uri)
{
player = new MediaPlayer();
player.Completion += OnPlaybackEnded;
player.SetDataSource(Android.App.Application.Context, Uri.Parse(uri.AbsoluteUri));
player.Prepare();
}
If you have any questions or need more information, just say so. I'm happy to provide what I can.
Edit: More information about the exception(s):
if I try to start the app with the uri, I get a Java.IO.IOException: 'Prepare failed.: status=0x1'
In the Output it also says:
[MediaPlayer] Couldn't open (and then the uri here): java.io.FileNotFoundException: No content provider: (uri here)
[System] ClassLoader referenced unknown path: /system/framework/tcmclient.jar
[NetworkSecurityConfig] No Network Security Config specified, using platform default
[MediaPlayer] error (1, -2147483648)
If I start the app by using another uri and then changing to this specifiy uri I get following System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'
The output says this time:
[MediaPlayer] Couldn't open (and then the uri here): java.io.FileNotFoundException: No content provider: (uri here)
[MediaPlayer] error (1, -2147483648)
System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'

C# vs PowerShell. How to get detailed exception info?

I'm using some external library though COM interface.
I have generic class for that.
Database.Connector connector = new Database.Connector();
string connectString = "srvr=nonexisthost;database=test;"; // bogus connect string
try
{
var database = connector.Connect(connectString);
}
catch (COMException ex)
{
Console.WriteLine(ex.Message);
}
Trying to build a error proof logic I intentionally provoke an exception.
And I have discovered that C# COMException contains only generic info, like:
Error HRESULT E_FAIL has been returned from a call to a COM component.
while executing samey code in PowerShell results in more detailed description:
$connector = New-Object -ComObject Database.Connector
$connectString = "srvr=nonexisthost;database=test;"
$database = $connector.Connect($connectString)
Error while executing transaction with an information base
server_addr=nonexisthost descr=11001(0x00002AF9): Host is unknown.
line=1048 file=src\DataExchangeCommon.cpp
My question is: what should I do in order to get same error info in C# (if it is possible)?
I'm not a COM Interop expert but I'll try to answer what I know and hope it will help you.
From the managed side
If the HRESULT is recognized by the runtime (CLR), the runtime automatically creates a specific managed exception for the error (e.g. FileNotFoundException). Otherwise, the runtime creates a generic COMException object which says "I don't know what this HRESULT meaning".
If the unmanaged code provides error info, you will see it in the ErrorCode property, otherwise, you will see just the HRESULT code.
You can try to search for this code (google\github) to obtain more info.
From the unmanaged side
You need to implement ISupportErrorInfo and IErrorInfo interfaces to provide more info.
So to answer your question, in C#, you can't get more info in the COMException object if this info is not provided.
For more info:
COMException, Handling COM Interop Exceptions, IErrorInfo, ISupportErrorInfo, HRESULT's mapping, Common HRESULT values

Invalid URI with UNC path

I have a path that uses some unc paths in the background such as:
\\crfile2\..some folders..\myFile.lbp
and needs to check if the file exists (won't exist in many cases). I have a simple check that reads the file if it exists. It works fine on almost all cases, but I have one customer that is getting an error:
Unhandled Error: Invalid URI: The format of the URI could not be determined.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at RDES.Common.RDLicenseCommon.LicenseBypassData.<GetBypassData>b__0(String x)
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
This seems like a valid UNC path correct? I'm not sure where the error is here, and even more so I find it confusing that my machine and hundreds of others use the same path string with no issues but this one user is getting this issue. I know it's very limited because for him it's cause a crash on startup and the program is used by enough people that when I post something with a critical issue like that I know it from many people in very short order (not that I ever have posted anything like that...). Anyway any help would be appreciated.
Here is the code line where the exception is being thrown:
string myPath = AllValidPaths.Where(x => VerifyFileExists(new Uri(x),500)).FirstOrDefault();
You can see by the stack that the exception is being thrown by the constructor of the URI inside of the lambda expression.

Serializing/Deserializing a roundtrip with NetTopologySuite's IO Library for GeoJson reveals a potential bug

I'm having trouble using NetTopologySuite's GeoJsonReader to deserialize Feature objects. In particular, I'm receiving the following exception (which at first glance seems straightforward, so please read on):
An unhandled exception of type 'System.ArgumentException' occurred in Newtonsoft.Json.dll. Additional information: Expected token '{' not found.
Just doing a simple round-trip results in this exception:
public static string DoIt( Feature feature )
{
GeoJsonWriter writer = new GeoJsonWriter();
var geoJson = writer.Write(feature);
GeoJsonReader reader = new GeoJsonReader();
var deserializedFeature = reader.Read<Feature>(geoJson );
}
in this case, geoJson is pretty straightforward:
"{\"type\":\"Feature\",\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[-104.50348159865847,40.891762392617345],[-104.50348672999991,40.891415817000279],[-104.50355999200002,40.887782408000135],[-104.5036332529998,40.884149000000093],[-104.50845260799991,40.884357883000121],[-104.51307160051412,40.884558081989375],[-104.51307160051412,40.891762392617345],[-104.50348159865847,40.891762392617345]]]},\"properties\":null}"
Please let me know what I'm doing wrong. By the way, I'm using NetTopologySuite 1.14, NetTopologySuite.IO.GeoJSON 1.14, & Json.Net 9.0.1.
this is actually a bug.
code fixed, see #120

How do I check if Metadata exists with ServerManager?

I use the following code to get metadata with Microsoft.Web.Administration.ServerManager:
var manager = new ServerManager();
var site = manager.Sites["siteName"];
var metadata = site.GetMetadata("metaKey");
Now, if "metaKey" is not there, the GetMetadata will throw a System.Runtime.InteropServices.COMException exception with the message "The request is not supported". If I first set a metadata value like this
site.SetMetadata("metaKey", "hello")
the GetMetadata("metaKey") won't throw an error but instead kindly return the value "hello". How do I check if a key exists before I attempt to retreieve it? I want to avoid a try catch if it's possible.
I've tried to dig it a little in disassembling tool. Internally it uses Microsoft.Web.Administration.Interop assembly over native API (as you've already guessed, that is why there is a COMException). Methods to work with metadata are described in IAppHostElement interface.
From it's GetMetadata method's description:
Return value:
S_OK: Indicates that the operation was successful.
ERROR_NOT_SUPPORTED: Indicates that the requested metadata is not recognized.
As you can see, there is no method to check if metadata exists, and interop throws exception in any case when returning result is not S_OK. So unfortunately I guess there is no way to know about the existence of specific metadata without calling GetMatadata method and catching exceptions.

Categories