Encryption and Certificates

Some quick notes on doing encryption.

Encryption is a process, by which information can be transformed (encoded) in such a format, that only authorized parties can read (decode) the information, and unauthorized parties cannot. The purpose of encrypting information is to protect the sensitive data from unauthorized use.

Symmetric and Asymmetric Encryption

In a symmetric encryption algorithm, both the sender and the recipient use the same key to encrypt and decrypt the message.

Examples of the Symmetric Algorithms are:

  • DES (Data Encryption Standard)
  • 3DES (Triple Data Encryption Standard)
  • AES (Advanced Encryption Standard)

In an Asymmetric encryption algorithm, sender and the recipient use different keys to encrypt and decrypt the message.

These two keys, or key pairs are called Public Key and Private Key, which we will cover in the next section.

Two most popular Asymmetric Algorithms include:

  • RSA (Rivest Shamir Adelman)
  • PGP (Pretty Good Privacy)

 

Symmetric Encryption

DES Encryption

Data Encryption Standard. An older standard developed in the 1970s, today is no longer used as it can be easily broken. Uses a secret key (56bits) to do the encryption and decryption. Since it’s always the same key size (and the size is fairly small compared to modern computing power), the key can be discovered with brute force attack.

 

3DES Encryption

A follow-on to DES Encryption where it uses the same 56bit key but applies multiple (3) steps during encryption and decryption. The first step is the same as DES in doing the encryption with the key, but then it takes another step in decrypting that encryption with a different key (or cipher) and then applying the encryption to that result once more. The addition of these steps makes the resulted encryption exponentially harder to break with brute force. However, with modern computing it can still be done.

 

AES Encryption

Advanced Encryption Standard is a modern encryption standard where the key is no longer bound to 56bit but can be of variable length. Those lengths can be 128, 192 or 256 and as of today, it is very difficult to break this key with brute force.

 

Example using .Net 

The .Net Framework uses the MachineKey API to do encryption for forms authentication. This API can be used to do any encryption using a key that is unique to the host machine. It is based on a 256bit AES encryption.

// Decrypts given string using machine key
private string DecryptString(string value)
{
   return Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String(value)));
}

// Encrypts given string using machine key
private string EncryptString(string value)
{
   return Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes(value)));
}

https://stackoverflow.com/questions/20497761/net-machinekey-protect-what-algorithm-is-used

 

Example using .Net Core

using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace StringEncryption
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] values = {"adam apple", "becky banana", "charlie cheese", "david donuts", "eddie eggs", "francis fish", "george grapes"};
            string key = "E546C8DF278CD5931069B522E695D4F2"; // use machine key

            foreach (var value in values)
            {
                Console.WriteLine(value);
            }
            Console.WriteLine();

            List encryptedValues = new List();
            foreach (var value in values)
            {
                var encrypted = EncryptString(value, key);
                encryptedValues.Add(encrypted);
                Console.WriteLine(encrypted);
            }
            Console.WriteLine();

            foreach (var value in encryptedValues)
            {
                var decrypted = DecryptString(value, key);
                Console.WriteLine(decrypted);
            }
            Console.WriteLine();
        }

         public static string EncryptString(string text, string keyString)
        {
            var key = Encoding.UTF8.GetBytes(keyString);

            using (var aesAlg = Aes.Create()) // Using AES encryption
            {
                using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
                {
                    using (var msEncrypt = new MemoryStream())
                    {
                        using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(text);
                        }

                        var iv = aesAlg.IV;

                        var decryptedContent = msEncrypt.ToArray();

                        var result = new byte[iv.Length + decryptedContent.Length];

                        Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
                        Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);

                        return Convert.ToBase64String(result);
                    }
                }
            }
        }

        public static string DecryptString(string cipherText, string keyString)
        {
            var fullCipher = Convert.FromBase64String(cipherText);

            var iv = new byte[16];
            var cipher = new byte[16];

            Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
            Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
            var key = Encoding.UTF8.GetBytes(keyString);

            using (var aesAlg = Aes.Create())
            {
                using (var decryptor = aesAlg.CreateDecryptor(key, iv))
                {
                    string result;
                    using (var msDecrypt = new MemoryStream(cipher))
                    {
                        using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (var srDecrypt = new StreamReader(csDecrypt))
                            {
                                result = srDecrypt.ReadToEnd();
                            }
                        }
                    }

                    return result;
                }
            }
        }
    }
}

 

