Giter Site home page Giter Site logo

pclcrypto's Introduction

PCLCrypto

PCLCrypto provides cryptographic APIs over algorithms implemented by the platform, including exposing them to portable libraries. PCLCrypto does not implement any crypto directly, thus making this library a good choice for applications that require the assurance of high quality crypto implementations that can most reliably be found within the operating system itself or hardware.

Build Status NuGet package Join the chat at https://gitter.im/AArnott/PCLCrypto

Features

  • Cryptographically strong random number generator
  • Symmetric and asymmetric encryption and signatures
  • Key derivation
  • Native crypto performance for each platform. This provides a 2-100X perf improvement for RSA on Android and iOS.
  • Streaming encryption on UAP, which goes beyond what the WinRT API itself offers (while still relying on the OS for the crypto implementation).
  • Support for multiple key formats (PKCS#1, PKCS#8, CAPI) on all platforms.

The API is designed to be similar to that found on WinRT or the .NET Framework. However some code changes may be required if migrating to this library from platform-specific crypto.

Installation

Add a dependency to this library into your project via the PCLCrypto NuGet package:

NuGet package

When using packages.config, you must be sure to install this package into each app project as well as any libraries in order to consume the right PCLCrypto.dll runtime library for the target platform. If you use PackageReference (preferred), this happens automatically.

Installing via NuGet is important because we use facade assemblies and platform-specific assemblies to allow your portable libraries to access crypto that is normally available only to platform-specific libraries using a technique Paul Betts calls Bait and switch PCLs. NuGet handles all the magic for you.

Documentation

Online documentation is available on our project wiki site.

Donations

If you appreciate this library and/or find it useful, please consider becoming a GitHub sponsor for its author or donating bitcoins to 1NC4k82nNev5Cz7ESBfaohbGsC6TKyjKvX or any other mechanism shown on their Keybase profile.

FAQ

  1. Can I trust the crypto implemented in this library?

    This library does not implement crypto. It merely provides .NET Standard-compatible APIs to invoke crypto, and at runtime the crypto offered by the platform is invoked. So you should be able to trust the crypto available through this library almost as much as you can trust the crypto in the operating system your application is already running on.

C# 6 Tip

One of the new features of C# 6 is using static, which bring static members of static classes into scope. You can take advantage of this feature with PCLCrypto to simplify your code:

Before:

...
using PCLCrypto;

class TwitterClient
{
    private static string GenerateHash(string input, string key)
    {
        var mac = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha1);
        var keyMaterial = WinRTCrypto.CryptographicBuffer.ConvertStringToBinary(key, Encoding.UTF8);
        var cryptoKey = mac.CreateKey(keyMaterial);
        var hash = WinRTCrypto.CryptographicEngine.Sign(cryptoKey, WinRTCrypto.CryptographicBuffer.ConvertStringToBinary(input, Encoding.UTF8));
        return WinRTCrypto.CryptographicBuffer.EncodeToBase64String(hash);
    }
}

After:

...
using PCLCrypto;
using static PCLCrypto.WinRTCrypto;

class TwitterClient
{
  private static string GenerateHash(string input, string key)
  {
      var mac = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha1);
      var keyMaterial = CryptographicBuffer.ConvertStringToBinary(key, Encoding.UTF8);
      var cryptoKey = mac.CreateKey(keyMaterial);
      var hash = CryptographicEngine.Sign(cryptoKey, CryptographicBuffer.ConvertStringToBinary(input, Encoding.UTF8));
      return CryptographicBuffer.EncodeToBase64String(hash);
  }
}

pclcrypto's People

Contributors

aarnott avatar benoitjadinon avatar dependabot[bot] avatar gitter-badger avatar jonathanpeppers avatar mattleibow avatar vithati avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pclcrypto's Issues

Windows phone 8.1 IHashAlgorithmProvider CreateHash not supported

Im not sure if this is intended or a bug. When i call my PCL library from a windows phone 8.1 silverlight application(both with PCLCrypto referenced) and IHashAlgorithm.CreateHash() or HashData(..) is called a Specified method is not supported exception.
Current Example:

var mac = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(alg);
var keyMaterial = WinRTCrypto.CryptographicBuffer.ConvertStringToBinary(key, System.Text.Encoding.UTF8);

