Quantcast
Channel: clrsecurity Forum Rss Feed
Viewing all 40 articles
Browse latest View live

New Post: CryptoConfig2

$
0
0

Shawn,

I found the following information in http://social.msdn.microsoft.com/Forums/en-US/Geneva/thread/35c10fe5-9693-4f3a-9c5c-8afbb423ee95 

For those who were unable to get this problem resolved using Phil Bolduc's solution...

I was having the same problem, and in reading some known issues with the WIF Samples, it seemed that there is a need to run this function in both 64bit and 32 bit mode, as the registry keys injected by this routine seem to be bound to the platform binary.

The solution is to compile both a 64bit executable and a 32bit executable, and run each of them once.
If you want to check that the OIDs have been registered successfully, check the following registry hives:
  -  32bit  -  HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Cryptography\OID\EncodingType 0\CryptDllFindOIDInfo
  -  64bit  -  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\OID\EncodingType 0\CryptDllFindOIDInfo

each should contain the 3 OIDs which represent the 3 new SHA2 algorithms
  -  (SHA256) - "2.16.840.1.101.3.4.2.1!1"
  -  (SHA384) - "2.16.840.1.101.3.4.2.2!1"
  -  (SHA512) - "2.16.840.1.101.3.4.2.3!1"


The solution suggests to call Oid2.RegisterSha2OidInformationForRsa(); and I checked the source code of the method which excludes windows 2008 R2. I modified the code to make it do the registration for windows 2008 and did successfully get the 32bit keys registered. However, The 64 bit version wouldn't compile because mscorlib.dll "targets a different processor. Any suggestion on how to register the 64 bit keys?

Come back to the beginning, will registering the 64bit keys resolve the problem? 


New Post: CryptoConfig2

$
0
0

When building 64 bit, make sure that you're referencing the 64 bit version of mscorlib.dll (in Framework64, rather than Framework).   If the OS doesn't have the OIDs in place, then yes, updating them for both 32 and 64 bit should do the trick for you.

New Post: CryptoConfig2

$
0
0

Hi,

I'm experiencing the same problem, getting a "Invalid algorithm specified." when trying to sign with SHA-256 using SignHash. I'm also getting the same error when trying to use SignedXml and setting SignedInfo.SignatureMethod to "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256".

I'm running Windows 7 64 bit and have tested with both .NET 3.5 SP1 and .NET 4. I have edited the machine.config in:

C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config
C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config

and added:

  <mscorlib>
    <cryptographySettings>
      <cryptoNameMapping>
        <cryptoClasses>
          <cryptoClass RSASHA256SignatureDescription="Security.Cryptography.RSAPKCS1SHA256SignatureDescription, Security.Cryptography, Version=1.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        </cryptoClasses>
        <nameEntry name="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" class="RSASHA256SignatureDescription" />
      </cryptoNameMapping>
    </cryptographySettings>
  </mscorlib>



I have also installed the Security.Cryptography.dll in the GAC.

Furthermore, I have also registered the OIDs using Oid2.RegisterSha2OidInformationForRsa(); after modifying it to accept Windows 7.

The code I'm using is:

X509Certificate2 cert = new X509Certificate2("test.pfx", "test");
RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider;
byte[] signature = rsa.SignHash(Encoding.UTF8.GetBytes("message"), "SHA256");

If i switch to SHA1 as algorithm, the code works.

Any help is appreciated

New Post: CryptoConfig2

$
0
0

You are on the right track, one detail missing
The rsa object is linked to the wrong cryptoservice provider.

To create an RSA-SHA256 signature you will need to force the Microsoft Enhanced RSA and AES Cryptographic Provider to be used.
On my Windows 2008R2 machine this is identified by type 24. Windows 7 will most likely use the same value.

