Showing posts with label cryptography. Show all posts
Showing posts with label cryptography. Show all posts

Wednesday, March 7, 2018

ASPNET_REGIIS: Place AES key and IV into a KeyContainer

Leave a Comment

Is it possible to place an AES key and IV into a KeyContainer using ASPNET_REGIIS? If yes, how?

Context:

I have created AesProtectedConfigurationProvider to encrypt web.config data using AES as opposed to Triple DES (i.e., 3DES). I have also created a console application that uses the AesProtectedConfigurationProvider in order to generate both the AES key and initialization vector (IV). I can save the key to a text file and then reference the text file in the provider of the web.config. From there, I am able to encrypt the web.config file. But, I would like to protect the keys.txt file by moving them into a KeyContainer, if that is possible.

So, under the provider tag, the section for keyContainerName would be:

keyContainerName="AesKeyContainer"  

as opposed to

keyContainerName="C:\AesKey.txt" 

My understanding is the current encryption offering that is available out of the box in ASPNET_REGIIS uses 3DES to encrypt the contents of the web.config file while the RsaProtectedConfigurationProvider is used to encrypt the 3DES keys (please correct me if I am wrong on this). So, if it is possible to use the RsaProtectedConfigurationProvider to encrypt the AES keys into a KeyContainer then that would be helpful. I have reviewed the following sites and I am not sure if this is possible:

https://msdn.microsoft.com/en-us/library/33ws57y0.aspx

How to encrypt web.config with AES instead of 3DES

EDIT: Does anyone know why Microsoft took out the AesProtectedConfigurationProvider in subsequent releases of .NET? This seems like a step backwards as AES is the current standard while 3DES is no longer recommended. In speaking with a colleague, they mentioned that it may have been removed due to a security flaw, such as; elevation of privileges. Microsoft is known for making unannounced changes with respect to security. But, I would like to know if anyone knows for sure. If, indeed, a flaw was found in the AesProtectedConfigurationProvider, then I might be inclined to stay with 3DES.

1 Answers

Answers 1

RsaProtectedConfigurationProvider and AesProtectedConfigurationProvider, despite very similar names, are parts of different universes.

RsaProtectedConfigurationProvider resides in System.Configuration and is used (as other providers inheriting from abstract ProtectedConfigurationProvider) for encryption/decryption of configuration sections in web.config for ASP.NET applications.

AesProtectedConfigurationProvider in its turn resides in Microsoft.ApplicationHost and is used only for IIS configuration encryption. In configuration file of default application pool (DefaultAppPool.config) you will find following:

<configProtectedData>     <providers>         <!-- ... -->         <add name="AesProvider" type="Microsoft.ApplicationHost.AesProtectedConfigurationProvider" ... />         <add name="IISWASOnlyAesProvider" type="Microsoft.ApplicationHost.AesProtectedConfigurationProvider" ... />     </providers> </configProtectedData> 

You could read about AesProvider and IISWASOnlyAesProvider in IIS Securing Configuration article:

AesProvider - Encrypting IIS configuration sections read by the IIS worker process using AES encryption.

IISWASOnlyAesProvider - Encrypting IIS configuration sections read by WAS using AES encryption.

So answering your first question:

  1. Confirm whether using the AesProtectedConfigurationProvider is safe. It was removed by Microsoft in subsequent releases of .NET but I cannot seem to find a reason

Yes, using of your custom AES provider is safe if we assume that you have implemented it correctly without security flaws. Microsoft has not removed AesProtectedConfigurationProvider from .Net Framework, it was never a part of System.Configuration. If Microsoft has found security flaw in its implementation, they could just fix it instead of removing, correct?

  1. Provide steps to implement the AesProtectedConfigurationProvider and to create a KeyContainer in ASPNET_REGIIS

I believe you can have AES encryption without implementing custom AesProtectedConfigurationProvider.

I dig into source code of RsaProtectedConfigurationProvider and found that it has the following logic:

