Rectangle 27 5

Creating NuGet package from class library

If you use Visual Studio 2015 RC and later: go to your class library project properties, open Build tab and check Produce outputs on build option:

{SolutionDir}\artifacts\bin\{ProjectName}\{Configuration}
  • Make sure you installed DNVM and DNX (see ASP.NET Home repo for instructions).
  • Run dnu pack in the project directory. NuGet package will be created in {ProjectDir}\bin\{Configuration} directory by default.

To use the class library in another project from the same solution, add it as a usual project reference in Visual Studio or to dependencies property in project.json:

"dependencies": {
  "ClassLibrary1": ""
}

To use the library in other solutions, publish NuGet package to nuget.org or any other NuGet feed and add it to your project using Visual Studio (References ~> Manage NuGet Packages...) or to dependencies property in project.json.

How to create and use ASP.NET vNext class library NuGet package? - Sta...

nuget-package asp.net-core dnx
Rectangle 27 9

I wouldn't bother with the NuGet package for this, simply because this is not a class library - which is technically, what NuGet is all about. ChromeDriver has also been updated many times since that release.

Anyway, I would say that I have just done the same thing to see what the issue is:

  • Using Visual Studio, add a new item to the project by right-clicking on the project -> Add Item -> Existing Item
  • Navigate and select the chromedriver.exe

You are probably falling down on point 4. That setting is set to Do not copy by default.