var hashBin = mac.HashData(keyMaterial);
var hash = WinRTCrypto.CryptographicBuffer.EncodeToHexString(hashBin);
return hash;

Is this intended? and if so how do i get around this problem?

Can't install package into a .NET Core project

I'm using PCLCrypto in a current PCL targeting .NETPortable,Version=v4.0,Profile=Profile328 without any problems. When I try to "upgrade" this project to a .NET Core project (using project.json), I get the following error:

1>project.json(13,18,13,18): .NET Portable Subset (.NET Framework 4, Silverlight 5, Windows 8, Windows Phone 8.1, Windows Phone Silverlight 8) error NU1002: The dependency PCLCrypto 1.0.86 in project DnxTest does not support framework .NETPortable,Version=v4.0,Profile=Profile328.

My project.json file looks like this:

{
  "dependencies": {
    "PCLCrypto": "1.0.86"
  },
  "frameworks": {
    ".NETPortable,Version=v4.0,Profile=Profile328": {
      "frameworkAssemblies": {
        "mscorlib": { },
        "System": { },
        "System.Core": { },
        "System.Net": { },
        "System.Runtime.Serialization": { }
      },
      "dependencies": {
      }
    }
  }
}

ILMerge and internalize the Validation dependency

Hi nice lib!

The Validation reference is non-transitive, i.e. a purely internal concern. It should be ilmerged /internalize and thus not be added as a reference to projects consuming PCLCrypto.

Cheers.

ExportParameters produces arrays with an extra byte for leading zero on Desktop and WinRT (making interop with other crypto libraries difficult)

Hi,

Maybe you could help me to explain my findings ;) - when I tried following code in my Windows Store 8.1 and Windows desktop .NET 4.5 application they both get some invalid lengths:

var provider = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaPkcs1);
var rsaKey = provider.CreateKeyPair(1024);
publicKey = rsaKey.ExportParameters(false);
privateKey = rsaKey.ExportParameters(true);

More precisely:

  • on Windows Runtime - it gets 129 long instead of 128 for Modulus. Similarly P, Q and DQ are 65 instead of 64. For each of them first value is always '0', what is pretty strange.
  • on Windows Desktop - it's even more crazy; publicKey.Modulus is 129, while privateKey.Modulus is 128 and they also differ in heaving this leading '0' value.

Generally I am unable to encrypt/decrypt anything with it and skipping those '0' bytes doesn't seem right to me ;)

Problem with exporting and importing AsymetricKey

I'm trying to do something like this:

var asymKey = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm (AsymmetricAlgorithm.RsaOaepSha256).CreateKeyPair(2048);
var exported = asymKey.Export();

foreach (var item in exported)
    System.Diagnostics.Debug.Write(item + " ");

var imported = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaOaepSha256).ImportKeyPair(exported);

foreach (var item in imported.Export())
    System.Diagnostics.Debug.Write(item + " ");

I am getting different values from ICryptographicKey.KeySize before invoking Export and after invoking Import.
My project is Xamarin.Android min. API 15 target API 21
I noticed that the problem appears on the android 4.0.3 and 5.0, in 4.1.1 and 4.4.1 is working fine.

Streaming CBC decryption fails CRC check in WinRT

I use following code in a common library for WP8.1 RT and iOS (Android is not yet been tested).
Encoding work fine in all platforms, but in WP app, decoding always fail with an exception "Data error (cyclic redundancy check). (Exception from HRESULT: 0x80070017)".
A stream encoded by WP is correctly decoded by iOS, of course, a stream encoded by iOS is correctly decoded by iOS.
The only way that I found for to make decoding working in WP is read all encoded stream in a buffer and use CryptographicEngine.Decrypt instead of CryptoStream as show in DecodeWP method.
Is that a CryptoStream implementation bug or a limitation of WinRT runtime?
There is a way to use CryptoStream method also in WP app? Input stream can be very huge, and I don't want load it all in memory.

An additional usefull info, in my first implementation I have used AesEcbPkcs7, and both encoding that decoding work fine in WP app, but I was obliged to change because AesCbcPkcs7 is the only implemented by iOS.

Thanks in advance
FP