private SymmetricAlgorithm GetSymAlgorithmProvider() {     SymmetricAlgorithm symAlg;      if (UseFIPS) {         // AesCryptoServiceProvider implementation is FIPS certified         symAlg = new AesCryptoServiceProvider();     }     else {         // Use the 3DES. FIPS obsolated 3DES         symAlg = new TripleDESCryptoServiceProvider();          byte[] rgbKey1 = GetRandomKey();         symAlg.Key = rgbKey1;         symAlg.Mode = CipherMode.ECB;         symAlg.Padding = PaddingMode.PKCS7;     }      return symAlg; } 

As you see, default RSAProtectedConfigurationProvider supports switch from Triple DES to AES encryption by means of System.Security.Cryptography.AesCryptoServiceProvider.

UseFIPS flag is read from configuration section of RsaProtectedConfigurationProvider. You could set it on machine level (machine.config) so that it's applied to all encrypted configs or only for specific web.config.

For later case add following section to web.config (I have copied the section from machine.config and added useFIPS="true"):

<configuration>    <!-- ... -->    <configProtectedData>     <providers>       <remove name="RsaProtectedConfigurationProvider"/>       <add name="RsaProtectedConfigurationProvider"            type="System.Configuration.RsaProtectedConfigurationProvider,System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"            description="Uses RsaCryptoServiceProvider to encrypt and decrypt"            keyContainerName="NetFrameworkConfigurationKey"            cspProviderName=""            useMachineContainer="true"            useOAEP="false"            useFIPS="true"            />     </providers>   </configProtectedData>    <!-- ... -->  </configuration> 

Now if you run aspnet_regiis, you will see that data is encrypted with 256 bit AES:

<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" /> 

The AES symmetric key is stored in the same way as for Triple DES mode: the key is encrypted with RSA and is embedded into encrypted section while RSA key is stored in machine key container. See this blog post for more details.

I believe using of AES encryption that is already implemented in RsaProtectedConfigurationProvider is far better option than custom AES provider. You are using existing key storing method and you are protected from possible (highly probable) security flaws.

Read More

Friday, January 5, 2018

Decrypting EnvelopedCms with non-default AlgorithmIdentifier

Leave a Comment

I'm trying to decrypt a EnvelopedCms that was encrypted using a non-default AlgorithmIdentifier like this:

ContentInfo contentInfo = new ContentInfo(data); EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(new System.Security.Cryptography.Oid("2.16.840.1.101.3.4.1.42"))); CmsRecipientCollection recipients = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, certificates); envelopedCms.Encrypt(recipients); byte[] encryptedData = envelopedCms.Encode(); 

The encryption works as expected. Now when I try to decrypt the envelopedCms using something like this:

EnvelopedCms envelopedCms = new EnvelopedCms(); envelopedCms.Decode(encryptedData ); envelopedCms.Decrypt(certificates); byte[] decryptedData = envelopedCms.ContentInfo.Content; 

I notice that a.) the access to the certificate takes quite long (longer then when using the default AlgorithmIdentifier) and b.) I get this error message:

System.Security.Cryptography.CryptographicException: Access denied 

Which, looking at the source where this fails, is probably not the issue. Now I see that I haven't provided the encryption algorithm to use in the decrypt method anywhere and I believe that's the issue but I'm not sure how to specify the AlgorithmIdentifier for the decryption.

From the documenation I can see that the EnvelopedCms.Decrypt can take a RecipientInfo which can specify the algorithm but since we used multiple certificates for the encryption I'm not sure how to build such an object. Ideally I was thinking that the correct RecipientInfo, containing the actually used AlgorithmIdentifier, is already contained in the EnvelopedCms.RecipientInfos array. But it seems like this is not the case.

Can anyone get the decrypt code above working?

1 Answers

Answers 1

Although my answer may lead to some incomplete tangents, I believe that it will get you the same assertion that I have come to. The fact is that I use a X509Store allows me to locate the certificates that my machine has. I then pass the collection into the CmsReceipientCollection with a X509Certificate2Collection that is found from my store.Certificates. This method takes 128ms to execute. HTH!

 [TestMethod]     public void TestEnvelopedCMS()     {         X509Store store = new X509Store("MY", StoreLocation.CurrentUser);         store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);          X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;         X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);          byte[] data = new byte[256];         //lets change data before we encrypt         data[2] = 1;          ContentInfo contentInfo = new ContentInfo(data);         EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(new System.Security.Cryptography.Oid("2.16.840.1.101.3.4.1.42")));         CmsRecipientCollection recipients = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, fcollection);         envelopedCms.Encrypt(recipients);         byte[] encryptedData = envelopedCms.Encode();          //lets decrypt now         envelopedCms.Decode(encryptedData);         envelopedCms.Decrypt(fcollection);         byte[] decryptedData = envelopedCms.ContentInfo.Content;           //grab index from byte[]         var item = decryptedData.Skip(2).Take(1).FirstOrDefault();         var item2 = data.Skip(2).Take(1).FirstOrDefault();          Assert.IsTrue(item == item2);     } 
Read More

Sunday, October 29, 2017

How to employ keyed-hash message authentication code (HMAC) with Android Keystore

Leave a Comment

I am investigating the use of the Android KeyStore for Marshmallow and above.

I would like to simultaneously verify both the data integrity and the authentication of my data by employing HMAC's.

How do I go about achieving this?