My recommendation is to research something like below.

          byte[] privateKeyBlob;
          X509Certificate2 cert = new X509Certificate2("test.pfx", "test");
          try {
            privateKeyBlob=cert.ExportCspBlob(true);
          } catch {
            throw new ApplicationException("Private key fails to export");
          }
          // To use the RSA-SHA256 the CryptoAPI needs to select a special CSP: Microsoft Enhanced RSA and AES Cryptographic Provider
          // By reinstantiating a CSP of type 24 we ensure that we get the right CSP.
          CspParameters cp=new CspParameters(24);
          cert=new RSACryptoServiceProvider(cp);
          cert.ImportCspBlob(privateKeyBlob);
          byte[] signature = rsa.SignHash(Encoding.UTF8.GetBytes("message"), "SHA256");

New Post: CryptoConfig2

$
0
0

Thank you, it works!

As it turns out, I don't need the CLR security package at all, I was just using the wrong crypto service provider.

When I was using the code I'm getting the "Microsoft Strong Cryptographic Provider" (type 1):

X509Certificate2 cert = new X509Certificate2("test.pfx", "test");
RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider;byte[] signature = rsa.SignData(Encoding.UTF8.GetBytes("message"), "SHA256");

However, when using the following code i'm getting the "Microsoft Enhanced RSA and AES Cryptographic Provider" (type 24):

X509Certificate2 cert = new X509Certificate2("test.pfx", "test", X509KeyStorageFlags.Exportable);
RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider;byte[] privateKeyBlob = rsa.ExportCspBlob(true);
RSACryptoServiceProvider rsa2 = new RSACryptoServiceProvider();
rsa2.ImportCspBlob(privateKeyBlob);byte[] signature = rsa2.SignData(Encoding.UTF8.GetBytes("message"), "SHA256");


My conclusion is that when casting the private key of the certificate to a RSACryptoServiceProvider, the provider type gets set to 1, but when creating a RSACryptoServiceProvider with the constructor, the type gets set to 24.
According to http://blogs.msdn.com/b/alejacma/archive/2009/04/30/default-provider-type-for-cspparameters-has-changed.aspx, default is type 24 from .NET 3.5 SP1 and above for OS's supporting it.

Is there a more elegant way of creating a signature with SHA256 by using a certificate without the need to create two RSACryptoServiceProviders as in my example above?

New Post: Full Backup & Recovery of RSA Keypair ( CNGKey.Import CngKeyBlobFormat does not work)

$
0
0
Guys, I need your help please!  .NET CNG makes me crazy...

 

I'm using your .NET wrappers for CNG and what I'm trying to achive is: backup & recovery of CNG RSA keypairs using "Microsoft Software Key Storage Provider"  (it should work on different Windows systems, sothat OpaqueTransportBlob is not useful)

 

Problem:
Why CNGKey.Import() runs without throwing any exception but the RSA-2048 keypair is not imported/created? Shoud I try with LEGACY_RSAPRIVATE_BLOB?
Tell me pls what the hell I'm doing wrong??? I have no ideas anymore and I'm tired... ((( 

 

Code built with .NET 3.5
Development/Test systems: Windows Server 2008 R2, Windows 7 SP1

 

How do I do it and what happens:
1) Create RSA-2048 Keypair in CNG KSP (works fine!)
if (!CngKey.Exists(KeyName, myKSP))
{
 CngProvider myKSP = new CngProvider(KSPName);
 CngKeyCreationParameters keyParams = new CngKeyCreationParameters();
 keyParams.ExportPolicy = CngExportPolicies.AllowPlaintextExport;
 keyParams.KeyCreationOptions = CngKeyCreationOptions.None;
 keyParams.Provider = myKSP;

 CngProperty keySizeProperty = new CngProperty("Length", BitConverter.GetBytes(KeySize), CngPropertyOptions.None);
 keyParams.Parameters.Add(keySizeProperty);
 CngKey myCNGKey = CngKey.Create(CngAlgorithm2.Rsa, KeyName, keyParams);
}
 
2) Export/backup RSA-2048 Keypair (Private/Public) into binary file (works w/o errors)
CngKey myMasterKey = CngKey.Open(tmpKEY, new CngProvider(tmpKSP));//Different keyblob formats are tested//buffer = myMasterKey.Export(CngKeyBlobFormat.OpaqueTransportBlob);//buffer = myMasterKey.Export(CngKeyBlobFormat.GenericPrivateBlob);//buffer = myMasterKey.Export(new CngKeyBlobFormat("RSAPRIVATEBLOB"));//buffer = myMasterKey.Export(new CngKeyBlobFormat("RSAFULLPRIVATEBLOB"));

CNGKSPUtility.writeByteArrayToFile(buffer, saveFileDialog.FileName);
 
3) Delete the exported keypair (works, what a surpise)
CngKey tmpK = CngKey.Open(KeyName, myKSP);
tmpK.Delete()
 