private byte[] GetHash(string data)
{
    IHashAlgorithmProvider objAlgProv = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(HashAlgorithm.Md5);
    return objAlgProv.HashData(System.Text.UTF8Encoding.UTF8.GetBytes(data));
}

public async Task Encode(System.IO.Stream input, System.IO.Stream output, string password)
{
    byte[] keyHash = GetHash(password);
    ISymmetricKeyAlgorithmProvider aes = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
    ICryptographicKey symetricKey = aes.CreateSymmetricKey(keyHash);

    using (CryptoStream cryptoStream = new CryptoStream(output, WinRTCrypto.CryptographicEngine.CreateEncryptor(symetricKey), CryptoStreamMode.Write))
    {
        await input.CopyToAsync(cryptoStream);
    }
}

public async Task Decode(System.IO.Stream input, System.IO.Stream output, string password)
{
    try
    {
        byte[] keyHash = GetHash(password);
        ISymmetricKeyAlgorithmProvider aes = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
        ICryptographicKey symetricKey = aes.CreateSymmetricKey(keyHash);

        using (CryptoStream cryptoStream = new CryptoStream(input, WinRTCrypto.CryptographicEngine.CreateDecryptor(symetricKey), CryptoStreamMode.Read))
        {
            await cryptoStream.CopyToAsync(output);
        }

    }
    catch (Exception ex)
    {
        throw ex; //Data error (cyclic redundancy check). (Exception from HRESULT: 0x80070017)
    }
}

public async Task DecodeWP(System.IO.Stream input, System.IO.Stream output, string password)
{
    byte[] keyHash = GetHash(password);
    ISymmetricKeyAlgorithmProvider aes = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
    ICryptographicKey symetricKey = aes.CreateSymmetricKey(keyHash);

    byte[] inputBuffer = new byte[input.Length];
    input.Read(inputBuffer, 0, inputBuffer.Length);
    byte[] outputBuffer = WinRTCrypto.CryptographicEngine.Decrypt(symetricKey, inputBuffer, null);
    await output.WriteAsync(outputBuffer, 0, outputBuffer.Length);
}

SslStream on PCL

Hi Andrew,

I'm trying to get together this PCL socket library to work with SSL/TLS for Secure Sockets: https://github.com/rdavisau/sockets-for-pcl/

I'm using your project for other crypto operations but I wonder if you have if PCLCrypto can help me with that and if yes, can you give me some directions for it?

Thanks!

Improve private key interop between iOS and .NET Framework

The KeyPairInterop_iOSGenerated test is now disabled on desktop. It reads an RSA private key created on iOS. Since .NET Framework calls into CAPI for its RSA, and CAPI doesn't support the number of bits in the RSAParameters of most iOS generated private keys, PCLCrypto falls back to RSAManaged from Mono.Security. But that too is quite unstable (failing about 50% of the time) and a bug is now filed against mono for it.

Even if that mono bug is fixed, ideally we wouldn't bring in a whole library just to workaround this CAPI limitation. WinRT supports such keys just fine, proving that BCrypt/NCrypt libraries in Windows can handle it. It's just the older crypto APIs from Windows that .NET calls into that are broken.

We should break away from RSA through .NET and call into BCrypt/NCrypt directly, lose our dependency on Mono.Security, and thereby offer better private key interop between Windows and iOS.

SHA512 Not supported on Silverlight (Not a bug - please remove)

EDIT: I just noticed I looked at a wrong library, SHA512 does not exist in Silverlight. Sorry.
You can delete this

Hi everyone, I was using your awesome library and I noticed sha512 was not supported for silverlight.

When looking at the code (PCLCrypto.Shared.NetFx/HashAlgorithmProvider.cs, in CreateHashAlgorithm), I saw the following:

#if SILVERLIGHT
        switch (algorithm)
        {
            case HashAlgorithm.Sha1:
                return new Platform.SHA1Managed();
            case HashAlgorithm.Sha256:
                return new Platform.SHA256Managed();
            default:
                throw new NotSupportedException();
       }
#else