Asymmetric Encryption

Private and Public Keys

Private Key , as the name suggests, is a key that is known only to the sender who possess it, and not known to anybody else. Public Key, on the other hand, can be shared to anyone.

It is important to note that, any data which is encrypted using the private Key can be decrypted by corresponding Public Key (not by any other Public Key). Similarly, any data which is encrypted using the Public Key can be decrypted by corresponding Private Key (not by any other Private Key).

Also, a data which is encrypted by a Private Key, cannot be decrypted by the same Private Key. Similarly, a data which is encrypted by a Public Key, cannot be decrypted by the same Public Key.

Session Key

As the names suggests, a session key is valid for only a single session or transaction. This makes the hackers difficult to break the key, because for every session (even between the same sender and receiver) the session key gets changed.

Please note that encryption using the Session Key is a Symmetric type of Encryption. This means that unlike Private-Public Key Pair, the information is encrypted and decrypted using the same key, the Session Key.

Asymmetric Encryption is complex, slow and consumes more computer resource. So typically, the Asymmetric Encryption is used only at the beginning of the session, just to share the Session Key in a secure manner. Once the Session Key is shared securely, then rest of the communication generally happens using the Session Key.

 

Digital Certificates

A Digital Certificate is a digital form of identification, like a passport or an Identity Card. A digital certificate certifies information about the identity of an entity. Digital certificates are issued by recognized trusted parties known as Certificate Authority (CA).

Apart from the globally recognized CAs like VeriSign, there are some CAs which are trusted within a certain boundary. The most common example of such CA is the Active Directory based Enterprise CA, which is trusted by all computers which are part of that AD Forest. However, certificate issued by that Enterprise CA will not be trusted globally, as computers outside that forest does not trust that Certificate Authority.

Certificate Signing Request (CSR)

A CSR is an encoded text file that is given to a Certificate Authority when applying for an SSL Certificate. While generating the CSR, the Private- Public key pair is generated automatically. The Private Key is securely stored in a location within the computer, from where the CSR wizard has been executed. The Public Key is attached with the CSR file.

When the CA issues the Digital Certificate, it attaches the Public Key with the Certificate along with below information:

  • Name of the entity to which the Certificate has been issued.
  • The CA (Certificate Authority) name, who issued the Digital Certificate.
  • The Certificate Validity Period (From and to dates)
  • Public Key of the Entity, which was shared by the entity while making Certificate Request.
  • Certificate type, purpose , encryption algorithm.
  • Various other information.

Once the requesting entity receives the certificate from the CA, it imports the certificate to its keystore. Keystore is a location where all the digital certificates are stored securely.

Hash Algorithms

Hash Algorithms are one way algorithms, which are used to verify the integrity of an encrypted message. When Hash Algorithm is applied to a particular message, it produces a Digest. Since it is a one way function, it is technically impossible to determine (re generate) the original content from the Digest. Hash Algorithm is used to verify the integrity of a message, whereas Encryption Algorithm is used to encrypt the content of the message.

Popular Hash Algorithms are SHA-1 and SHA-2. Please note that Microsoft (and many other vendors) no longer considers SHA-1 as secured Hash Algorithm, and recommends using SHA-2. Also, the SHA-2 family consists of six hash functions with digests that are 224, 256, 384 or 512 bits: SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, SHA-512/256.

 

Active Directory Certificate Services (AD CS)

Microsoft offers to build a complete Enterprise PKI (Public Key Infrastructure) solution through Active Directory, which is extremely popular among large organizations.

Advantages of internal PKI

  • There is no cost associated per certificate. An organization typically uses thousands of certificates for its internal web servers, application servers, mail servers, users and so on. Purchasing units for each of these certificates from external CA and periodically renewing those certificates would be a costly affair.
  • Organizations can have more granular control over the PKI implementation.
  • AD CS supports a feature called Autoenrollment. Using this feature, a certificate can be automatically approved by the CA as soon as request is generated. This does not require manual intervention for every certificate issuance. Similarly, the Auto Renewal feature will automatically renew a certificate before it expires.
  • Since AD CS is integrated with Active Directory, the overall management of the PKI environment would be simpler with more control.