4) Import (works only with OpaqueTransportBlob, but not with other options - the import operations completes w/o errors but key isn't in KSP)
CNGKSPUtility.writeByteArrayToFile(buffer, saveFileDialog.FileName);

buffer = CNGKSPUtility.ReadByteArrayFromFile(openFileDialog.FileName);

//Works fine but useless, because keyblob must be importable on another system//CngKey.Import(buffer, CngKeyBlobFormat.OpaqueTransportBlob, new CngProvider(tmpKSP));//No errors but the key is not created in KSP after import//CngKey.Import(buffer, CngKeyBlobFormat.GenericPrivateBlob, new CngProvider(tmpKSP));//No errors but the key is not created in KSP after import//CngKey.Import(buffer, new CngKeyBlobFormat("RSAPRIVATEBLOB"), new CngProvider(tmpKSP));//No errors but the key is not created in KSP after import//CngKey.Import(buffer, new CngKeyBlobFormat("RSAFULLPRIVATEBLOB"), new CngProvider(tmpKSP));






New Post: FIPS 186-2 PRF

$
0
0

Hi guys I'm developing a radius server that supports eap-sim. Based on 4186 I need to do FIPS 186-2 PRF based on the master key computed. Is there a function implemented on this library that provides a 160 bytes hashed value based by a key provided?

New Post: Enumerating KeyContainer names on XP

$
0
0

Hi,

My group is using aspnet_regiis -pi to load key containers to encrypt parts of web.config.

I know I can use -pi to install key containers, -pe to export, or -pz to delete containers, but don't know how to enumerate all installed containers.

Another wrinkle - I am using XP so don't have NCRYPT.DLL so when I tried to use CngProvider.GetKeys, it complained about missing NCRYPT.DLL.

The key containers I want to see are in C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys.

Can I enumerate key containers with existing crypto utility?

Thanks!


New Post: Create CNG Keys

$
0
0

Hi,

I have been able to create a CNG Key with this, even gone as far as manipulating some of the parameters... Now only need to be able to specify the key length, which I have not been able to do... Below is a snippet that generates a new key with the details I want, except the setting the key size... I tried adding as a parameter but get an exception.

CngKeyCreationParameters cngParams = new CngKeyCreationParameters();
cngParams.KeyUsage = CngKeyUsages.Decryption;
cngParams.Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider;
//Throws unsupported exception
//cngParams.Parameters.Add(new CngProperty("KeySize", new System.Text.UTF8Encoding().GetBytes("2048"),CngPropertyOptions.Persist));
key = CngKey.Create(CngAlgorithm2.Rsa, keyName, cngParams);

New Post: [Solved] Create CNG Keys

$
0
0

[SOLVED] Posting for other for the benefit of others. Change the original posting's line #5 to:

cngParams.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));

Will write a blog about it on my TechNet blog later.

 



New Post: Memory leaks???

$
0
0

I think this project suffer some kind of memory leak. I created an application to perform as many AES encryption/decryption per second as the machine can, but the memory consumption increase without stop.

 

My code to decryptthat is repeated:

 