but on Platform (system.security.cryptography), there seem to be a SHA512Managed (https://msdn.microsoft.com/fr-fr/library/system.security.cryptography.sha512managed(v=vs.110).aspx).

Do you think this could be added to the version ?

Thanks for your awesome library !

Padding problems

I have an application where the server runs on ASP.NET and encrypts content for a Windows 8.1 / RT client. It generally works, but some files throws an ArgumentException with the message Length does not a multiple of block size and no padding is selected. Parameter name: data.

The weird thing is that I am using a cipher with padding (well, at least I think I do).

Here is my shared code with my private bits redacted:

 public class CryptoService : ICryptoService
    {
        private const string Password = "xxxxxxxxxxxxxxxxxxxxxxx";
        private static readonly byte[] Salt = Convert.FromBase64String("xxxxxxxxxxxxxxxxxxx==");
        private const int SaltSize = 16;

        public byte[] Encrypt(byte[] data, string password)
        {
            return WinRTCrypto.CryptographicEngine.Encrypt(GetKey(password), data, Salt);
        }

        public byte[] Decrypt(byte[] encryptedData, string password)
        {
            return WinRTCrypto.CryptographicEngine.Decrypt(GetKey(password), encryptedData, Salt);
        }

        static ICryptographicKey GetKey(string id)
        {
            const int Iterations = 5000; // higher makes brute force attacks more expensive
            var key = NetFxCrypto.DeriveBytes.GetBytes(id + Password, Salt, Iterations, SaltSize);

            var aesKey = WinRTCrypto.SymmetricKeyAlgorithmProvider
          .OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7)
          .CreateSymmetricKey(key);

            return aesKey;
        }
    }

Any feedback on what I could be doing wrong is much appreciated 😄

Make all providers IDisposable or none of them

We should make them all IDisposable so that going forward they may add requirements for a Dispose method without it constituting a breaking change.
Or we should commit to a design where the providers don't allocate unmanaged resources except as local variables so that none of them need to be disposed of.

WinRT itself does not require disposing them. But I think this includes keys, and I think we must maintain fields for keys since the native side of them can retain state that we need.

iOS Unified

Any thoughts on adding support for iOS Unified? Getting a Not implemented in reference assembly right now. Using latest nuget version 0.5.2.14286

KeyFormatters_PrivateKeyRoundTrip test unstable

The KeyFormatters_PrivateKeyRoundTrip test fails non-deterministically.
For example, here is one such failure.

 PCLCrypto.KeyFormatterTests.KeyFormatters_PrivateKeyRoundTrip(format: Capi1PrivateKey) [FAIL]
      Assert.Equal() Failure
      Expected: Byte[] [107, 135, 39, 12, 178, ...]
      Actual:   Byte[] [0, 107, 135, 39, 12, ...]
      Stack Trace:
        src\PCLCrypto.Tests.Shared\KeyFormatterTests.cs(62,0): at PCLCrypto.KeyFormatterTests.KeyFormatters_PrivateKeyRoundTrip(CryptographicPrivateKeyBlobType format)
      Output:
        Generated RSA parameters:
          Modulus: a4d5f49f3298500af851b031d27754fd63b8df7f37508b2bea15794ae706abc4cc790d5c8f4bac7ac46ac770b53830a28e97fd3bd9d2afdd18b8db9266965413
          Exponent: 010001
          P: e6505d775acbc8077462f0cdbe22a59fc6c75758a9a097211bc4e071c963e415
          D: 6b87270cb2f4a9427ebacb35b516235b28b271198bfbfecda6e65b39817bd8907b0e7051b74ddb728f1f29220cef00095d63c224d5a148e14e15a9cb4c6849
          Q: b73823d2929601f4f95050e17de1587841cbdc4152444f2352d9f83f54d71987
          DP: 200f81e352855994081499d6da27f28c5a5c77814523b0c6101a88efee0bf4bd
          DQ: 1471d6457c07f325f3e00b766e068449bf05d1891475fce2b32f116d77b91ce7
          InverseQ: c7e4c27f6596dec9f8d18eb3ccead992ca2ad7241a4abffdecaa5ad5bf965895
        Read RSA parameters:
          Modulus: a4d5f49f3298500af851b031d27754fd63b8df7f37508b2bea15794ae706abc4cc790d5c8f4bac7ac46ac770b53830a28e97fd3bd9d2afdd18b8db9266965413
          Exponent: 010001
          P: e6505d775acbc8077462f0cdbe22a59fc6c75758a9a097211bc4e071c963e415
          D: 006b87270cb2f4a9427ebacb35b516235b28b271198bfbfecda6e65b39817bd8907b0e7051b74ddb728f1f29220cef00095d63c224d5a148e14e15a9cb4c6849
          Q: b73823d2929601f4f95050e17de1587841cbdc4152444f2352d9f83f54d71987
          DP: 200f81e352855994081499d6da27f28c5a5c77814523b0c6101a88efee0bf4bd
          DQ: 1471d6457c07f325f3e00b766e068449bf05d1891475fce2b32f116d77b91ce7
          InverseQ: c7e4c27f6596dec9f8d18eb3ccead992ca2ad7241a4abffdecaa5ad5bf965895