Adding the file manually is a good work around, but any ideas why NuGet is not adding the "tools" folder to the PATH environment variable? (It's documentation suggests that it should)

I wonder if Visual Studio has to be run as administrator for the path variables to be able to be set?

I tried this - adding the diver manually in the project root, after installing the NuGet package. The result was that every time I tried to run the code, TWO instances of chromedriver.exe was started. And then when I tried to run it again, it didn't work because the chromedriver.exe was in use by another process. Switching from Release to Debug worked exactly ONCE, then never again. This solution is at best flaky, and should NOT have been accepted as an answer imo.

@FrankH. probably, but I never experienced that issue, so it's possible you've got something else going on. This is an old answer so it's entirely possible there are better ways of achieving it.

c# - Selenium WebDriver.ChromeDriver Nuget package installed, but not ...

c# visual-studio selenium-webdriver mstest selenium-chromedriver
Rectangle 27 5

Kpm is the package manager for the new KRuntime. Instructions on how to install the KRuntime command line utilities on your developer machine can be found on the aspnet Home repo. Once you have kvm and a version of the KRuntime set up you will have kpm available as well.

Now you can run kpm build on your class libraries project location. Output should be something like this:

kpm build src\ClassLibrary1\
ClassLibrary1 -> C:\Users\username\Documents\Visual Studio 14\Projects\WebApplication1\src\ClassLibrary1\bin\Debug\ClassLibrary1.1.0.0.nupkg
ClassLibrary1 -> C:\Users\username\Documents\Visual Studio 14\Projects\WebApplication1\src\ClassLibrary1\bin\Debug\ClassLibrary1.1.0.0.symbols.nupkg

Build succeeded.
    0 Warnings(s)
    0 Error(s)

Time elapsed 00:00:01.7556414

The easiest way to add a reference to a class project is to do it in your project.json, assuming you have it in the same solution. Here is an example project.json from a web application, which references a class library called ClassLibrary1.

{
    "webroot" : "wwwroot",
    "exclude": "wwwroot/**/*.*",
    "dependencies": {
        "Microsoft.AspNet.Server.IIS": "1.0.0-alpha4",
        "ClassLibrary1": ""
    },
    "frameworks" : {
        "aspnet50" : { },
        "aspnetcore50" : { }
    }
}
kpm build

Note: VS14 CTP4 only works with alpha4 of the KRuntime. If you want to use VS14 for vNext without errors popping up you need to downgrade your KRuntime to version 1.0.0-alpha4.

I've retracted my answer but leaving as comment in case anybody else comes here trying to figure this out for regular class libraries: I used Nuget Package Explorer to create the nuget packgage for the third party dll's that I needed to reference. After simple drag & drop of dll in lib folder and filling out basic metadata in explorer, I created the package and added the path to Nuget Package Manager (CTP4 version) lookup directories. After that I added the nuget package name directly in project.json and it picked up like it picks up any other online packages.

I've tried this, but it breaks. My class library has a dependency on "mongocsharpdriver": "1.9.2", it's in the project.json and it builds fine in VS. However it can't find this dependency when I try to build with kpm. It doesn't complain for Microsoft dependencies though. Any ideas?

Hard to say. The package location was moved between alpha3 and alpha4 so it might be that. Make sure your runtime is alpha4 at least. I tried using that package in a simple vnext project and it builds just fine.

1.0.0-alpha4 CLR x86

How to create and use ASP.NET vNext class library NuGet package? - Sta...

nuget-package asp.net-core dnx
Rectangle 27 2

In your class library project, make sure that the required ASP.NET MVC nuget package is added, same way as your web project itself.

It will add the various missing assemblies in your class library project, like System.Web.Mvc, System.Web.Razor etc.

In that case, why not add a test project instead of a class library?

c# - Namespace not recognised after adding MVC6 project dependency to ...

c# .net asp.net-core-mvc portable-class-library class-library
Rectangle 27 2

net40
"frameworks": {
    "net40": {},
    "dnx451": { },
    "dnxcore50": {}
 }

Thanks a lot. This was what I was looking for.

Referencing a nuget package create by an asp.net 5 class library from ...

nuget asp.net-core visual-studio-2015
Rectangle 27 100

Why does the name have "ASP.NET" in it?

There are a number of benefits of ASP.NET 5 Class Library projects (.kproj) over Class Library projects (.csproj):

  • ASP.NET 5 class libraries easily support cross-compiling projects to multiple targets, such as aspnet50, aspnetcore50, net45, and various other portable class library variations. This includes rich Visual Studio support for Intellisense to notify you which APIs are available for which targets.
  • NuGet packages are automatically created, which is an extremely common thing to do with class libraries.
  • Better productivity when it comes to things like automatically refreshing Solution Explorer when the file system changes. Fewer conflicts in source control when trying to merge conflicting changes in the *.csproj file.

You can reference a *.csproj project from a *.kproj project (this was just made a lot easier with the new preview of Visual Studio 2015), but it was always possible with some manual steps.

As far as the names goes, it's a relic of history that will soon be addressed. The new project type is useful far beyond ASP.NET 5 applications. Expect to see new names in a future preview of Visual Studio:

With the release of Visual Studio 2015 RC you can see the updated project template names:

These use the project.json file and the .NET Execution Environment (DNX) to build, run, and package (into a NuGet package) the project.

These project templates continue to show up in the New Project dialog under the "Web" node, but now also show up in the main "Visual C#" node as well.

can you expand on #2 - do you mean the intellisense suggests an API and then downloads the nuget package for you? I type JQuery and it'll give it to me?

@Simon_Weaver I mean that whereas the regular Class Library project produces just a DLL and PDB, the new one generates a NUPKG (NuGet package) that can be uploaded to nuget.org.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

c# - Why create an ASP.NET 5 Class Library project? - Stack Overflow

c# asp.net asp.net-mvc asp.net-core
Rectangle 27 7

Another advantage are that the vNext projects output nuget-packages on build, while pre-vNext class libraries only output DLLs. If you specify multiple target frameworks in your project.json file the nuget-package from building will contain a DLL built for all of these target frameworks.

As an example here is a project.json:

{
    "dependencies": {
        "Microsoft.Framework.DependencyInjection": "1.0.0-*",
        "System.Linq": "4.0.0.0",
    },
    "frameworks": {
        "net45": {},
        "aspnetcore50": {}
    }
}

If you run the "kpm build" command from the class libraries project folder it will output a nuget-package containing the following files.

lib/aspnetcore50/ProjectName.dll
lib/aspnetcore50/ProjectName.xml
lib/net45/ProjectName.dll
lib/net45/ProjectName.xml

When you reference this class library from other projects it will use the correct DLL depending on the target framework it requires.

Does it has anything to do with ASP.NET? I mean why it is named as ASP.NET vNext Class library (& available under web category in VS 14 as these benefits are available for other project types as well?

Currently only the ASP.NET vNext projects use the new project structure so no it is not a benefit available to other project types. It is called ASP.NET vNext Class Library because only ASP.NET projects can use them currently (without jumping through some hoops). There is a uservoice to support project.json for all project types over here visualstudio.uservoice.com/forums/121579-visual-studio/. Go vote it up. :)

Great, that explains it. Thanks and voted up! :-)