Disadvantages of internal PKI

  • The CA servers within Internal PKI are not globally trusted.
  • When an organization deploys Enterprise PKI, the responsibility of maintaining that PKI falls under the organization. For that, it requires few skillful CA admins and proper training.
  • The initial deployment and training cost is higher for Enterprise PKI, However, in order to achieve a long term goal, this investment is worth.
  • The organization needs to ensure that the CA servers are secured, and their keys are not compromised. They should also have a recovery plan, in case the key of the CA servers would be compromised.

 

Enterprise Certificate Authority (CA)

When you are going to deploy an Internal CA server, you have the option of deploying Standalone CA or Enterprise CA.

  • For Enterprise CA, the Server must be domain joined at it leverages many features offered by ADCS. For Standalone CA, domain join is not mandatory as it does not use any feature offered by ADCS.
  • Enterprise CA offers features like Certificate Template, Certificate Auto enrollment and Key archival. Standalone CA does not offer these features.
  • Enterprise CA is trusted by all domain joined clients. For Standalone CA, some mechanism is required to establish that trust relationship, which includes adding the CA manually to the client Certificate Store, or using automation / group Policy to do that.

CA Hierarchy

The Enterprise PKI hierarchy starts with the Root CA , also referred as the Trusted Root CA. Since Root CA is the top of the certification hierarchy, the certificate is issued to Root CA by the Root CA itself. In other words, the certificate which is issued to the Root CA is a self sign certificate.

In a certificate hierarchy, Root CA Certificate is the only certificate which is self signed. All other Certificate must be issued either by Root CA or Subordinate CAs. In a PKI environment, all CAs which are not Root CA are called subordinate CAs.

The exact number and hierarchy of subordinate CAs depends on the PKI design. There can be only one layer of subordinate CAs which directly report to Root CA, or in a large and complex environment there can be multiple layers of subordinate CAs.  Subordinate CAs can be Intermediate CAs and Issuing CAs.

Intermediate CAs

Intermediate CAs are subordinate CAs, which directly seats under the Root CA. They act as a layer between Trusted Root CA and Issuing CAs. As Root CA is extremely critical, it just issues certificate to Intermediate CAs , which in turn issue certificates to issuing CAs. This is called “Certificate Trust Chain”

Issuing CAs

These are the CAs which are deployed to issue certificates to end users , computers and applications. In a large PKI environment, there are more than one issuing CAs, each playing a specific role. Example: Infrastructure CA , User CA and so on. While Infrastructure CA will issue Certificates to computers, devices and applications;  User CA would issue certificates to users.

 

Enterprise PKI Tool

For a CA Admin who is handling a large and complex PKI environment, the Enterprise PKI Tool (PKIVIEW.MSC) is one of the most useful tools. Once run from any of the domain joined CA server, the PKIVIEW tool gives a comprehensive picture which is as follows :
  • It discovers and captures the PKI structure of the entire AD Forest. This includes the number of Root CA and all Subordinate CAs.
  • The CA hierarchy of all PKI environment within the forest.
  • It validates the certificates and CRLs to ensure that they are working correctly. If they are not working correctly or if they are about to fail, it provides a detailed warning or some error information.

The PKIVIEW tool gets all this information from Active Directory configuration partition.

Domain Integration

While designing and deploying a PKI environment with the help of ADCS, the CA admin should have a clear idea of the boundary of the PKI environment (which computers, users, apps the environment covers), the AD Domains involved, and if the environment covers all AD Domain/Forest or do we need multiple environments.

Certificate Template

As the name suggests, Certificate Template defines some predefined structure and policies associated with the certificate. The certificate templates and their permissions are defined in Active Directory,  and are valid within the forest. This is because Certificate Templates are stored in AD Configuration partition, which is replicated to the entire forest. When a certificate template is created in one CA, it should be available to all other CAs within that forest, which is accomplished through AD Replication.

Certificate Enrollment

Certificate enrollment request to a CA server can be submitted manually, or we can leverage an ADCS feature called Auto-enrollment. For manual enrollments, it can be done through the Certificates MMC manager (run ‘certmgr.msc’), or through web enrollment which is a web page the CA server interacts with to get information.