key and iv length for AesCbcPkcs7

Hi, I was wondering how to know the key and iv length for AesCbcPkcs7. By experiment, I found them to be 32 and 16 by default. Is the 32 fixed? Is the 16 changeable? Is there advantage to changing it?

Breaking change of Xamarin.iOS 9 (NSMutableDictionary) - application no longer compiles

Hi,

I just installed the new Xamarin.iOS version and a breaking change is causing us trouble. On compilation, we have the following error: Failed to resolve System.Void MonoTouch.Foundation.NSMutableDictionary.

This is due to a breaking changing in Xamarin.iOS 9 regarding NSMutableDictionary : https://developer.xamarin.com/releases/ios/xamarin.ios_9/xamarin.ios_9.0/

They are now generic-based.

We can see the use of NSMutableDictionary here for instance : https://github.com/AArnott/PCLCrypto/blob/master/src/PCLCrypto.Shared.iOS/RsaAsymmetricKeyAlgorithmProvider.cs
But also in several other files.

Maybe a simple recompile would be enough.

Hoping this helps, I also use this occasion to tell you that your library is awesome :)

PS: we thought this bug was coming from Xamarin, the discussion is here (https://bugzilla.xamarin.com/show_bug.cgi?id=34621)

Compatibility with Xamarin.iOS Unified API

Hi Arnott,

First of all, I would like to congratulate you for this project. It is pretty good and worked like a charm. There is only one thing, I just updated my Xamarin.iOS projects to the Unified API. And now, it lost compatibility with the Touch project, because the new Unified API, is not being recognized in the Nuget file.

Do you have any plan for fix those changes?

Thanks in regard,

Duplicate types in Abstractions

It looks like there's a number of interfaces/algorithms that are in the PCLCrypto.Abstractions that are also in PCLCrypto. This leads to issues requiring assembly aliases to properly compile when both are added to a PCL (as per the NuGet).

I'm guessing that the interfaces/enums are intended to be removed from PCLCrypto and just put into the Abstractions?

Using SymmetricKeyAlgorithmProvider in PCL codebase ios

Hi,

I have the following method:

        public string Encrypt(string stringToEncrypt, string cryptoKey)
    {
        byte[] keyMaterial = System.Text.Encoding.UTF8.GetBytes (cryptoKey);
        byte[] data = System.Text.Encoding.UTF8.GetBytes (stringToEncrypt);
        var provider =          WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
        var key = provider.CreateSymmetricKey (keyMaterial);
        byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data);

        return Convert.ToBase64String (cipherText);
    }

The line var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7); fails with error System.NotImplementedException: Not implemented in reference assembly

I'm confused as I thought the point of the library was to provide cryptographic support for codebases that use the PCL. Is SymmetricKeyAlgorithmProvider not available to PCL codebases? And if not, what is the way to encrypt/decrypt strings on iOS devices?

extra bytes in transform - adding junk to the decrypted text

We are in the process of gutting a lot of shared functionality in our system and porting it to PCL libraries. I am taking some existing data in our database, and trying to decrypt it with the same algorithm. I get the value back, but there are 16 extra bytes at the end that are just garbage.

See Code below:
Old Algorithm using System.Security.Cryptography