c# - Difference Between Class Library & ASP.NETvNext Class Library? - ...

c# class-library asp.net-core
Rectangle 27 3

I just run into this problem today. I have data repository class library with EF63 NuGet package and console application for testing, which have reference only to class library project. I created very simple post-build command, which copies EntityFramework.SqlServer.dll from class library's Bin\Debug folder to console application's Bin\Debug folder and problem solved. Do not forget to add entityFramework section to console application's .config file.

No Entity Framework provider found for the ADO.NET provider with invar...

entity-framework
Rectangle 27 3

I just run into this problem today. I have data repository class library with EF63 NuGet package and console application for testing, which have reference only to class library project. I created very simple post-build command, which copies EntityFramework.SqlServer.dll from class library's Bin\Debug folder to console application's Bin\Debug folder and problem solved. Do not forget to add entityFramework section to console application's .config file.

No Entity Framework provider found for the ADO.NET provider with invar...

entity-framework
Rectangle 27 2

The new feature of .NET Core and Class Library (Package) is that it targets multiple platform and will compile into multiple assemblies which get automatically packaged into a nuget package.

When your class library targets multiple targets, it will compile to all of them. So if a certain library is only available on full .NET framework but not on .NET Core or other target framework, then you may receive intellisense if your editor is set to .NET 4.5. More information can be found in my other recent answer.

You can switch back and forth with the pull down menu on top left of the coding window, show in the screenshot below.

If you do not want to target a certain framework, you have to remove it's moniker from the project.json file or use preprocessor directives to write platform specific code or libraries/replacements.

.NET Core is heavily modularized and most of only the core modules are referenced in the default project and if you need additional one you need to reference them within the dotnet5.x section.

Basically you have multiple places with "dependencies" in your project.json, a global one where you can add dependencies which are available on all targeted frameworks and one within each "frameworks" section for each of the targets only.

c# - Class library references on Visual Studio 2015 - Stack Overflow

c# .net visual-studio-2015 asp.net-core
Rectangle 27 203

I got annoyed by this recently too. I fixed it by putting a wrapper function in the Configuration class in the Seed method, and replaced calls to SaveChanges with calls to my function instead. This function would simply enumerate the errors within the EntityValidationErrors collection, and rethrow an exception where the Exception message lists the individual problems. This makes the output show up in the NuGet package manager console.

/// <summary>
/// Wrapper for SaveChanges adding the Validation Messages to the generated exception
/// </summary>
/// <param name="context">The context.</param>
private void SaveChanges(DbContext context) {
    try {
        context.SaveChanges();
    } catch (DbEntityValidationException ex) {
        StringBuilder sb = new StringBuilder();

        foreach (var failure in ex.EntityValidationErrors) {
            sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
            foreach (var error in failure.ValidationErrors) {
                sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                sb.AppendLine();
            }
        }

        throw new DbEntityValidationException(
            "Entity Validation Failed - errors follow:\n" + 
            sb.ToString(), ex
        ); // Add the original exception as the innerException
    }
}
context.SaveChanges()
SaveChanges(context)

I used this technique but used an override of savechanges inside the context instead. public override int SaveChanges() inside the context.