Auto Enrollment

Auto-enrollment can happen when the user or computer is on the same domain. Users and computers can do enrollment, retrieval and renewal automatically when below conditions are met.

  • Group Policy
  • Certificate Template

 

Authority Information Access (AIA)

In order to ensure that the certificate is issued by a trusted entity , the SSL client needs to validate the entire chain. The validation will continue until it will reach to the Root CA. The validation process will stop once it will reach to the Root CA, because Root CA is already trusted by the web browser and does not need further validation.
The AIA field captures the location of the issuer certificate, and client can download a copy of the issuer certificate during each stage of validation. So AIA is mostly instrumental to furnish a copy of the intermediate CAs to the SSL client, during the validation process. Another key function of AIA is to support Microsoft Online Certificate Status Protocol (OCSP) Responder. We will discuss OCSP later, but the location of OSCP Responder needs to be added in AIA.

CRL and CDP

Certificate Revocation List (CRL) contains the list of non-expired revoked certificates. It does not contain the revoked certificate itself, but the serial number of the revoked certificate. CRL Distribution Point (CDP) is the repository where CRL can be found and downloaded. Validating CRL is one of the most important part of certificate validation, as the client wants to ensure that the certificate is not revoked by the issuer.

Clients will check this list to see which certificates are no longer valid.

Base and Delta CRL

There are two types of CRL

  • Base CRL : This contains the list of all Revoked certificate. This can be a long list in a large environment.
  • Delta CRL : This contains the list of all revoked certificates since the last base CRL is published.

CRL is generally cached to the client. If the base CRL is already cached, client has to download only the delta CRL.

CDP Protocols

You can publish CDP using LDAP or HTTP protocol. Do not use HTTPS, as client cannot access CRLs using HTTPS due to authentication issue. In a Windows based domain environment, publishing CDPs using LDAP has some advantages.
  • It offers fault tolerance, through Active Directory replication.
  • With the help of AD Sites, client can download CRL from the nearest Domain Controller.
    However, non-windows and Windows workgroup clients cannot leverage LDAP to download CRL. Also, to access the CDP over LDAP, various firewall ports need to be opened.
However, in general, publishing CDP using HTTP has some advantages over LDAP. First of all, any client can access an HTTP based CDP irrespective of OS and Domain join status. Secondly, It does not require complex firewall rules to be implemented.

High Availability

Another factor which needs to be considered is the High Availability of CDP and AIA. Please note that in order to make the revocation checking successful, client must access both Base CRL and Delta CRL (if enabled). So a CA administrator must plan to ensure that CRLs of all CAs are accessible and there is some fault tolerance. Similarly, in order to validate the issuer’s certificate and (if enabled) to access OSCP, the client must access AIA .

Online Certificate Status Protocol (OCSP)

There are certain management overhead involved in order to configure CDP and manage it. Also, the client needs to download these CRLs and go through each serial number to confirm that the specific certificate is not revoked.

Starting from Windows Server 2008, Microsoft launched a feature called Online Certificate Status Protocol, or in short OCSP.

The OCSP approach is little different than the CRL approach. In the CRL approach, the client goes through a given list (or lists) to ensure that a specific serial number is not there.

OCSP has two major components: 1) Online Responder 2) OCSP Client

Online Responder (Or OSCP Responder) is the server component, which accepts requests from OCSP client to check the revocation status of a certificate. Before making the request, client uses AIA extension to check whether OSCP is configured, and if yes what is the OSCP responder location.

The OCSP responder server FQDN must be specified in the AIA field, following below format :
http:// <FQDN of OSCP responder server>/ocsp

Windows Vista or above can act as an OCSP client.

 

 

 

 

References

Comparison of DES, 3DES and AES
https://stackoverflow.com/questions/5554526/comparison-of-des-triple-des-aes-blowfish-encryption-for-data

http://blog.syncsort.com/2018/08/data-security/aes-vs-des-encryption-standard-3des-tdea/

https://social.technet.microsoft.com/wiki/contents/articles/51429.active-directory-certificate-services-digital-certificate-overview.aspx