I cannot find the System.Security.Cryptography.RNGCryptoServiceProvider class in .NetCore.
It is essential to the application I am trying to port from .Net Framework, as it is being used to generate an initialisation vector for encryption.
Does it exist under a different name, or is there another way of achieving this functionality?
System.Security.Cryptography.RandomNumberGenerator is the base class for Cryptographically-Secure Pseudo-Random Number Generator (CSPRNG) implementations. In .NET Framework RandomNumberGenerator.Create() returns an RNGCryptoServiceProvider instance (unless configured differently by CryptoConfig). In .NET Core RandomNumberGenerator.Create() returns an opaque type which is based on BCryptGenRandom (Windows) or OpenSSL's random number generator (!Windows).
RandomNumberGenerator.Create() is the only way to get an RNG instance on .NET Core, and since it works on both .NET Core and .NET Framework is the most portable.
Of course, if you're generating an IV, you can also just call the instance method SymmetricAlgorithm.GenerateIV() to have it use the CSPRNG internally; though as the documentation says, calling it is unnecessary as a random IV is created with the instance (GenerateIV can be used to force it to generate a new one before the next call to CreateEncryptor).
One of the solutions suggested is to use RandomNumberGenerator.Create()
https://github.com/dotnet/corefx/issues/2881
We can do it like this in .Net core. It worked for me.
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
var byteArray = new byte[4];
provider.GetBytes(byteArray);
//convert 4 bytes to an integer
var randomInteger = BitConverter.ToUInt32(byteArray, 0);
It is present under the namespace : System.Security.Cryptography
add this in your class to use the method :
using System.Security.Cryptography;
Hope it is Helpful.
Thanks
Related
I have inherited a .net framework console app that uses a custom authenticator to connect to a third party API. It works fine and authenticates against the API.
I have migrated this code to .NET Core as I need it part of our main application. The conversion has gone well accept i still couldn't get the authentication to work.
Below is the code that run to register a new authentication method. It's pretty standard.
private static AuthenticationModule registerAuthenticationModule(Uri loginServerUrl)
{
IEnumerator registeredModules = AuthenticationManager.RegisteredModules;
AuthenticationModule authenticationModule;
while (registeredModules.MoveNext())
{
object current = registeredModules.Current;
if (current is AuthenticationModule)
{
authenticationModule = (AuthenticationModule)current;
if (authenticationModule.LoginServerUrl.Equals(loginServerUrl))
{
return authenticationModule;
}
}
}
authenticationModule = new AuthenticationModule(loginServerUrl);
AuthenticationManager.Register(authenticationModule);
displayRegisteredModules();
return authenticationModule;
}
In the .net framework version, AuthenticationManager.RegisteredModules returns 5 standard authentication methods e.g. digest, basic. When i run this within .NET Core it returns none. In fact the list that should store the modules also doesn't exist.
When i then add the new authentication module using AuthenticationManager.Register nothing happens. There is no additional authentication module on the list (which still doesn't exist).
Here is the .NET Framework list showing 5 standard methods plus the custom one at the bottom.
Here is the .NET Core list.
There is very little documentation on the web around this and this is not my area of expertise. Can anyone please give some suggestions as to why this might not be working in .net core. I suspect if i can get this populated it will fix my issues.
Hope the below link would help you to sort the issue with.net core conversion.
What Is The Alternate Of AuthenticationManager In .Net Core
Cheers
seems that Portable Class Library does not support PerSession (Wshttpbinding) required for this.
Is there any work around for this?
i have xamarin forms application (server client) that users can connect to their own database and get or update data.
once the user provide his username and password some information must be stored to their sessions like database connection string and when data request from user then the appropriate connection string that is stored to his session will be used for that database and send the data back.
otherwise without persession i have to pass on every function the connection string from the client.
how can i avoid this? Portable Class Library does not support wshttpbinding and therefore i cannot use PerSession
any help?
Too much Headache
The obstacles are too much for anyone working with the following combination
Xamarin Forms
PCL (Portable Class Libray)
WCF
IClientMessageInspector
The Problem:
I was need to have a multi client application that each one can connect to his own database ( same schema all )
For this purpose i was looking to store some information at a session level like (Connection String,User Information) so when a method called to know from which database i will retreive the data .
Problem # 1 ( took me 5 days to understand and realized)
that Sessions cannot be worked with PCL ( WCF PerSession) why? Because PerSession Needs WsHttpBinding but PCL Does not support WsHttpBinding only BasicHttp
Problem # 2 (took me 3 days to understand why is not working)
Then i saw many posts here and there about implementing IClientMessageInspector (see examples online how to implement IClientMessageInspector it's easy) so every time a client request a call to send some extra info to the server together with the call in my case was the connectionString. Here i was getting an exception that
NotImplementedException. Why? because of this BUG in MONO
https://bugzilla.xamarin.com/show_bug.cgi?id=40064
in simple words
When creating a WCF client in a PCL (targetting .NET Core) you must use EndpointBehaviors and not Behaviors. This works fine in a Windows RT application, but Mono has not implemented this so produces NotImplementedException in Android and iOS.
The answer is on the link above by another reply from someone else and i thank him for that .
In simple words
Instead of
MyService.Endpoint.EndpointBehaviors(New MyBehavior)
Use
Dim prop = MyService.Endpoint.GetType.GetTypeInfo.GetDeclaredProperty("Behaviors")
Dim obj = CType(prop.GetValue(MyService.Endpoint), KeyedCollection(Of Type, IEndpointBehavior))
obj.Add(New Behavior)
and instead of
clientRuntime.ClientMessageInspectors.Add(New MyInspector)
Use
Public Sub ApplyClientBehavior(endpoint As ServiceEndpoint, clientRuntime As ClientRuntime) Implements IEndpointBehavior.ApplyClientBehavior
Dim prop = clientRuntime.GetType.GetTypeInfo.GetDeclaredProperty("MessageInspectors")
Dim obj = CType(prop.GetValue(clientRuntime), ICollection(Of IClientMessageInspector))
obj.Add(New MyInspector)
End Sub
No changes needed to the configuration file
Hope this help someday someone.
I am currently working on a .NET Core project where I use the Microsoft.Azure.Servicebus version 1.0 NuGet package found here: https://github.com/Azure/azure-service-bus
The problem I have is that I haven't found any method to get a queue's number of active messages. This used to be pretty easy with .NET framework using the ServicebusNamespace.NamespaceManager, referring to a queue and use the .ActiveMessageCount.
Is this possible in some other way in this library with .NET Core 1.1?
It is now possible using the latest version of the Service Bus library (3.1.1):
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Management;
var client = new ManagementClient(connectionString);
var queue = await client.GetQueueRuntimeInfoAsync(queuePath);
var counts = queue.MessageCountDetails;
var subs = await client.GetSubscriptionRuntimeInfoAsync(topic, subscription);
var countForThisSubscription = subs.MessageCount; //// (Comes back as a Long.)
The .NET Standard client (Microsoft.Azure.ServiceBus) is deliberately not providing management operations. It states that management operations should not be performed at run time. Management operations are extremely slow.
Is this possible in some other way in this library with .NET Core 1.1?
Yes, it is possible.
Instead of the NamespaceManager that was available with the old client (WindowsAzure.ServiceBus), there's a ServiceBus management library (Microsoft.Azure.Management.ServiceBus.Fluent)
You will need to do the following:
Authenticate using ServiceBusManager
Access the namespace you're interested in via ServiceBusManager.Namespaces
Filter out the entity you're interested in by locating it under ServiceBusManager.Namespaces.Queues/ServiceBusManager.Namespaces.Topics. For subscription you'll need to locate one via ITopic object.
Once you've got your entity (IQueue, ITopic, or ISubscription), you'll be able to access the message counts.
I'm not a big fan of this approach. Rather than each developer reinventing this wheel, Azure Service Bus team should have provided a helper library to replace NamespaceManger. You can always raise an issue or vote for an issue that was closed.
Management operations were introduced back in version 3.1.1 with pull request #481.
I have a WCF Restful Service that returns JSON objects that my iPhone and Android apps consume nicely. This is my first attempt at building something like this and I left WP7 till last as my background lies with C# and VS2010. But it seems it’s not going to be a simple as I had guessed.
So I guess I have three questions:
1, Can I consume JSON objects in WP7? If so does anyone know of a tutorial?
2, if not, can I use the existing service and build some new contracts for consumption in WP7? Or,
3, do I need to build a whole new service?
Option one is most desirable but either way, I need to develop for all three operating systems so does anyone know the best type of model to bring this all together???
Cheers,
Mike.
Yes, but not with the channel factory / proxy programming model which you may be used to with WCF. REST services are usually consumed by using some simpler classes such as WebClient. You can use the JSON libraries (DataContractJsonSerializer is in the WP7 profile) then to deserialize the data you receive. Even the untyped JSON (the System.Json classes from the System.Json.dll on Silverlight), while not officially in the profile, they kind of work on WP7 as well (I've seen a few people simply referencing the SL library on a WP7 project).
If you want proxy support, you can add a new endpoint to the service using BasicHttpBinding, which is supported in WP7; if you don't need it, see 1).
No. See 1) and 2).
Try this to deserialize a JSON object:
public static T Deserialize<T>(string strData) where T : class
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
byte[] byteArray = Encoding.UTF8.GetBytes(strData);
MemoryStream memoryStream = new MemoryStream(byteArray);
T tRet = serializer.ReadObject(memoryStream) as T;
memoryStream.Dispose();
return tRet;
}
I find a totally wcf-based approach more interesting.
This is a good post that addresses this issue
http://blogs.msdn.com/b/carlosfigueira/archive/2010/04/29/consuming-rest-json-services-in-silverlight-4.aspx
Can I deserialize an object in the Silverlight 3.0 runtime that was serialized using the full .NET 2.0 runtime using the BinaryFormatter? I am using the following code to serialize an object to a ByteArray which we write to a DB table:
MemoryStream serStream = new MemoryStream();
BinaryFormatter binFormatter = new BinaryFormatter();
binFormatter.Serialize(serStream, csMetric);
serStream.Position = 0;
return serStream.ToArray();
The Silverlight client then needs to retrieve this binary data from the DB (via a Web service call) and deserizlize the bytes back into an instance of the csMetric class.
Is this possible? If so, how is that done on the client given that the BinaryFormatter is not availble in the SL 3.0 runtime?
Thanks,
jon
Since you have to go through WCF, and thus the full .NET Framework, to get the data into Silverlight anyway I'd recommend deserializing the object on the server before sending it back to Silverlight. The Silverlight 3 WCF stack supports binary WCF encoding which should make the data transfer reasonably efficient.
Jon,
Have you tried to deserialize the object using the DataContractSerializer? I have not tested this exact scenario, but this is how I would approach it:
the following is an extension method off of a byte array (byte[]):
pubilc static T Deserialize<T>(this byte[] yourSerializedByteArray)
{
T deserializedObject;
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
using(MemoryStream ms = new MemoryStream(yourSerializedByteArray))
{
deserializedObject = (T)serializer.ReadObject(ms);
}
return deserializedObject;
}
Maybe one would like to try my SharpSerializer. It can serialize data to the both binary and xml format. It works on .NET Full, Compact und Silverlight.
DataContractSerializer has a whole bunch of problems, I've created a binary serializer that removes some of them (at least for me!) It uses reflection and produces reasonably compact representations that can be sent to WCF services.
More info here.