If you are doing UserManager operations in your seed method then this change won't include the validation errors in the output, you would need to override the DBContext SaveChanges, SaveChangesAsync and SaveChangesAsync(CT) methods as per @jwize answer.

asp.net mvc 3 - EF Code First: How do I see 'EntityValidationErrors' p...

asp.net-mvc-3 entity-framework entity-framework-4 nuget
Rectangle 27 203

I got annoyed by this recently too. I fixed it by putting a wrapper function in the Configuration class in the Seed method, and replaced calls to SaveChanges with calls to my function instead. This function would simply enumerate the errors within the EntityValidationErrors collection, and rethrow an exception where the Exception message lists the individual problems. This makes the output show up in the NuGet package manager console.

/// <summary>
/// Wrapper for SaveChanges adding the Validation Messages to the generated exception
/// </summary>
/// <param name="context">The context.</param>
private void SaveChanges(DbContext context) {
    try {
        context.SaveChanges();
    } catch (DbEntityValidationException ex) {
        StringBuilder sb = new StringBuilder();

        foreach (var failure in ex.EntityValidationErrors) {
            sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
            foreach (var error in failure.ValidationErrors) {
                sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                sb.AppendLine();
            }
        }

        throw new DbEntityValidationException(
            "Entity Validation Failed - errors follow:\n" + 
            sb.ToString(), ex
        ); // Add the original exception as the innerException
    }
}
context.SaveChanges()
SaveChanges(context)

I used this technique but used an override of savechanges inside the context instead. public override int SaveChanges() inside the context.

If you are doing UserManager operations in your seed method then this change won't include the validation errors in the output, you would need to override the DBContext SaveChanges, SaveChangesAsync and SaveChangesAsync(CT) methods as per @jwize answer.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

asp.net mvc 3 - EF Code First: How do I see 'EntityValidationErrors' p...

asp.net-mvc-3 entity-framework entity-framework-4 nuget
Rectangle 27 3

From what I understand one benefit is that the end product of ASP.NET 5 Class Library project is a NuGet package (rather than just the .dll assembly).

You can generate the NuGet package by right clicking the project in Visual Studio 2015 and choosing the "Publish..." option. Or you can use "KPM pack" at the command line.

Also, you have the ability to use the ASP.NET 5 Core runtime so that your library can run cross-platform .

One of the key goals of ASP.NET 5 is to allow it to run cross platform. Some have asked "shouldn't this be called .NET Core instead?" At least for now Microsoft's multi-platform approach is only about the web (and console apps) and doesn't support desktop development like Java. To emphasise it's about the web they're branding it all under the name "ASP.NET 5". If you're wanting to produce a library that runs cross platform it should be an ASP.NET 5 Class Library.

It means I can tell my boss 'yes' when he asks 'is ASP.NET the best technology' - that's why

c# - Why create an ASP.NET 5 Class Library project? - Stack Overflow

c# asp.net asp.net-mvc asp.net-core
Rectangle 27 1

For the record, I had a similar issue in a class library with a reference to MVC. I installed a nuget package in the class library that itself had a dependency on MVC (note: the new package was: RazorGenerator.Mvc). Previously, the class library relied on a Sytem.Web.Mvc.dll reference added using the 'Add Reference' dialogue rather than on one installed via the "Microsoft.AspNet.Mvc" nuget package.

Nuget chose the lowest MVC version that would meet the dependency requirements of the new package. That meant that the previous reference (to MVC 5) was replaced with a lower version reference (to MVC 3).

Upgrading the MVC version in the class library using nuget resolved the issue.

c# - The type or namespace name 'HttpGet' could not be found when add ...

c# asp.net-mvc http-post http-get
Rectangle 27 1

For the record, I had a similar issue in a class library with a reference to MVC. I installed a nuget package in the class library that itself had a dependency on MVC (note: the new package was: RazorGenerator.Mvc). Previously, the class library relied on a Sytem.Web.Mvc.dll reference added using the 'Add Reference' dialogue rather than on one installed via the "Microsoft.AspNet.Mvc" nuget package.

