HashAlgorithms in CoreCLR - asp.net-core

I'm trying use this class in my coreclr project but I can't seem to find the correct package for SHA256Managed. I have tried using System.Security.Cryptography.Algorithms": "4.0.0-beta-23409" but it doesn't contain the implementation of SHA2565Managed. Are there any other alternative for computing hash values in coreclr?

You can use SHA256.Create() from namespace System.Security.Cryptography
(Assembly: System.Security.Cryptography.Algorithms)
using (var algorithm = SHA256.Create())
{
// Create the at_hash using the access token returned by CreateAccessTokenAsync.
var hash = algorithm.ComputeHash(Encoding.ASCII.GetBytes(response.AccessToken));
// Note: only the left-most half of the hash of the octets is used.
// See http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
identity.AddClaim(JwtRegisteredClaimNames.AtHash, Base64UrlEncoder.Encode(hash, 0, hash.Length / 2));
}

Related

CryptographicEngine::SignHashedData not implemented error

I encountered an error while using cppwinrt. When I use CryptographicEngine::SignHashedData function to sign a hash value, it returns WinRT originate error - 0x80004001 : 'not implemented'.
Here is the code:
#include "pch.h"
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Security::Cryptography;
using namespace Windows::Security::Cryptography::Core;
using namespace Windows::Storage::Streams;
using namespace std;
int main()
{
init_apartment();
IBuffer buffKeyPair;
IBuffer buffPublicKey;
IBuffer nullBuff(nullptr);
uint32_t asymmetricKeyLength = 512;
hstring strMsg = L"zzp yes!";
hstring strAsymmetricAlgName = AsymmetricAlgorithmNames::RsaPkcs1();
hstring strAlgNameH = HashAlgorithmNames::Md5();
AsymmetricKeyAlgorithmProvider objAlgProv = AsymmetricKeyAlgorithmProvider::OpenAlgorithm(strAsymmetricAlgName);
CryptographicKey keyPair = objAlgProv.CreateKeyPair(asymmetricKeyLength);
IBuffer buffUtf8Msg = CryptographicBuffer::ConvertStringToBinary(strMsg, BinaryStringEncoding::Utf8);
HashAlgorithmProvider objAlgH = HashAlgorithmProvider::OpenAlgorithm(strAlgNameH);
IBuffer buffHash = objAlgH.HashData(buffUtf8Msg);
IBuffer signedBuff = CryptographicEngine::SignHashedData(keyPair, buffHash);
hstring strHashHex = CryptographicBuffer::EncodeToHexString(signedBuff);
std::cout << "the strHashHex is: " << winrt::to_string(strHashHex) << std::endl;
}
Could you please help me find the problem? Thanks!
I'm not too experienced in this space, but I think I figured out a couple issues. This is happening because you aren't using an algorithm that can be used for signing, and you aren't using a hash algorithm compatible with it. The docs seem a bit... sparse... in this regard, but the algorithm names that have "sign" in them looked promising.
After a little experimentation, I got this to work.
using namespace Windows::Security::Cryptography;
using namespace Windows::Security::Cryptography::Core;
using namespace Windows::Storage::Streams;
using namespace std;
int main()
{
init_apartment();
auto algo_name = AsymmetricAlgorithmNames::RsaSignPkcs1Sha1();
auto asymmetric_provider = AsymmetricKeyAlgorithmProvider::OpenAlgorithm(algo_name);
auto keyPair = asymmetric_provider.CreateKeyPair(512);
auto md5_hasher = HashAlgorithmProvider::OpenAlgorithm(HashAlgorithmNames::Sha1());
auto buffHash = md5_hasher.HashData(
CryptographicBuffer::ConvertStringToBinary(
L"Hello world", BinaryStringEncoding::Utf8));
auto signature = CryptographicEngine::SignHashedData(keyPair, buffHash);
auto publicKey = asymmetric_provider.ImportPublicKey(keyPair.ExportPublicKey());
auto match = CryptographicEngine::VerifySignatureWithHashInput(
publicKey, buffHash, signature);
}
Notice that I used RsaSignPkcs1Sha1 which seems to indicate that this algorithm can do signing. Also, for the hash algorithm, I used Sha1. Using Md5 gave a different runtime error (and Md5 is pretty weak, anyway). I also added the code to show how to use your key pair's public key to verify the signature.
After try your code and more tests, I have found that RsaSignPkcs1Sha1 is needed when you want to sign a content, the RsaPkcs1 does not support signing. Besides, I found that Windows only support RSA signing with SHA hashes, it does not support sign a md5 hash. Further more, the two names (RsaSignPkcs1Sha1 and Sha1) must match, or you will encounter an error. I don't known how it works in the back. I also found that sign a content with the sign function is equvalent with sign a content's hash with SignHashedData function, It seems that sign function first computes the hash before signing it.