public static string SymmetricEncrypt(this string plaintext, string key, SymmetricAlgorithm algorithm)
{
    byte[] keyBuffer = Convert.FromBase64String(key.Hash(HashAlgorithm.MD5));
    byte[] plainTextBuffer = Encoding.UTF8.GetBytes(plaintext);

   var symmetricAlgorithm = new AesCryptoServiceProvider();
    symmetricAlgorithm.Key = keyBuffer;
    symmetricAlgorithm.Mode = CipherMode.ECB;

    var encryptor = symmetricAlgorithm.CreateEncryptor();
    byte[] cipherBuffer = encryptor.TransformFinalBlock(plainTextBuffer, 0, plainTextBuffer.Length);
    symmetricAlgorithm.Clear();

    return Convert.ToBase64String(cipherBuffer);
}


 public static string SymmetricDecrypt(this string cipherText, string key, SymmetricAlgorithm algorithm)
    {
        byte[] keyBuffer = Convert.FromBase64String(key.Hash(HashAlgorithm.MD5));
        byte[] cipherTextBuffer = Convert.FromBase64String(cipherText);
        var symmetricAlgorithm = new AesCryptoServiceProvider();
        symmetricAlgorithm.Key = keyBuffer;
        symmetricAlgorithm.Mode = CipherMode.ECB;

        var decryptor = symmetricAlgorithm.CreateDecryptor();
        byte[] plainTextBuffer = decryptor.TransformFinalBlock(cipherTextBuffer, 0, cipherTextBuffer.Length);
        symmetricAlgorithm.Clear();

        return Encoding.Default.GetString(plainTextBuffer);
    }

Decryption using PCLCrypto

public static string SymmetricDecrypt(this string cipherText, string key, SymmetricAlgorithm algorithm) {
    byte[] keyBuffer = Convert.FromBase64String(key.Hash(HashAlgorithm.MD5));
    byte[] cipherTextBuffer = Convert.FromBase64String(cipherText);

    ISymmetricKeyAlgorithmProvider symmetricAlgorithm = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(PCLCrypto.SymmetricAlgorithm.AesEcb);

    var symmetricKey = symmetricAlgorithm.CreateSymmetricKey(keyBuffer);
    var decryptor = WinRTCrypto.CryptographicEngine.CreateDecryptor(symmetricKey);
   byte[] plainTextBuffer = decryptor.TransformFinalBlock(cipherTextBuffer, 0, cipherTextBuffer.Length);
    return UTF8Encoding.UTF8.GetString(plainTextBuffer, 0, plainTextBuffer.Length);
}

Using the old version: plainTextBuffer is 16 bytes, new version it is 32 bytes.

Help!

CryptographicEngine.Sign not implemented on WP8 ?

I'm doing this code and getting an not implemented exception on the sign :S
Any though?

var mac = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha512);
        var keyMaterial = CryptographicBuffer.ConvertStringToBinary(hashKey, Encoding.UTF8);
        var cryptoKey = mac.CreateKey(keyMaterial);
        var hash = CryptographicEngine.Sign(cryptoKey, CryptographicBuffer.ConvertStringToBinary(stringToSign, Encoding.UTF8));
       return  CryptographicBuffer.EncodeToHexString(hash).ToUpper();

Compiler error updating to 2.0

I tried to update the nugget package for my Xamarin projects (with PCL libraries). I was getting the following errors on the UWP app so I reverted to 1.0 for now.
The non-generic type 'PInvoke.NTSTATUS.Code__PInvoke_Windows_Core' cannot be used with type arguments TestRunner.App.Windows D:...SafeTypes.g.cs 415

The type or namespace name 'Value' could not be found (are you missing a using directive or an assembly reference?) TestRunner.App.Windows D:...\SafeTypes.g.cs 415

Sporadic NotImplementedException on some environments

Hi
I've been struggling to figure out the reason why some of our environments sometimes (not always!) fail with a "System.NotImplementedException: Not implemented in reference assembly." exception.

Our solution has a .net 4.5 backend, silverlight 5 client and portable classes. I've installed PCLCrypto into all relevant projects (both backend, client, and portable) via NuGet.

It works fine locally and sometimes also on our production and acceptance environment, but then after a deployment it can be broken again..

I've created a helper class in a common portable project, that has the following code:

public static byte[] EncryptAes(byte[] data, string encryptionKey)
        {
            byte[] salt = Encoding.UTF8.GetBytes(encryptionKey);
            byte[] key = CreateDerivedKey(encryptionKey, salt);

            ISymmetricKeyAlgorithmProvider aes = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
            ICryptographicKey symetricKey = aes.CreateSymmetricKey(key);
            var bytes = WinRTCrypto.CryptographicEngine.Encrypt(symetricKey, data);
            return bytes;
        }

        public static byte[] CreateDerivedKey(string encryptionKey, byte[] salt, int keyLengthInBytes = 32, int iterations = 1000)
        {
            byte[] key = NetFxCrypto.DeriveBytes.GetBytes(encryptionKey, salt, iterations, keyLengthInBytes);
            return key;
        }

I get the error at NetFxCrypto.DeriveBytes.GetBytes

I can see that the right dlls are referenced and included in the bin folder. I'm out of ideas as of what can cause this behaviour. Any suggestions to try?

Wrong assumptions in ASN.1 BER reader

Please correct me, if I am wrong ;) but I suspect there are some wrong assumptions around ASN.1 BER reader functionality.

I put them all here:

  • BerTag values greater than 30 are not supported (checkout point 8.1.2.4.1 of the X.609) and it might cause invalid reads after that tag
  • indefinite-form of length is not clearly indicated at all to the upper layer (point 8.1.3.6 of the X.609 above); even if current implementation doesn't cause invalid reads instantly, the upper layer won't know, that it needs to process content until End-Of-Contents DataElement (two zero octets)
  • reading lenght doesn't handle end-of-stream correctly and can consume -1 value
  • lengthOfLength with all bits set is also a reserved value
  • is there any reason for 8kb length limit (beside of handling both cases above)?
  • decoded bit-stream doesn't need to be always lead by '0' octet (as applied here to X.509 RSA key info); according to standard first octet describes a number of unused bits at the end of the received stream (point 8.6.2.2); this is just probably 0 for RSA keys

Import of RSA key crashes on iOS9

Hi,

I'm using PCLCrypto to verify RSA signature on Android/iOS.
After tests in iOS9 Beta it appeared that importing public key is not working on iOS9. The exact result is InvalidOperationException "SecItemAdd returns 0".

The strange thing is that return result (OSStatus) is 0, which means "no error". However, the reference handle which has to be set by SecItemAdd is 0. Please refer to the code below:

        IAsymmetricKeyAlgorithmProvider algorithmProvider = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaSignPkcs1Sha256);

        ICryptographicKey generatedKeyPair = algorithmProvider.CreateKeyPair(2048);

        byte[] generatedPublicKey = generatedKeyPair.ExportPublicKey(CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);

        ICryptographicKey importedKey = algorithmProvider.ImportPublicKey(generatedPublicKey, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey); //InvalidOperationException

Any thoughts or ideas how to overcome this issue?

Thanks in advance!
Denys

Encryption/Decryption code breaks on Android 6 Marshmallow (NetFxCrypto.DeriveBytes.GetBytes)

My encryption/decryption code works perfectly fine up to Android 5.x, but on Android 6 Marshmallow the code doesn't work anymore. The root cause seems to be that the keysize changes from 32 bytes (Android 5) to 16 bytes (Android 6). It seems that the NetFxCrypto.DeriveBytes.GetBytes method does not return the correct number of bytes on Android 6.

I am using the following code to derive the keymaterial (the salt has 8 bytes):

// Returns 32 bytes on Android 5 and 16 bytes on Android 6.
private byte[] deriveKeyMaterialFromPassword(string password, byte[] salt)
{
    const int numIterations = 500;
    return NetFxCrypto.DeriveBytes.GetBytes(password, salt, numIterations, 256 / 8);
}

Further information

Android 5 device: Google Nexus 4 (Android version 5.1.1)
Android 6 device: Google Nexus 5 (Android version 6.0.1)

Possibly related links

According to this post on stackoverflow, the default crypto provider was changed in Android 6 from "BC" to "AndroidOpenSSL":

I could not find any official information about this, however. But I have found a related bug report in the Google Android bugtracker:

Add Windows 10 support

After referencing installing on the PCL project and Windows 10 app, I get Not implemented in reference assembly.. Seems the bait and switch is not working properly.

AesEcb: BlockLength not supported on iOS