Nuget chose the lowest MVC version that would meet the dependency requirements of the new package. That meant that the previous reference (to MVC 5) was replaced with a lower version reference (to MVC 3).

Upgrading the MVC version in the class library using nuget resolved the issue.

c# - The type or namespace name 'HttpGet' could not be found when add ...

c# asp.net-mvc http-post http-get
Rectangle 27 1

I followed the same procedure as mentioned in your question

This is probably what you need to do. Also, I believe the correct framework to target for class library projects is net451, not dnx451. Because class libraries do not have a dnx run entry point like web & console apps do.

@danludwig I guess net451 and dnx451 are meant for giving names to framework target and its dependencies. Am I right?

Turns out I had a couple issues, the first as @danludwig pointed out I needed to target net451 for a class library - my own fault for trying to do things manually! I also needed to increment my version number and rebuild before re-installing.

tbh I am not really sure. I think dnx451 and net451 both target the same runtime framework, but that targeting dnx451 just designates a project as an application entry point (class libraries by definition are not application entry points). @MisterEpic, glad you got the answer you were looking for.

asp.net - Target specific framework in Class Library (Package) - Stack...

asp.net visual-studio-2015 asp.net-core asp.net-core-mvc .net-core
Rectangle 27 42

do you happen to have any assembly binding redirects in your web.config? if yes, could you share them...i am specifically looking if there are any related to System.Web.Http* assemblies..

c# - GlobalConfiguration.Configure() not present after Web API 2 and ....

c# asp.net-web-api asp.net-mvc-5 asp.net-4.5
Rectangle 27 42

do you happen to have any assembly binding redirects in your web.config? if yes, could you share them...i am specifically looking if there are any related to System.Web.Http* assemblies..

c# - GlobalConfiguration.Configure() not present after Web API 2 and ....

c# asp.net-web-api asp.net-mvc-5 asp.net-4.5
Rectangle 27 1

As far as I am aware, Nuget tracks library dependencies using the metadata stored in the nuget package file. If I were you I'd avoid implementing arbitrary restrictions. What if one of your plugin developers wants to create a shared support library of useful classes, for example?

To my mind, a plugin should be a black box of functionality. If a plugin needs another plugin, then they should communicate via a standardized messaging platform rather than directly.

That said, you could always scrape all interface implementations from the library you load and hook those up as well as your plugins. That way the plugin developer can "request" implementations of those interfaces as well as plugins.

You'll need to cope with massive class libraries (I recommend only hooking up in Ninject interfaces that are referenced in plugin constructors) and with potential conflicts (two plugins might expect separate implementations of the same interface - which is the main reason I believe that a plugin should take care of itself internally, rather than hoping its design time expectations are fulfilled by the external plugin manager).

