четверг, 25 сентября 2014 г.

Preparing to MS Exam 70-483 - Perform symmetric and asymmetric encryption

The full set of questions I'm trying to cover in time of my preparation to MS Exam 70-483  you can find here.

Encryption is the process of transforming some plain data to make it harder for an unauthorized person to read it. The encrypted data is called ciphertext. Decryption is the reverse process of applying some transformation to the ciphertextto to get back the original information.
Before encrypt data it should be converted to byte sequence. 

Asymmetric vs Symmetric algorithms

There are two abstract classes in the System.Security.Cryptography namespace which reflect two main encryption techniques:
  • AsymmetricAlgorithm class - Represents the abstract base class from which all implementations of asymmetric algorithms must inherit. 
    • Properties:
      • BlockSize
      • FeedbackSize
      • IV
      • Key
      • KeySize
      • LegalBlockSizes
      • LegalKeySizes
      • Mode
      • Padding
    • Methods:
      • Clear() 
      • Create(["AlgoritmName"])
      • CreateDecryptor([Key, IV])
      • CreateEncryptor([Key, IV])
      • GenerateIV()
      • GenerateKey()
      • ValidKeySize()
    • Derived classes:
      • Aes
        • AesManaged 
        • AesCryptoServiceProvider
      • DES
        • DESCryptoServiceProvider class
      • RC2
        • RC2CryptoServiceProvider class
      • Rijndael
        • RijndaelManaged
      • TripleDES
        • TripleDESCryptoServiceProvider
  • SymmetricAlgorithm class - Represents the abstract base class from which all implementations of symmetric algorithms must inherit.
    • Properties:
      • KeyExchangingAlgorithm
      • KeySize
      • LegalKeySizes
      • SignatureAlgorithm
    • Methods:
      • Clear()
      • Create(["AlgoritmName"])
      • FromXMLString(bool includePrivateParameters)
      • ToXMLString()
    • Derived classes:
      • DSA
        • DSACryptoServiceProvider class
      • ECDiffieHellman
        • ECDiffieHellmanCng
      • ECDsa
        • ECDsaCng
      • RSA
        • RSACryptoServiceProvider
  • The classes which name is the algorithm name suffixed with CryptoServiceProvider wrappers around the native Cryptography API (CAPI) implementation. 
  • The classes which name is the algorithm name suffixed with Managed are managed classes which implement some algorithms. They are slower and are not certified by FIPS organization.
  • The classes which name is the algorithm name suffixed with CNG are wrappers around the native Cryptography Next Generation (CNG) API implementation.

Symmetric Encryption

The workflow of encrypting plain text using symmetric encryption:
  1. Create a symmetric algorithm object by calling the SymmetricAlgorithm.Create() method and setting the optional string parameter to the name of the wanted algorithm. 
  2. Setting a key and an IV (not necessary because they are generated by default).
  3. Create an encryptor by calling the CreateEncryptor method on the symmetric algorithm object. It is possible to change the key and the IV by passing parameters to this method.
  4. Call the TransformFinalBlock(plain data, offset, length) method on the encryptor. It will return the encrypted data back.

Decryption is similar to the encryption workflow.

Asymmetric Encryption

The essence of the assymetric encryption is very good described by a GIF on codeproject's article dedicated to this subject:
Teken from codeproject's article of RaviRanjankr

Encrypting data:
  1. Create an asymmetric encryption object
  2. Set the public key
  3. Encrypt the data
  4. Send the data to the receiver
  5. Clear the asymmetric encryption object
Decrypting data:

  1. Create an asymmetric encryption object
  2. Set the private key
  3. Decrypt the data
  4. Clear the asymmetric encryption object

Key Management

There is a static class in the System.Security.Cryptography namespace which is called ProtectedData.This class provides access to the Data Protection API (DPAPI) available in Microsoft Windows 2000 and later operating systems. This is a service that is provided by the operating system and does not require additional libraries. It provides protection using the user or machine credentials to encrypt or decrypt data.