I am current generating an Encrypt/Decrypt key as follows:-

        mKeyStore = KeyStore.getInstance(keyStoreName);         mKeyStore.load(mKeyStoreLoadStoreParameter);          if (mKeyStore.containsAlias(keyStoreAlias)) {             mSecretKey = (SecretKey) mKeyStore.getKey(keyStoreAlias, KEY_STORE_PASSWORD);         } else {             final KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, keyStoreName);             final int keyPurpose = KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT;              keyGenerator.init(                     new KeyGenParameterSpec.Builder(keyStoreAlias, keyPurpose)                             .setKeySize(KEY_STORE_KEY_SIZE)                             .setBlockModes(KeyProperties.BLOCK_MODE_GCM)                             .setRandomizedEncryptionRequired(true)                             .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)                             .build());              mSecretKey = keyGenerator.generateKey(); 

I have found this sample for generating HMAC's

SecretKey key = ...; // HMAC key of algorithm "HmacSHA512".   KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");  keyStore.load(null);  keyStore.setEntry(          "key1",          new KeyStore.SecretKeyEntry(key),          new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN).build());  // Key imported, obtain a reference to it.  SecretKey keyStoreKey = (SecretKey) keyStore.getKey("key1", null);  // The original key can now be discarded.   Mac mac = Mac.getInstance("HmacSHA512");  mac.init(keyStoreKey); 

However, how do I use this when encrypting/decrypting my data?

EXPLANATION

I have a number of choices/decisions to make when implementing security/cryptography within any Android application.

1). Do I implement cryptography of any sort Yes or No? 2). If Yes then... I should attempt to achieve the "most" secure solution possible.

If I am going to employ cryptography then I need to ensure the following.

a). I store passwords/secret keys in a "Safe Place" e.g. Android Key Store. b). I use the "strongest" cryptography available. c). I would like to simultaneously verify both the data integrity and the authentication of my data, e.g. I would like to detect if my encrypted data has been tampered with.

As I understand what I have read about HMAC's, they provide this functionality. I would like to know how I code the use of HMAC's into my Android application to ensure both the data integrity and the authentication of my data.

1 Answers

Answers 1

You can apply HMAC to the plain text HMAC(plain text) before encrypting and recompute the HMAC after decrypting to check that the original message is the same.

It may be redundant because if the cipher text is altered you will not be able to decrypt it.

First generate a HMAC key inside AndroidKeyStore. I found an example here