On iOS I get the following exception:

System.NotSupportedException: Specified method is not supported.

This is my code:

var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesEcb);
var blockLength = provider.BlockLength; // <- This is where the exception is thrown.

Details:

  • Tested on iPhone 5C 9.1 (real device) and iPhone 6 9.2 (simulator)
  • I can use SymmetricAlgorithm.AesCbcPkcs7 without problems

Add support for Zeros padding

This must be done for all platforms (iOS, Android, desktop, and WinRT)

The sponsor of this issue has provided this sample code snippet of what is done on Desktop that must be done in equivalence via PCLCrypto:

internal static string EncryptData(string data, string key)
{
    // Reference objects
    ICryptoTransform encryptor = null;
    MemoryStream msEncrypt = null;
    CryptoStream csEncrypt = null;

    try
    {
        // Encrypt the PUK Code
        var rijndael = new RijndaelManaged
        {
            Padding = PaddingMode.Zeros,
            Key = Encoding.ASCII.GetBytes(key),
            Mode = CipherMode.ECB
        };
        encryptor = rijndael.CreateEncryptor();

        //Encrypt the data.
        msEncrypt = new MemoryStream();
        csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

        //Convert the data to a byte array.
        var toEncryptPuk = Encoding.ASCII.GetBytes(data);

        //Write all data to the crypt stream and flush it.
        csEncrypt.Write(toEncryptPuk, 0, toEncryptPuk.Length);
        csEncrypt.FlushFinalBlock();

        //Get encrypted array of bytes.
        var encryptedPuk = msEncrypt.ToArray();

        return ToHexString(encryptedPuk);
    }
    catch (Exception ex)
    {
        _logger.Error($"{"Static.EncryptData"}: {ex.Message}", ex);
        throw new InvalidOperationException(ex.Message, ex);
    }
    finally
    {
        csEncrypt?.Close();
        msEncrypt?.Close();
        encryptor?.Dispose();
    }
}

Attempting to JIT compile method

Hi - I am using your PCLCrypto package to encrypt/decrypt strings in our Android/iOS app. I've defined two simple methods that use the classes and support from the package as follows:

    public string Encrypt(string stringToEncrypt, string cryptoKey)
    {
        byte[] keyMaterial = System.Text.Encoding.UTF8.GetBytes (cryptoKey);
        byte[] data = System.Text.Encoding.UTF8.GetBytes (stringToEncrypt);
        var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
        var key = provider.CreateSymmetricKey (keyMaterial);
        byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data);

        return Convert.ToBase64String (cipherText);
    }

    public string Decrypt(string stringToDecrypt, string cryptoKey)
    {
        byte[] keyMaterial = System.Text.Encoding.UTF8.GetBytes (cryptoKey);
        byte[] data = Convert.FromBase64String (stringToDecrypt);
        var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
        var key = provider.CreateSymmetricKey(keyMaterial);
        byte[] plainText = WinRTCrypto.CryptographicEngine.Decrypt(key, data);

        return System.Text.Encoding.UTF8.GetString(plainText, 0, plainText.Length);
    }

Bu when I run in iOS, I see the following errors:

System.ExecutionEngineException: Attempting to JIT compile method 'CryptoHelper:Decrypt (string,string)' while running with --aot-only

Any ideas?

Thanks,
Ed

Support streaming encryption on WinRT

Overcome the WinRT API limitation of not supporting encryption in a streaming fashion.

Now that we implement symmetric key encryption/decryption on WinRT, this should be more straightforward.

The BufferingCryptoTransform type needs to ultimately be deleted.

PCLCrypto does not support framework .NETPlatform,Version=v5.4

I'm getting the following error message when I try using PCLCrypto in a ASP.NET vNext (5.0 RC1) project when I get PCLCrypto over Nuget.

Error NU1002 The dependency Validation 2.0.6.15003 in project does not support framework .NETPlatform,Version=v5.4.

Xamarin Studio 5.x Nuget Client problem

Hi!
I have a problem with adding PCLCrypto Nuget package in XS. It says that The 'PCLCrypto 1.0.0-beta2' package requires NuGet client version '2.8.3' or above, but the current NuGet version is '2.8.1.0'. Can you solve it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.