And in answer to (2), as long as the methods and properties you reference don't change name or signature, you shouldn't have any problems using a newer version of DLL B with DLL A. If you change a return type, change from a public field (which shouldn't exist in the first place) to a public property, change the parameters on a method or anything of that nature on a class that you're using from DLL B in DLL A, a recompile of A would be required.

c# - Design pattern for plugin dependencies (similar to Nuget package ...

c# design-patterns plugins
Rectangle 27 45

BouncyCastle is a great Crypto library for .NET, it's available as a Nuget package for install into your projects. I like it a lot more than what's currently available in the System.Security.Cryptography library. It gives you a lot more options in terms of available algorithms, and provides more modes for those algorithms.

This is an example of an implementation of TwoFish, which was written by Bruce Schneier (hero to all us paranoid people out there). It's a symmetric algorithm like the Rijndael (aka AES). It was one of the three finalists for the AES standard and sibling to another famous algorithm written by Bruce Schneier called BlowFish.

First thing with bouncycastle is to create an encryptor class, this will make it easier to implement other block ciphers within the library. The following encryptor class takes in a generic argument T where T implements IBlockCipher and has a default constructor.

UPDATE: Due to popular demand I have decided to implement generating a random IV as well as include an HMAC into this class. Although from a style perspective this goes against the SOLID principle of single responsibility, because of the nature of what this class does I reniged. This class will now take two generic parameters, one for the cipher and one for the digest. It automatically generates the IV using RNGCryptoServiceProvider to provide good RNG entropy, and allows you to use whatever digest algorithm you want from BouncyCastle to generate the MAC.

using System;
using System.Security.Cryptography;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;

public sealed class Encryptor<TBlockCipher, TDigest>
    where TBlockCipher : IBlockCipher, new()
    where TDigest : IDigest, new()
{
    private Encoding encoding;

    private IBlockCipher blockCipher;

    private BufferedBlockCipher cipher;

    private HMac mac;

    private byte[] key;

    public Encryptor(Encoding encoding, byte[] key, byte[] macKey)
    {
        this.encoding = encoding;
        this.key = key;
        this.Init(key, macKey, new Pkcs7Padding());
    }

    public Encryptor(Encoding encoding, byte[] key, byte[] macKey, IBlockCipherPadding padding)
    {
        this.encoding = encoding;
        this.key = key;
        this.Init(key, macKey, padding);
    }

    private void Init(byte[] key, byte[] macKey, IBlockCipherPadding padding)
    {
        this.blockCipher = new CbcBlockCipher(new TBlockCipher());
        this.cipher = new PaddedBufferedBlockCipher(this.blockCipher, padding);
        this.mac = new HMac(new TDigest());
        this.mac.Init(new KeyParameter(macKey));
    }

    public string Encrypt(string plain)
    {
        return Convert.ToBase64String(EncryptBytes(plain));
    }

    public byte[] EncryptBytes(string plain)
    {
        byte[] input = this.encoding.GetBytes(plain);

        var iv = this.GenerateIV();

        var cipher = this.BouncyCastleCrypto(true, input, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] message = CombineArrays(iv, cipher);

        this.mac.Reset();
        this.mac.BlockUpdate(message, 0, message.Length);
        byte[] digest = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];
        this.mac.DoFinal(digest, 0);

        var result = CombineArrays(digest, message);
        return result;
    }

    public byte[] DecryptBytes(byte[] bytes)
    {
        // split the digest into component parts
        var digest = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];
        var message = new byte[bytes.Length - digest.Length];
        var iv = new byte[this.blockCipher.GetBlockSize()];
        var cipher = new byte[message.Length - iv.Length];

        Buffer.BlockCopy(bytes, 0, digest, 0, digest.Length);
        Buffer.BlockCopy(bytes, digest.Length, message, 0, message.Length);
        if (!IsValidHMac(digest, message))
        {
            throw new CryptoException();
        }

        Buffer.BlockCopy(message, 0, iv, 0, iv.Length);
        Buffer.BlockCopy(message, iv.Length, cipher, 0, cipher.Length);

        byte[] result = this.BouncyCastleCrypto(false, cipher, new ParametersWithIV(new KeyParameter(key), iv));
        return result;
    }

    public string Decrypt(byte[] bytes)
    {
        return this.encoding.GetString(DecryptBytes(bytes));
    }

    public string Decrypt(string cipher)
    {
        return this.Decrypt(Convert.FromBase64String(cipher));
    }

    private bool IsValidHMac(byte[] digest, byte[] message)
    {
        this.mac.Reset();
        this.mac.BlockUpdate(message, 0, message.Length);
        byte[] computed = new byte[this.mac.GetUnderlyingDigest().GetDigestSize()];
        this.mac.DoFinal(computed, 0);

        return AreEqual(digest,computed);
    }

    private static bool AreEqual(byte [] digest, byte[] computed)
    {
        if(digest.Length != computed.Length)
        {
            return false;
        }

        int result = 0;
        for (int i = 0; i < digest.Length; i++)
        {
            // compute equality of all bytes before returning.
            //   helps prevent timing attacks: 
            //   https://codahale.com/a-lesson-in-timing-attacks/
            result |= digest[i] ^ computed[i];
        }

        return result == 0;
    }

    private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, ICipherParameters parameters)
    {
        try
        {
            cipher.Init(forEncrypt, parameters);

            return this.cipher.DoFinal(input);
        }
        catch (CryptoException)
        {
            throw;
        }
    }

    private byte[] GenerateIV()
    {
        using (var provider = new RNGCryptoServiceProvider())
        {
            // 1st block
            byte[] result = new byte[this.blockCipher.GetBlockSize()];
            provider.GetBytes(result);

            return result;
        }
    }

    private static byte[] CombineArrays(byte[] source1, byte[] source2)
    {
        byte[] result = new byte[source1.Length + source2.Length];
        Buffer.BlockCopy(source1, 0, result, 0, source1.Length);
        Buffer.BlockCopy(source2, 0, result, source1.Length, source2.Length);

        return result;
    }
}