Readding all key batch wise using stack exchange Redis client

i am using StackExchange.Redis (2.1.58) , i write below code by using cursor .
Dictionary<string, string> keyResult = new Dictionary<string, string>();
var Server = Connection.GetServer(Connection.GetEndPoints()[0]);
long current_cursor = 0;
int next_cursor =-1;
long page_size = 10;
while(next_cursor!=0)
{
var allkeys = Server.Keys(RedisCache.Database, argKeyPattern, 10, 0, next_cursor==-1 ? 0 : next_cursor);
var cursor = ((StackExchange.Redis.IScanningCursor)allkeys);
foreach (var key in allkeys)
{
if (current_cursor == cursor.Cursor)
{
keyResult.Add(key, RedisCache.StringGet(key));
}
else
{
next_cursor = Convert.ToInt32(cursor.Cursor);
current_cursor = next_cursor;
break;
}
}
}
this code works fine , my question is there any other approach to read keys from Redis batch wise in more efficient way ?
Thanks !!
From the documentation
The Keys(...) method deserves special mention: it is unusual in that it does not have an *Async counterpart. The reason for this is that behind the scenes, the system will determine the most appropriate method to use (KEYS vs SCAN, based on the server version), and if possible will use the SCAN approach to hand you back an IEnumerable that does all the paging internally - so you never need to see the implementation details of the cursor operations. If SCAN is not available, it will use KEYS, which can cause blockages at the server.
From first looks, KEYS command should be avoid. However, the library already fix that for you by using SCAN if the command is available. So I think you're good here.
if SCAN command is not available so Keys() will fallback to using KEYS command
SCAN command is available in version 2.8++

.Net Core Image Manipulation (Crop & Resize) / File Handling