using (var encryptionObject = ClrSecurity.Cryptography.AesCng.Create())using (MemoryStream ms = new MemoryStream())using (CryptoStream cs = new CryptoStream(ms, encryptionObject.CreateDecryptor(key.Key, key.IV), CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                    cs.FlushFinalBlock();return ms.ToArray();
                }

 

and to encrypt:

using (var encryptionObject = ClrSecurity.Cryptography.AesCng.Create())using (MemoryStream ms = new MemoryStream())using (CryptoStream cs = new CryptoStream(ms, encryptionObject.CreateEncryptor(key.Key, key.IV), CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                    cs.FlushFinalBlock();return ms.ToArray();
                }

Am I using in a wrong way the library?

 

New Post: Memory leaks???

$
0
0

While your code is disposing of the CryptoStreams, it's not disposing of the ICryptoTransforms that the stream uses.   Specifically, the encryptionObject.CreateEncryptor and CreateDecryptor objects are never disposed, which means their underlying resources will not be cleaned up until the GC kicks in.

To fix this, you can create those outside of the cryptostream and dispose of them explciitly after closing down the stream.

-Shawn

New Post: The naming of "security.dll" causes "SslStream.AuthenticateAsClient" to fail (and others)

$
0
0

 

I think the naming of security.dll is causing an exception with the following code

 


class Program { staticvoid Main(string[] args) { conststring HostName = "email.nfp.com"; TcpClient tcpClient = new TcpClient(HostName, 443); SslStream sslStream = new SslStream(tcpClient.GetStream(), false, null, null); sslStream.AuthenticateAsClient(HostName, null, SslProtocols.Tls, false); } }

 

other blogs indicate that anything named security.dll causes an exception..

New Post: PEM-formatted RSA key pair... can this library help

$
0
0

I want to generate an RSA key pair and export and import that in PEM format.

 

I found a way to read a PEM file in this library, but no way to export it, or import a public key.

 

Assistance is appreciated.

New Post: Quick Question on RSA with SHA256 Signing (What am i missing?)

$
0
0

I am trying to understand the basics of RSA w/SHA256 hashing.  After reading the RFC docs i get the impression RSA-SHA256 works in this order:

FIRST: Hash the data using SHA256 hashing
SECOND: Use the resulting Hash output to be encrypted by RSA algorthim (sign)

So while using PHP i decided to perform a test.  I first took regular text e.g. "Hello world".  And then i ran it through the hash() function (to output raw binary using sha256..ie. "hash("sha256","Hello World",true);").  Now i used that hashed output and had it signed using RSA (using the openssl tool ie. "openssl dgst -sha256 -sign TestPriv.key -out Signed.bin TestHash.bin").  I then used base64 encoding on the signed output to get a displayable result.  Note that i created an RSA Private key in this signing and this say private key is used in the next paragraph.

NOW, when i compared the result with a function that performs RSA-SHA256 encryption in one step (e.g. crypto libraries that have a "SHA256WithRSAEncryption" feature) on the same original input data (ie. "Hellow World" and use my same private key) and then did a base64 encode on its signed output i noticed that its result did not match mine from the prior paragraph.

Why is that?  Shouldn't the results match perfectly since what i gather RSA is first putting the input data through SHA256 and then it performs its signing.  What i am starting to think is that these libraries that combine the steps are doing more than that...in other words, it isn't just signing the hashed result but doing mroe with the hash.

What am i missing?


New Post: CryptoConfig2

$
0
0

Descartes2,

Can you let  me know if you got this working in .Net 3.5 with Cryptoconfig2 and Signedxml.signedinfo.signaturemethod as SHA 256.? I have updated the configs and the Security.Cryptography.dll to my .Net 3.5 Project and I am not sure of registering the OIds as desphyxia mentioned??  has WS2k8 R2 as OS 64 bit.?? Let me know if this works in 3.5, I have this working in 4.0.

 

Desphyxia,

           You mentioned it works for you ??wanted to know if it is 3.5 or 4.0. I have this working in .Net 4.0 without the CLS package (Secruity.Cryptography.dll) as I am Crytoconfig.Addalgorithm to add my signature defnition at runtime in .Net 4.0 application.?? Also wanted to know the correct version of  " <cryptoClass RSASHA256SignatureDescription="Security.Cryptography.RSAPKCS1SHA256SignatureDescription, Security.Cryptography, Version=1.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</cryptoClasses> " is it still 1.6.0.0 as the latest?

 

Thanks and appreciate your earnest response

New Post: CryptoConfig2

$
0
0

The explicit type 24 construction method works on both .NET 3.5 as well as on .NET 4.0 on the x64 bit OS Windows 2008R2.

Please note that you need to find the corresponding machine.config and add the

mscorlib/cryptographySettings/cryptoNameMapping/cryptoClasses/cryptoClass/nameEntry element.

To get it running in all configurations you may need to make this addition four times

C:\WINDOWS \Microsoft.NET\Framework64\v4.0.30319\Config\machine.config

C:\WINDOWS \Microsoft.NET\Framework\v4.0.30319\Config\machine.config

C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\CONFIG\machine.config

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config

It is my understanding the v3.5 uses the v2.0.50727 framework configuration files.

New Post: Support for secp256k1?

$
0
0

I need support for the secp256k1 curve in .NET and would rather use native libraries.

 

What is the likelyhood of getting this included in any version (P/Invoke or not)?

New Post: using GCM with TagSize=96 throws CryptographicException

$
0
0

When i try authenthed encryption using GCM, TagSize=96 and plain text >= 16 bytes an CryptographicException throws:

 System.Security.Cryptography.CryptographicException : An invalid parameter was passed to a service or function.
   at Security.Cryptography.BCryptNative.SymmetricEncrypt(SafeBCryptKeyHandle key, Byte[] input, Byte[] chainData, ref BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authenticationInfo) in BCryptNative.cs: line 1028   at Security.Cryptography.BCryptAuthenticatedSymmetricCryptoTransform.CngTransform(Byte[] input, Int32 inputOffset, Int32 inputCount) in BCryptAuthenticatedSymmetricCryptoTransform.cs: line 388   at Security.Cryptography.BCryptAuthenticatedSymmetricCryptoTransform.TransformBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[] outputBuffer, Int32 outputOffset) in BCryptAuthenticatedSymmetricCryptoTransform.cs: line 297   at System.Security.Cryptography.CryptoStream.Write(Byte[] buffer, Int32 offset, Int32 count)

using (AuthenticatedAesCng aes = new AuthenticatedAesCng())
{
    aes.CngMode = CngChainingMode.Gcm;
    aes.KeySize = 128;
    aes.TagSize = 96;
    aes.Padding = PaddingMode.None;

    aes.GenerateIV();
    aes.GenerateKey();

    aes.AuthenticatedData = 
        newbyte[] { 0x30,0xAA,0xAA,0xAA,0xAA,0xBB,0xBB,0xBB,0xBB,0xCC,0xCC,0xCC,0xCC,0xDD,0x14,0x15,0x16 };using (MemoryStream ms = new MemoryStream())using (IAuthenticatedCryptoTransform encryptor = aes.CreateAuthenticatedEncryptor())using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
    {byte[] plaintext = newbyte[] { 0xAA,0xAA,0xAA,0xAA,0xBB,0xBB,0xBB,0xBB,0xCC,0xCC,0xCC,0xCC,0xDD,0x14,0x15,0x16 };
        cs.Write(plaintext, 0, plaintext.Length);

        cs.FlushFinalBlock();

        byte[] cipherText = ms.ToArray();byte[] authenticationTag = encryptor.GetTag();
    }
}

New Post: MSFT: What is the roadmap / future of this project ?

$
0
0

Can the project owner or project manager comment on what the roadmap for CLR Security looks like and what project does Microsoft intend to spotlight as the main cryptographic and security library?

For details:

I ask because the official .NET 4.5 libraries don't seem to have any support for authenticated encryption like AES-GCM. At least I couldn't find it. Then the only option I ran into was CLR Security (this!) and this too seemed to support only AES-GCM (not OCB or EAX). On top of that, looking the project activity levels, it was surprisingly low, making me wonder if MSFT has had a change of plans. Not that crypto algos change monthly, but still ...

The only other option I see is the 3rd party library BouncyCastle.org.

Considering that NSA Suite B recommends AES-GCM as the (only) suggested symmetric encryption mode for traffic (http://www.nsa.gov/ia/programs/suiteb_cryptography/index.shtml), and newer, slightly better modes like OCB have recently had their licensingdramatically softened, I think there is room for improvement in terms of documentation within MSDN, having a strong roadmap for commercial projects making a decision on which library to commit to etc.

I'm told security is a serious topic at Microsoft I'm wondering what the roadmap actually is!

Viewing all 40 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>