static class ProtectedData 

  • Protect(byte[] data, byte[]  optionalEntropy, DataProtectionScope scope)
    • Optional Entropy is used to increase complexity of encoded data
    • DataProtectionScope can take two values
      • DataProtectionScope.CurrentUser
      • DataProtectionScope.LocalMachine
  • Unprotect(byte[] data, byte[]  optionalEntropy, DataProtectionScope scope)

The class consists of two wrappers for the unmanaged DPAPI, Protect and Unprotect. These two methods can be used to encrypt and decrypt data such as passwords, keys, and connection strings.

Using of these methods during impersonation can cause the error: "Key not valid for use in specified state.", because the DPAPI stores the key data in user profiles and if the profile is not loaded, DPAPI won’t be able to perform the decryption. 

Stream Encryption

To encrypt stream use System.Security.Cryptography.CryptoStream.
Stream encryption is very similar to symmetric encription workflow with only change in point number 4. Instead of  calling  the method TransformFinalBlock of encryptor/decryptor it should be passed to new instance of CryptoStream as the second parameter:
CryptoStream(memory, cryptor, CryptoStreamMode.Read)
CryptoStream class
  • Methods
    • Clear()
    • CopyTo()
    • CopyToAsync()
    • Flush()
    • FlushFinalBlock() - Updates the underlying data source or repository with the current state of the buffer, then clears the buffer.
    • Read(buffer, offset, count)
    • Write()

Hashing Data

Hashing is the mapping of binary data of variable lengh to a binary data of fixed size.
Hashing is used for:
  • supporting data integrity
    • immutable data
  • sequrity purposes
    • passwords
    • data authenticity
  • searching
    • use of hash buckets
Hashig algorithms:
  • with key
    • data integrity
    • data indexing
  • without key
    • data integrity
    • authenticity
All hashing algorithms in .NET are derived from HashAlgorithm abstract class.

HashAlgorithm class
  • Properties (read-only)
    • CanReuseTransform
    • CanTransformMultipleBlocks
    • Hash
    • HashSize
    • InputBlockSize
    • OutputBlockSize
  • Methods
    • Clear()
    • ComputeHash(byte[])
    • ComputeHash(stream)
    • ComputeHash(byte[], offset, length)
    • Create() - by default SHA1
    • Create(String)
    • TransformBlock() - Computes the hash value for the specified region of the input byte array and copies the specified region of the input byte array to the specified region of the output byte array.
    • TransformFinalBlock() - Computes the hash value for the specified region of the specified byte array.
  • Derived classes
    • SHA1 - 160 bits hash code
    • SHA256
    • SHA384
    • SHA512
    • MD5 - 128  bits hash code
    • RIPEMD160 - 160 bits hash code
byte[] input = Encoding.Default.GetBytes("Some data...");
 HashAlgorithm hash = HashAlgorithm.Create();
 byte[] buffer = new byte[input.Length];
 Console.WriteLine(hash.TransformBlock(input, 0, input.Length, buffer, 0));


The keyed hashing algorithms inherit from the System.Security.Cryptography.KeyedHashAlgorithm class, and the difference in comparacing with the HashAlgorithm class is only one property - Key.
KeyedHashAlgorithm.Key is the property representing the key to be used class.

If you attempt to change the key after the hashing has begun, a CryptographicException is thrown

Choose an appropriate encryption algorithm

Microsoft gives recomendations how to choose an appropriate algorithm:
  • Data privacy: 
    • Aes.
  • Data integrity:
    • HMACSHA256 
    • HMACSHA512.
  • Digital signatures:
    • RSA 
    • ECDsa.
  • Random number generation:
    • RNGCryptoServiceProvider.
  • Generating a key from a password:
    • Rfc2898DeriveBytes.
  • Key exchange,
    • RSA 
    • ECDiffieHellman.

Managing and creating certificates

Asymmetric encryption + Hashing = Digital certificates
This formula represents realisation of secutiry and data integrity in the face of one thing called certificate. Asymmetric encryption serves for secure data transmission and hashing serves for checking if the transmitted data correspond to original one,

There is a tool for generatin x.509 certificates called Makecert.exe. This tool creates a certificate and after installation it on your system it stores at certificate store which enables you use it:
makecert -n “CN=Rvach_Flyver” -sr currentuser -ss myCertStore