I have spent the last 5 hours trying to find a feasible way to accomplish what seems to me quite an easy task if it was a previous version of the .NET family that I was working with:
Uploading a picture
Resizing & Cropping the picture
Saving the new picture into a directory
I have come accross to couple of libraries that are either in pre-release stage or in a not-complete stage.
Has anyone at all accomplished the above tasks without specifically including the System.Drawing namespace and/or adding a dependency for an earlier version of the .NET framework?
UPDATE on 08 / 08 / 2016
I ended up using System.Drawing something which is very annoying and disappointing. If you are developing a software used by thousands of developers, and if all these developers are relying on the components of this software, I believe, one cannot just come up with a new version, "sweet talk" about it during the conferences to show off your public speaking skills rather than giving a shit about your work and on one hand proudly hold in high esteem of it, and on the other, strip away the mostly used and demanded portions of it.
I do understand and appreciate with great excitement myself - of the new era of .net with the core framework - being a loyal asp dev since the first days of classic asp - however, to me, it is just an uncomplete product causing more frustrations and dissappointment than pleasure. When there are millions of websites in today's content-driven world, completely relying on content management, you can't just come up and say, "Hey, I have this brilliant, techonology, leaner, faster blah blah" but errr, you will have some problems with "managing" your content..
It should not be forgotten that, although, MS (and us) is very excited about this new core framework, with now being open source etc, there are other languages and frameworks out there that are doing what MS is promising to do, for a very very long time now.
ImageSharp
ImageSharp is a new, fully featured, fully managed, cross-platform, 2D graphics API.
Designed to democratize image processing, ImageSharp brings you an incredibly powerful yet beautifully simple API.
Compared to System.Drawing we have been able to develop something much more flexible, easier to code against, and much, much less prone to memory leaks. Gone are system-wide process-locks; ImageSharp images are thread-safe and fully supported in web environments.
Built against .Net Standard 1.1 ImageSharp can be used in device, cloud, and embedded/IoT scenarios.
You can use the Microsoft ASP.NET Core JavaScript Services to invoke arbitrary NPM packages at runtime from .NET code which means you can choose any npm package that provide image scaling and invoke it.
The following example shows how to use JavaScriptServices to resize image
https://github.com/aspnet/JavaScriptServices/tree/dev/samples/misc/NodeServicesExamples
Hope that Helps
.NET Core Image Processing blog post (January 19, 2017) compares 6 libraries:
CoreCompat.System.Drawing
ImageSharp
Magick.NET (Win only)
SkiaSharp
FreeImage-dotnet-core
MagicScaler
Feb 26 update: post was updated, two new packages added
To complete the #Hossam Barakat answer, you can use the Microsoft ASP.NET Core JavaScript Services to invoke arbitrary NPM packages at runtime from .NET code which means you can choose any npm package that provide image scaling and invoke it.
The sample use the sharp module, which has a lot of dependecies. If you prefere, like me, to use jimp which is pure javascript:
Startup.cs
public class Startup
{
...
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Enable Node Services
services.AddNodeServices();
...
}
...
}
ImageController.cs
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.NodeServices;
using Microsoft.AspNetCore.StaticFiles;
using System.Security.Cryptography;
using System.Text;
namespace NodeServicesExamples.Controllers
{
public class ResizeImageController : Controller
{
private const int MaxDimension = 1000;
private static string[] AllowedMimeTypes = new[] { "image/jpeg", "image/png", "image/gif" };
private IHostingEnvironment _environment;
private INodeServices _nodeServices;
public ResizeImageController(IHostingEnvironment environment, INodeServices nodeServices)
{
_environment = environment;
_nodeServices = nodeServices;
}
[Route("resize/{*imagePath}")]
[ResponseCache(Duration = 3600)]
public async Task<IActionResult> Index(string imagePath, double maxWidth, double maxHeight)
{
// Validate incoming params
if (maxWidth < 0 || maxHeight < 0 || maxWidth > MaxDimension || maxHeight > MaxDimension
|| (maxWidth + maxHeight) == 0)
{
return BadRequest("Invalid dimensions");
}
var mimeType = GetContentType(imagePath);
if (Array.IndexOf(AllowedMimeTypes, mimeType) < 0)
{
return BadRequest("Disallowed image format");
}
// Locate source image on disk
var fileInfo = _environment.WebRootFileProvider.GetFileInfo(imagePath);
if (!fileInfo.Exists)
{
return NotFound();
}
var eTag = GenerateETag(Encoding.UTF8.GetBytes($"{fileInfo.LastModified.ToString("s")}-{fileInfo.Length}"));
HttpContext.Response.Headers["ETag"] = eTag;
var match = HttpContext.Request.Headers["If-None-Match"].FirstOrDefault();
if (eTag == match)
{
return StatusCode(304);
}
// Invoke Node and pipe the result to the response
var imageStream = await _nodeServices.InvokeAsync<Stream>(
"./Node/resizeImage",
fileInfo.PhysicalPath,
mimeType,
maxWidth,
maxHeight);
return File(imageStream, mimeType, fileInfo.Name);
}
private string GetContentType(string path)
{
string result;
return new FileExtensionContentTypeProvider().TryGetContentType(path, out result) ? result : null;
}
private string GenerateETag(byte[] data)
{
string ret = string.Empty;
using (var md5 = MD5.Create())
{
var hash = md5.ComputeHash(data);
string hex = BitConverter.ToString(hash);
ret = hex.Replace("-", "");
}
return ret;
}
}
}
Node\resizeImage.js
var jimp = require("jimp");
module.exports = function (result, physicalPath, mimeType, maxWidth, maxHeight) {
// Invoke the 'jimp' NPM module, and have it pipe the resulting image data back to .NET
jimp.read(physicalPath).then(function (file) {
var width = maxWidth || jimp.AUTO;
var height = maxHeight || jimp.AUTO;
file.resize(maxWidth, height)
.getBuffer(mimeType, function (err, buffer) {
var stream = result.stream;
stream.write(buffer);
stream.end();
});
}).catch(function (err) {
console.error(err);
});
};
install jimp: npm install jimp --save
Short answer is no, not yet. Most if not all current libraries rely on System.Drawing. If you need this now, I would go that route and add System.Drawing.
The .NET team is currently working through the features that are missing on the Core 1.0 stack, but this one isn't high enough on their priority list: Link
This is a library to watch as they're getting very close to a releasable API without System.Drawing. : ImageSharp
use SkiSharp, it is on the official microsoft documentation also:
https://learn.microsoft.com/en-us/dotnet/api/skiasharp?view=skiasharp-1.68.0

SymmetricAlgorithm' does not contain a definition for 'Create'

I'm trying to work on ASP.NET 5 application. Here is a class and it looks good (no red curly underlines). But when I try to build, it gives error - SymmetricAlgorithm' does not contain a definition for 'Create'
using System;
using System.IO;
using System.Security.Cryptography;
namespace SalesBook
{
public static class Encryptor
{
private static byte[] EncryptString(string data)
{
byte[] byteData = Common.GetByte(data);
SymmetricAlgorithm algo = SymmetricAlgorithm.Create();
}
}
}
I'm using .net 4.6.1.
Any help?
This method has not been ported to .NET Core. The recommended alternative is to use the specific Create method associated with the algorithm you need:
var algorithm = Aes.Create();
On CoreCLR, it will automatically determine and return the best implementation, depending on your OS environement.
If you don't need .NET Core support, you can remove the dnxcore50/dotnet5.4 from your project.json.

How to extract class IL code from loaded assembly and save to disk?