KeyGenerator keyGenerator = KeyGenerator.getInstance(          KeyProperties.KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore"); keyGenerator.initialize(          new KeyGenParameterSpec.Builder(hmacKeyAlias, KeyProperties.PURPOSE_SIGN).build()); SecretKey key = keyGenerator.generateKey(); 

Then Apply HMAC to the original data and store the result somewhere

Mac mac = Mac.getInstance("HmacSHA256"); mac.init(key); byte hmacOriginalData[] = mac.doFinal(dataToEncrypt); //Store hmacOriginalData  

After decrypting, get HMAC key from AndroidKeyStore, recompute HMAC and check both macs are equal

Key key = keyStore.getKey(hmacKeyAlias, null); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(key); byte hmacDecryptedData[] = mac.doFinal(decryptedData); //Check equals(hmacDecryptedData, hmacOriginalData); 
Read More

Friday, June 9, 2017

C# MVC Query String Encoding and Decoding

Leave a Comment

I want to encode and decode the url parameters.

calling function in javascript

var url = '/Demo/Demo?id=58'; $(location).attr('href', url) 

Current url parameter

www.example.com/Demo/Demo?id=58

code in Demo controller

public ActionResult Demo(int id) {    return view(); } 

i want the above url to be changed like the bolow line

www.example.com/Demo/Demo?id=Sff5f8ddg

So that the id value will be confidential. what is the best way to encode and decode.

Note: we calling method by anchor tag, ajax and jquery. Encoding and Decoding other than Base64

Is there any cryptography method other than Base64 enoding and decoding like encrypt in javascript and decrypt in C# method

9 Answers

Answers 1

So that the id value will be confidential. what is the best way to encode and decode.

It won't. At least in the way you are trying to make it. As soon as you encode the [internal] id it becomes the public id for that entry. It does not matter for user which id to use: 58 or Sff5f8ddg, as it would refer to the same entry in the system. If you are using unsalted algorithms it would prevent only not so sophisticated users to discover other entries in your system.

As I understand the problem you are trying to solve is - how to make other entries undiscoverable by having an id for some entry(ies). Eg, if user has an url for entry 58, they should not be able to find entries 57 and 59.

The solution is: use GUIDs as ID for your entries.

Also, you need to make sure that you've implemented proper access control for your entries.

Answers 2

var id=Encrypt(YourID); var id=Decrypt(YourID);    using System.Security.Cryptography;  public static string Encrypt(string inputText)     {         string encryptionkey = "SAUW193BX628TD57";         byte[] keybytes = Encoding.ASCII.GetBytes(encryptionkey.Length.ToString());         RijndaelManaged rijndaelCipher = new RijndaelManaged();         byte[] plainText = Encoding.Unicode.GetBytes(inputText);         PasswordDeriveBytes pwdbytes = new PasswordDeriveBytes(encryptionkey, keybytes);         using (ICryptoTransform encryptrans = rijndaelCipher.CreateEncryptor(pwdbytes.GetBytes(32), pwdbytes.GetBytes(16)))         {             using (MemoryStream mstrm = new MemoryStream())             {                 using (CryptoStream cryptstm = new CryptoStream(mstrm, encryptrans, CryptoStreamMode.Write))                 {                 cryptstm.Write(plainText, 0, plainText.Length);                 cryptstm.Close();                 return Convert.ToBase64String(mstrm.ToArray());                 }             }         }     }  public static string Decrypt(string encryptText) {     string encryptionkey = "SAUW193BX628TD57";     byte[] keybytes = Encoding.ASCII.GetBytes(encryptionkey.Length.ToString());     RijndaelManaged rijndaelCipher = new RijndaelManaged();     byte[] encryptedData = Convert.FromBase64String(encryptText.Replace(" ", "+"));     PasswordDeriveBytes pwdbytes = new PasswordDeriveBytes(encryptionkey, keybytes);     using (ICryptoTransform decryptrans = rijndaelCipher.CreateDecryptor(pwdbytes.GetBytes(32), pwdbytes.GetBytes(16)))     {         using (MemoryStream mstrm = new MemoryStream(encryptedData))         {             using (CryptoStream cryptstm = new CryptoStream(mstrm, decryptrans, CryptoStreamMode.Read))             {             byte[] plainText = new byte[encryptedData.Length];             int decryptedCount = cryptstm.Read(plainText, 0, plainText.Length);             return Encoding.Unicode.GetString(plainText, 0, decryptedCount);             }         }     } } 

Answers 3

In javascript, you can use

var str = "Hello World!"; var enc = window.btoa(str); var dec = window.atob(enc); 

The result of res will be:

Encoded String: SGVsbG8gV29ybGQh Decoded String: Hello World! 

This example shows you how to use the RijndaelManaged for encryption decryption.

 public static class Cryptography     {          private static readonly byte[] _key = { 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03 };         private static readonly byte[] _iV = { 0x10, 0x11, 0x12, 0x13, 0x10, 0x11, 0x12, 0x13, 0x10, 0x11, 0x12, 0x13, 0x10, 0x11, 0x12, 0x13 };          #region Encryption           public static string Encrypt(this string inputText)         {             string _encryptString = string.Empty;             if (string.IsNullOrEmpty(inputText))                 return string.Empty;             else             {                 ASCIIEncoding textConverter = new ASCIIEncoding();                 RijndaelManaged myRijndael = new RijndaelManaged();                  ICryptoTransform encryptor = myRijndael.CreateEncryptor(_key, _iV);                 MemoryStream msEncrypt = new MemoryStream();                 CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);                 byte[] toEncrypt = textConverter.GetBytes(inputText);                 csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);                 csEncrypt.FlushFinalBlock();                 _encryptString = Convert.ToBase64String(msEncrypt.ToArray()).Replace(" ", "+");                 return _encryptString;             }         }          public static string Decrypt(this string inputText)         {             string text = inputText;             try             {                 if (string.IsNullOrEmpty(inputText))                     return string.Empty;                 else                 {                     inputText = inputText.Replace(" ", "+");                      byte[] encrypted = Convert.FromBase64String(inputText);                     ASCIIEncoding textConverter = new ASCIIEncoding();                     RijndaelManaged myRijndael = new RijndaelManaged();                      ICryptoTransform decryptor = myRijndael.CreateDecryptor(_key, _iV);                     MemoryStream msDecrypt = new MemoryStream(encrypted);                     CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);                     byte[] fromEncrypt = new byte[encrypted.Length];                     csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);                     return textConverter.GetString(fromEncrypt).TrimEnd('\x0');                 }             }             catch (FormatException)             {                 return "";             }             catch (Exception ex)             {                 return text;             }         }            #endregion Encryption      } 

Now encrypt decrypt in controller Like

 "id".Encrypt();///   "encryptID".Decrypt(); 

Answers 4

What I am able to understand from your question is that you want to restrict user from being able to know the exact value of the id parameter.

But that's not gonna help because you already have that value on your browser/client side. so you have id on your client and you want to restrict your client from knowing its value. An average developer(anyone who write code) can access your value using developer tool of browser. So no benefit.

Another way is you send your id encrypted from server itself. For that you can use the solution provided by @Karan Singh. Or any other option you want to explore for that matter is up to you.

One suggestion try to use an encryption method which can not be done in reverse. This will add overhead in processing as you will have to first encrypt your Id from DB and then match it with the value sent by client.

Thanks.

Answers 5

You can simply use jquery function like:

var encodedUrl = encodeURIComponent("your url"); //'/Demo/Demo?id=58'; console.log(encodedUrl);

Thank you

Answers 6

If what you are looking to do is to hide the 58 from the rendered content (client-side), then you need to implement an encryption/decryption scheme on the backend and pass that value from/to the client side as needed.

When you provide data to the client, your server side code will encrypt the 58 into some string in order to conceal the real value and pass that to the client.

When the client issues a request to you, it should use that encrypted string that you provided before and your server should decrypt it into something it can use.

You don't need JavaScript to encrypt and C# to decrypt the values. The JavaScript portion should be working off of the encrypted id at all times since it's scripting that is executing after the fact at the client side. How the value is consumed on the server side is an internal aspect of which the client-side JavaScript does not need to know about.

Answers 7

You want to encode / decode parameters, but the question is why? What are you trying to accomplish in the first place? What is your requirement and how sensitive is the data on the page? What is the purpose of the id, does it identify a user or a page?

If you are thinking of sharing a link or publish it (anchor tag) on an unsecured page, then consider the fact that the link can be shared beyond control or even stolen. Anyone who has the link can access the page. How are you going to detect that it is compromised? How are you going to revoke the link?

It doesn't even matter then how you encrypt the id: a random string, a highly encrypted id, a GUID (which isn't safe either since an attacker will recognize that it's a GUID and can use brute force attack to 'guess' available guid's).

The best chance you may have is to use an auto-expiring link which has some random value and variable length id (so it cannot be guessed). Store the value in the database with expiration date and link to the actual id. This doens't prevent the link from being shared, but at least you can limit possible damage.

But: the only way to prevent unauthorized access is to add a level of security. You can try to think of all kinds of things to secure your data, but in the end you are re-inventing security. Why don't you take a look at modern security, like OpenId Connect and OAuth2. If you want to secure your resource, implement something like Asp.Net Identity 2.

Answers 8

Hello anand i think you want to create a temper proof Query string Download the code from github repository

Answers 9

controller:

[HttpPost]         public ActionResult SubmitInputTest(int id) {              //your code              //do stuff              return RedirectToAction("index");         } 

In your view (cshtml):

<form id="frmToSubmit" action="<controller>/SubmitInputTest">  <hidden id="id" name="id"/> </form> 

In your javascript:

$('#id').attr('value', [your ID Value]); $('#frmToSubmit').submit(); 
Read More

Sunday, September 18, 2016

'EntryPoint' object has no attribute 'resolve' when using Google Compute Engine

Leave a Comment

I have an issue related to Cryptography package in Python. Can you please help in resolving these, if possible ? (tried a lot, but couldnt figure out the exact solution)

The python code which initiates this error:

print("Salt: %s" % salt) server_key = pyelliptic.ECC(curve="prime256v1")  # ----->> Line2 print("Server_key: %s" % server_key)   # ----->> Line3 server_key_id = base64.urlsafe_b64encode(server_key.get_pubkey()[1:])  http_ece.keys[server_key_id] = server_key http_ece.labels[server_key_id] = "P-256" encrypted = http_ece.encrypt(data, salt=salt, keyid=server_key_id,             dh=self.receiver_key, authSecret=self.auth_key)  # ----->> Line8 

Value of "Salt" is getting displayed in 100% of the cases.

If Line3 gets executed successfully, I see the the following EntryPoint Error because of http_ece.encrypt() call (Line8):

AttributeError("'EntryPoint' object has no attribute 'resolve'",) 

(Ref. File Link: https://github.com/martinthomson/encrypted-content-encoding/blob/master/python/http_ece/init.py#L128 )

Requirements.txt(partial):

cryptography==1.5 pyelliptic==1.5.7 pyOpenSSL==16.1.0 

On Running the command: sudo pip freeze --all |grep setuptools, I get: setuptools==27.1.2

Please let me know if any more detail is required.

This problem seems to be basically due to some Old/Incompatible packages(related to PyElliptic, Cryptography, PyOpenSSL and/or setuptools) installed on the VM. For Reference: https://github.com/pyca/cryptography/issues/3149

Can someone please suggest a good solution to resolve this issue completely ?

Thanks,

2 Answers

Answers 1

The issue referenced in c66303382 has this traceback (you never gave your traceback so I have to assume yours ends the same way):

File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/__init__.py", line 35, in default_backend     _default_backend = MultiBackend(_available_backends()) File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/__init__.py", line 22, in _available_backends     "cryptography.backends" 

The full line that triggers the error looks like this:

_available_backends_list = [         ep.resolve()         for ep in pkg_resources.iter_entry_points(             "cryptography.backends"         )     ] 

Searching the repository for EntryPoint definition, then blaming pkg_resources/__init__.py where it is reveals that pkg_resources.EntryPoint.resolve() was added in commit 92a553d3adeb431cdf92b136ac9ccc3f2ef98bf1 (2015-01-05) that went into setuptools v11.3.

Thus you'll see this error if you use an older version.

Answers 2

Ran Following Commands from the project path /opt/projects/myproject-google/myproject and it resolved the Attribute EntryPoint Error Issue:

(Assuming project virtual env path as: /opt/projects/myproject-google/venv)

Command: (from path: /opt/projects/myproject-google/myproject)

export PYTHONPATH=      # [Blank] sudo pip install --upgrade virtualenv setuptools sudo rm -rf ../venv sudo virtualenv ../venv source ../venv/bin/activate sudo pip install --upgrade -r requirements.txt deactivate 

Running the above commands upgraded the virtual environment & the setuptools version inside the virtual Env. located at path: /opt/projects/myproject-google/venv/lib/python2.7/site-packages. To test if setuptools have upgraded successfully, try some of these commands:

  1. Command: sudo virtualenv --version Output: 15.0.3
  2. Command: echo $PYTHONPATH Output: [blank]
  3. Command: python -c 'import pkg_resources; print(pkg_resources.__file__)' Output: ~/.local/lib/python2.7/site-packages/pkg_resources/__init__.pyc
  4. Command: python -c 'import sys; print(sys.path)' Output: ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '~/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/opt/projects/myproject-google/myproject', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat']
  5. Command: ls /opt/projects/myproject-google/venv/lib/python2.7/site-packages Output: easy_install.py pip pkg_resources setuptools-27.2.0.dist-info wheel-0.30.0a0.dist-info easy_install.pyc pip-8.1.2.dist-info setuptools wheel
  6. Command: python -c 'from cryptography.hazmat.backends import default_backend; print(default_backend())' Output: <cryptography.hazmat.backends.multibackend.MultiBackend object at 0x7ff83a838d50>
  7. Command /opt/projects/myproject-google/venv/bin/python -c 'from cryptography.hazmat.backends import default_backend; print(default_backend())' Output Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: No module named cryptography.hazmat.backends
  8. Command: /opt/projects/myproject-google/venv/bin/python -c "import pkg_resources; print(pkg_resources.__file__)" Output: /opt/projects/myproject-google/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.pyc

Ref Link: https://github.com/pyca/cryptography/issues/3149

These Steps resolved the Attribute EntryPoint Issue completely with an updated version of cryptography package & the setuptools.

Update As on 15 September 2016, The Cryptography Team has again added the workaround for supporting old packages too. (Ref. Link: https://github.com/pyca/cryptography/issues/3150 )

Read More

Monday, August 1, 2016

HTTPS with PSK using Bouncy Castle

Leave a Comment

I have established a secure socket connection using the Bouncy Castle Pre-Shared Key. I would like to know how to use this socket connection to send my http request securely. I am using a apache http client for sending my http request.

IN short, I have to use https but with PSK Implementation of Bouncy Castle. It is easy to create a socket connection with PSK BC, but how to redirect http request through it ?

0 Answers

Read More

Thursday, June 9, 2016

How do I correctly use libsodium so that it is compatible between versions?

Leave a Comment

I'm planning on storing a bunch of records in a file, where each record is then signed with libsodium. However, I would like future versions of my program to be able to check signatures the current version has made, and ideally vice-versa.

For the current version of Sodium, signatures are made using the Ed25519 algorithm. I imagine that the default primitive can change in new versions of Sodium (otherwise libsodium wouldn't expose a way to choose a particular one, I think).

Should I...

  1. Always use the default primitive (i.e. crypto_sign)
  2. Use a specific primitive (i.e. crypto_sign_ed25519)
  3. Do (1), but store the value of sodium_library_version_major() in the file (either in a dedicated 'sodium version' field or a general 'file format revision' field) and quit if the currently running version is lower
  4. Do (3), but also store crypto_sign_primitive()
  5. Do (4), but also store crypto_sign_bytes() and friends

...or should I do something else entirely?

My program will be written in C.

0 Answers

Read More

Thursday, April 14, 2016

Create RSA Token in nodejs

Leave a Comment

I'm trying to authenticate to a REST API using encryption.

First I need to call the API to get an encryptionKey and a timestamp. The encryptionKey is in Base 64 format.

Then I need to create a RSAToken using the key and finaly encrypt the password using password + "|" + timestamp.

This is some sample code using python to authenticate to the API

key, timestamp = get_encryption_key() decoded_key = key.decode('base64') rsa_key = RSA.importKey(decoded_key) encrypted = rsa_key.encrypt(password + '|' + str(timestamp), 'x') encrypted_password = encrypted[0] 

and

import base64 from Crypto.PublicKey import RSA r = requests.get(my_url, headers=headers)  myData = r.json() decoded = base64.b64decode(myData['encryptionKey']) key = RSA.importKey(decoded) enc = key.encrypt(password + '|' + str(myData['timeStamp']), 'x') encryptedPassword = enc[0]  session = "/session" my_url = url + session  payload = {"identifier": identifier, "password": encryptedPassword, "encryptedPassword": "True" } 

Any hints to achieve this under Node?

1 Answers

Answers 1

You can use crypto.publicEncrypt to encrypt your password. Notice the padding, you might want to use the right padding that is being used in your Python script.

const crypto = require('crypto'); const constants = require('constants'); const decodedKey = Buffer(encriptionKey, 'base64').toString();  const encryptedPassword = crypto.publicEncrypt({     key: decodedKey,     padding : constants.RSA_PKCS1_OAEP_PADDING } , Buffer(`${password}|${timestamp}`)); 

Check out this node.js test to find out more examples for different padding.

Read More

Wednesday, March 16, 2016

Android 6 crypto Cipher.update doesn't work anymore like Android 5

Leave a Comment

The following code worked perfectly on Android 5, now on Android 6 I have this assert error:

junit.framework.ComparisonFailure: expected:

This is clear te[xt right now]

but was:

This is clear te[]

at testAndroidAesCfbDecrypther(AesCfbCryptherTest.java:112)

This function works on Motorola Moto G Android 5.1, Samsunsg S5 Android 5.1 and emulator with Android 5.1. It doesn't work on Motorola Moto G Android 6 and emulator with Android 6.

public void testAndroidAesCfbDecrypther() {    Cipher AESCipher;   final String password = "th3ke1of16b1t3s0"; //password   final byte[] IV = Hex.toBytes("aabbccddeeff3a1224420b1d06174748"); //vector    final String expected = "This is clear text right now";   final byte[] encrypted1 = Hex.toBytes("a1ea8e1c4d8579b84e3e8d48d17fe916a70079b1bdc75841667cc15f");   final byte[] encrypted2 = Hex.toBytes("73052b25306059dda5d6880aa873383124448a38bcb3a769f6aed2f5");    try {         byte[] key = password.getBytes("US-ASCII");         key = Arrays.copyOf(key, 16); // use only first 128 bit           SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");          IvParameterSpec IVSpec = new IvParameterSpec(IV);          AESCipher = Cipher.getInstance("AES/CFB/NoPadding"); //Tried also with and without "BC" provider          AESCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, IVSpec);          byte[] dec1 = AESCipher.update(encrypted1);         String r = new String(dec1);         assertEquals(expected, r); //assert fail here          byte[] dec2 = AESCipher.update(encrypted2);         r = new String(dec2);         assertEquals(expected, r);    } catch (NoSuchAlgorithmException e) {         ...   }  } 

For testing purposes i tried also with 'doFinal', but second assertion fails:

ByteArrayOutputStream bytesStream1 = new ByteArrayOutputStream();  byte[] dec1 = AESCipher.update(encrypted1); bytesStream1.write(dec1); byte[] dec2 = AESCipher.doFinal(); bytesStream1.write(dec2);  r = new String(bytesStream1.toByteArray()); assertEquals(expected, r); //ASSERTION OKAY  ByteArrayOutputStream bytesStream2 = new ByteArrayOutputStream();  dec1 = AESCipher.update(encrypted2); bytesStream2.write(dec1); dec2 = AESCipher.doFinal(); bytesStream2.write(dec2);  r = new String(bytesStream2.toByteArray()); assertEquals(expected, r); //ASSERTION FAIL 

Just as a test I tried the same thing in ruby and it works:

require 'openssl'  expected = "This is clear text right now" encrypted1 = ["a1ea8e1c4d8579b84e3e8d48d17fe916a70079b1bdc75841667cc15f"].pack('H*') encrypted2 = ["73052b25306059dda5d6880aa873383124448a38bcb3a769f6aed2f5"].pack('H*')  decipher = OpenSSL::Cipher.new('AES-128-CFB') decipher.decrypt decipher.key = "th3ke1of16b1t3s0" #password decipher.iv = ["aabbccddeeff3a1224420b1d06174748"].pack('H*') #vector  puts "TEST1-------------------" puts (decipher.update(encrypted1) + decipher.final) == expected ? "OK" : "FAIL" puts "------------------------"  puts "TEST2-------------------" puts (decipher.update(encrypted2) + decipher.final) == expected ? "OK" : "FAIL" puts "------------------------" 

2 Answers

Answers 1

Block ciphers have many different modes of operation. Some like CBC require an additional padding, because only multiples of the block size can be encrypted, but others like CFB are streaming modes without padding.

If you use padding, then the contract is that full blocks are returned from Cipher#update, but the last block that must be padded or unpadded, can only be returned from Cipher#doFinal.

Since CFB mode doesn't need padding, it really shouldn't have this restriction, but then you would have changed the contract, because now Cipher#update can return incomplete data. If this contract is to be enforced even for CFB mode, then the implementation will be consistent and possibly even easier (because of intermediate values and the shift register of CFB).

You really need to finish the decryption and combine the output yourself. It's easy to do this with a ByteArrayOutputStream, but you can also use three System.arraycopy calls.

ByteArrayOutputStream fullPlaintextStream = new ByteArrayOutputStream();  byte[] dec1 = AESCipher.update(encrypted1); fullPlaintextStream.write(dec1);  byte[] dec2 = AESCipher.update(encrypted2); fullPlaintextStream.write(dec2);  byte[] dec3 = AESCipher.doFinal(); fullPlaintextStream.write(dec3);  r = new String(fullPlaintextStream.toByteArray()); assertEquals(expected, r); 

Answers 2

Tried to run the code in java - jdk 1.6 but it fails. Below is what I tried, if its of any help - (modified to be able to run in eclipse by default) :

public static void testAndroidAesCfbDecrypther() {      Cipher AESCipher;     final String password = "th3ke1of16b1t3s0"; //password     final byte[] IV = DatatypeConverter.parseHexBinary("aabbccddeeff3a1224420b1d06174748"); //vector      final String expected = "This is clear text right now";     final byte[] encrypted1 = DatatypeConverter.parseHexBinary("a1ea8e1c4d8579b84e3e8d48d17fe916a70079b1bdc75841667cc15f");     final byte[] encrypted2 = DatatypeConverter.parseHexBinary("73052b25306059dda5d6880aa873383124448a38bcb3a769f6aed2f5");      try {         byte[] key = password.getBytes("US-ASCII");         key = Arrays.copyOf(key, 16); // use only first 128 bit           SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");          IvParameterSpec IVSpec = new IvParameterSpec(IV);          AESCipher = Cipher.getInstance("AES/CFB/NoPadding"); //Tried also with and without "BC" provider          AESCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, IVSpec);          byte[] dec1 = AESCipher.update(encrypted1);         String r = new String(dec1);         assertEquals(expected, r); //assert fail here          byte[] dec2 = AESCipher.update(encrypted2);         r = new String(dec2);         assertEquals(expected, r);      } catch (NoSuchAlgorithmException e) {         e.printStackTrace();     } catch (UnsupportedEncodingException e) {         e.printStackTrace();     } catch (NoSuchPaddingException e) {         e.printStackTrace();     } catch (InvalidKeyException e) {         e.printStackTrace();     } catch (InvalidAlgorithmParameterException e) {         e.printStackTrace();     }  }  private static void assertEquals(String left, String right) {     System.out.println(left+":"+right);     System.out.println(left.equals(right)); } 

Output :

This is clear text right now:This is clear te false This is clear text right now:xt right nowThis is clear text r false 

May be the default buffer sizes changed.

Can you run the above in the two emulators and post the same ?


Also below code helps in identifying the CipherSpi implementation used (assuming security manager does not complain) :

private static void printCipherDetails(Cipher cipher) {     try {         for(Field field : cipher.getClass().getDeclaredFields() ){             field.setAccessible(true);              if( field.getType() == javax.crypto.CipherSpi.class ) {                 Object object = field.get(cipher);                 System.out.print("Name :"+field.getName()+". ");                 if( object != null ) {                     System.out.println("CipherSpi :"+object.getClass());                     }                 else {                     System.out.println("CipherSpi not initialized!");                 }             }             else if(  field.getType() == java.security.Provider.class ) {                 Object object = field.get(cipher);                 System.out.print("Name :"+field.getName()+". ");                 if( object != null ) {                     System.out.println("Provider :"+object.getClass());                  }                 else {                     System.out.println("Provider not initialized!");                 }             }         }     }catch (Exception e) {         e.printStackTrace();     }     System.out.println(""); } 

When invoked after cipher.init(), prints details such as noted below :

Name :b. Provider :class com.sun.crypto.provider.SunJCE Name :c. CipherSpi :class com.sun.crypto.provider.AESCipher Name :j. CipherSpi not initialized! 
Read More