Next just call the encrypt and decrypt methods on the new class, here's the example using twofish:

var encrypt = new Encryptor<TwofishEngine, Sha1Digest>(Encoding.UTF8, key, hmacKey);

string cipher = encrypt.Encrypt("TEST");   
string plainText = encrypt.Decrypt(cipher);

It's just as easy to substitute another block cipher like TripleDES:

var des = new Encryptor<DesEdeEngine, Sha1Digest>(Encoding.UTF8, key, hmacKey);

string cipher = des.Encrypt("TEST");
string plainText = des.Decrypt(cipher);

Finally if you want to use AES with SHA256 HMAC you can do the following:

var aes = new Encryptor<AesEngine, Sha256Digest>(Encoding.UTF8, key, hmacKey);

cipher = aes.Encrypt("TEST");
plainText = aes.Decrypt(cipher);

The hardest part about encryption actually deals with the keys and not the algorithms. You'll have to think about where you store your keys, and if you have to, how you exchange them. These algorithms have all withstood the test of time, and are extremely hard to break. Someone who wants to steal information from you isn't going to spend eternity doing cryptanalysis on your messages, they're going to try to figure out what or where your key is. So #1 choose your keys wisely, #2 store them in a safe place, if you use a web.config and IIS then you can encrypt parts of the the web.config, and finally if you have to exchange keys make sure that your protocol for exchanging the key is secure.

Update 2 Changed compare method to mitigate against timing attacks. See more info here http://codahale.com/a-lesson-in-timing-attacks/ . Also updated to default to PKCS7 padding and added new constructor to allow end user the ability to choose which padding they would like to use. Thanks @CodesInChaos for the suggestions.

1) That class is pretty annoying to use since you put the burden of IV management on the user who will almost certainly get it wrong. 2) Lack of MAC makes this vulnerable to padding oracles.

1) Your padding looks broken to me. You add a zero padding and don't remove it. Zero padding is a bad idea since it can't be removed reliably. Use PKCS#7 padding instead. I'd expect the bouncycastle encryption/decryption function to already support this. 2) You should use a constant time comparison to validate the MAC, not SequenceEqual. This avoids a timing side-channel that leaks how long a prefix of the presented MAC and the actual MAC match.

great answer, just one question....what would be the key and hmacKey, i'm new to crypto..thanks !

@Terkhos You should use a secure random number generator for generating keys like RNGCryptoServiceProvider, you should never use a passphrase or something predictable. You should also use the maximum length that the algorithm will provide for example AES 256 uses a key size that's 256 bits in length so 32 random bytes would be best, HMAC key sizes are typically are based on the size of the algorithm for example SHA2 (256) a 256 bit key generated by a secure random number generator would suffice. Change keys often! The more often the better!

c# - Encrypt and decrypt a string - Stack Overflow

c# .net encryption mono cryptography