How would I go about extracting the IL code for classes that are generated at runtime by reflection so I can save it to disk? If at all possible. I don't have control of the piece of code that generates these classes.
Eventually, I would like to load this IL code from disk into another assembly.
I know I could serialise/deserialise classes but I wish to use purely IL code. I'm not fussed with the security implications.
Running Mono 2.10.1
Or better yet, use Mono.Cecil.
It will allow you to get at the individual instructions, even manipulating them and disassembling them (with the mono decompiler addition).
Note that the decompiler is a work in progress (last time I checked it did not fully support lambda expressions and Visual Basic exception blocks), but you can have pretty decompiled output in C# pretty easily as far as you don't hit these boundary conditions. Also, work has progressed since.
Mono Cecil in general let's you write the IL to a new assembly, as well, which you can then subsequently load into your appdomain if you like to play with bleeding edge.
Update I came round to trying this. Unfortunately I think I found what problem you run into. It turns out there is seems to be no way to get at the IL bytes for a generated type unless the assembly happened to get written out somewhere you can load it from.
I assumed you could just get the bits via reflection (since the classes support the required methods), however the related methods just raise an exception The invoked member is not supported in a dynamic module. on invocation. You can try this with the code below, but in short I suppose it means that it ain't gonna happen unless you want to f*ck with Marshal::GetFunctionPointerForDelegate(). You'd have to binary dump the instructions and manually disassemble them as IL opcodes. There be dragons.
Code snippet:
using System;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using System.Reflection.Emit;
using System.Reflection;
namespace REFLECT
{
class Program
{
private static Type EmitType()
{
var dyn = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("Emitted"), AssemblyBuilderAccess.RunAndSave);
var mod = dyn.DefineDynamicModule("Emitted", "Emitted.dll");
var typ = mod.DefineType("EmittedNS.EmittedType", System.Reflection.TypeAttributes.Public);
var mth = typ.DefineMethod("SuperSecretEncryption", System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.Static, typeof(String), new [] {typeof(String)});
var il = mth.GetILGenerator();
il.EmitWriteLine("Emit was here");
il.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
il.Emit(System.Reflection.Emit.OpCodes.Ret);
var result = typ.CreateType();
dyn.Save("Emitted.dll");
return result;
}
private static Type TestEmit()
{
var result = EmitType();
var instance = Activator.CreateInstance(result);
var encrypted = instance.GetType().GetMethod("SuperSecretEncryption").Invoke(null, new [] { "Hello world" });
Console.WriteLine(encrypted); // This works happily, print "Emit was here" first
return result;
}
public static void Main (string[] args)
{
Type emitted = TestEmit();
// CRASH HERE: even if the assembly was actually for SaveAndRun _and_ it
// has actually been saved, there seems to be no way to get at the image
// directly:
var ass = AssemblyFactory.GetAssembly(emitted.Assembly.GetFiles(false)[0]);
// the rest was intended as mockup on how to isolate the interesting bits
// but I didn't get much chance to test that :)
var types = ass.Modules.Cast<ModuleDefinition>().SelectMany(m => m.Types.Cast<TypeDefinition>()).ToList();
var typ = types.FirstOrDefault(t => t.Name == emitted.Name);
var operands = typ.Methods.Cast<MethodDefinition>()
.SelectMany(m => m.Body.Instructions.Cast<Instruction>())
.Select(i => i.Operand);
var requiredTypes = operands.OfType<TypeReference>()
.Concat(operands.OfType<MethodReference>().Select(mr => mr.DeclaringType))
.Select(tr => tr.Resolve()).OfType<TypeDefinition>()
.Distinct();
var requiredAssemblies = requiredTypes
.Select(tr => tr.Module).OfType<ModuleDefinition>()
.Select(md => md.Assembly.Name as AssemblyNameReference);
foreach (var t in types.Except(requiredTypes))
ass.MainModule.Types.Remove(t);
foreach (var unused in ass.MainModule
.AssemblyReferences.Cast<AssemblyNameReference>().ToList()
.Except(requiredAssemblies))
ass.MainModule.AssemblyReferences.Remove(unused);
AssemblyFactory.SaveAssembly(ass, "/tmp/TestCecil.dll");
}
}
}
If all you want is the IL for your User class, you already have it. It's in the dll that you compiled it to.
From your other assembly, you can load the dll with the User class dynamically and use it through reflection.
UPDATE:
If what you have is a dynamic class created with Reflection.Emit, you have an AssemblyBuilder that you can use to save it to disk.
If your dynamic type was instead created with Mono.Cecil, you have an AssemblyDefinition that you can save to disk with myAssemblyDefinition.Write("MyAssembly.dll") (in Mono.Cecil 0.9).