L0030 OpenSSL Algorithms and Ciphers

TLS Protocol

The Internet Engineering Task Force (IETF) organization publishes the TLS security protocol, which is used to ensure the integrity and privacy of communications over a computer network. This protocol describes how various algorithms ( "cryptographic primitives" ) are used to achieve this goal. OpenSSL is one of the softwares that implements this security protocol.

TLS means "Transport Layer Security". The old name of this protocol was "Secure Socket Layer" ( SSL ). That is why we have the name "OpenSSL".

Cipher Suites Nomenclature

"Cipher suites" are security protocol algorithms ( "cryptographic primitives" ) that are usually used together.

We can run this command to list cipher suites.
openssl ciphers -v
Command "ciphers" will list the cipher suites, and option "-v" will give us a verbose presentation.

The name of one cipher suite is divided into 4 parts.
– The first part ( ECDHE ) is the name of the algorithm used for key exchange.
– The second part ( ECDSA ) is algorithm for asymmetric cryptography.
– The third part ( AES256-GCM ) is algorithm used for symmetric encryption.
– The fourth part ( SHA384 ) is a hashing algorithm.
                                                                                                                        
ECDHE–ECDSA–AES256-GCM–SHA384

These elements are called "Cryptographic primitives", because the are building blocks from which protocols are made.

Only the third algorithm ( AES256-GCM ) is a cipher ( encryption ) algorithm, but traditionally we call them all together a "cipher suite".

In the second column we can see different versions of the TLS security protocol ( TLSv1.3, TLSv1.2 ). These versions are generations of this protocol from different years. Notice hat TLSv1.3 version cipher suites don't list all of the security algorithms. Key exchange algorithm and Asymmetric key algorithm are not included.

In the previous versions of the TLS standard, list of the cipher suites was huge. That was the consequence of the fact that there are many security algorithms and they can be combined in different ways. In order to simplify things, TLSv1.3 did two things:
1) It retired old security algorithms that are safe no more.
2) The name of the cipher suite is now broken into three parts ( ECDHE,      ECDSA,      AES256-GCM–SHA384 ). Key exchange algorithm and asymmetric key algorithm are separated. This is possible because key exchange and asymmetric key algorithms are technology that is independent from the rest of algorithms. We can choose them independently.

Cipher Command

"Cipher" command is used to list cipher suites. I will use Linux command "wc" ( word count ) to count how many cipher suites will this command return. We will test some ways how to limit number of the returned cipher suites.

openssl ciphers -v | wc60We will see 60 suites. These are the suites that OpenSSL recommend for us.
openssl ciphers -v DEFAULT | wc60The same as above.
openssl ciphers -v ALL | wc140This will list all of the supported suites. There are 140 suites in total.
openssl ciphers -v HIGH | wc140This will return only strong cipher suites. All 140 cipher suites are considered strong. Options "MEDIUM" and "LOW" are no more working because such suites are deleted from TLSv1.3.
openssl ciphers -s -v | wc
                                                            
30Option "-s" is for supported suites. This will return 30 suites. Some suites are not applicable on our current configuration. This could be because we disabled some suites in our configuration file, or because OpenSSL is compiled with some algorithms missing, or some other reason.
openssl ciphers -v 'RSA SHA384'38We will filter only for these "cryptographic primitives". Only the suites that are using RSA, for asymmetric key, or SHA384, for hash, will be returned. We will get 38 suites.
openssl ciphers -v 'RSA DEFAULT' | wc22We can combine different conditions, for example RSA and DEFUALT.

All Possible Cipher Suites

Long lists of cipher suites, that includes deprecated historical suites, can be found on these web pages:

https://www.iana.org/assignments/tls-parameters/tls-parameters.txt
https://ciphersuite.info/search/?q=aes

Lists of Individual Algorithms

We can get lists of individual algorithms with these commands:

openssl list -key-exchange-algorithmsList all key exchange algorithms.
openssl list -public-key-algorithmsList all asymmetric key algorithms.
openssl list -cipher-algorithmsList all symmetric key algorithms.
openssl list -digest-algorithmsList all hash algorithms.

Recommended Algorithms

Key Exchange Algorithms

TLSv1.3 only supports DHE and ECDHE. ECDHE* is better than DHE because the keys are smaller and there is less CPU usage.* EC – Elliptic curve. This helps algorithm to be faster.
* DH – Diffie-Hellman algorithm. The key is never transported over network.
* E – Ephemeral. Keys are temporary. Each session uses different keys.

ECDHE and DHE provide "perfect forward secrecy". Because the keys are short-lived, even if someone steals the keys, they will only be able to decrypt communications from one session. They will not be able to decrypt messages from previous sessions.

Asymmetric Key Algorithms

Today we use either RSA or ECDSA keys. RSA keys are supported everywhere and are much more compatible. Otherwise ECDSA keys are better.
RSA is short for "Rivest–Shamir–Adleman". ECDSA is short for "Elliptic Curve Digital Signature Algorithm".

ECDSA has smaller keys, certificates, and signatures. It uses less CPU. This makes the TLS handshake between the client and server faster. This is especially important for mobile devices, high-traffic websites, and cloud services. RSA is still more popular for most websites today, but for high-performance internet services, ECDSA has taken the lead. For new installations, ECDSA is often the first choice.

For the same level of security, ECDSA keys are much smaller than RSA keys. Even worse, RSA keys scale poorly. If the ECDSA key is doubled, then the RSA key must be 5 times larger to achieve the same level of security. This is why RSA keys will be deprecated in the near future.ECDSARSA
112-bit2048-bit
128-bit3072-bit
192-bit7680-bit
256-bit15360-bit

Symmetric Encryption Algorithms

We use either CHACHA20 or the AES algorithm. CHACHA20 is a better and faster algorithm. The AES algorithm is an older algorithm and most modern processors have hardware acceleration for this algorithm. As a result, the AES algorithm is, in real-world use, faster than CHACHA20.

This is only true for computers. Phones and other mobile devices historically did not have AES hardware support, and that is why most phones today use CHACHA20.

Most servers are set up to offer AES encryption first, and CHACHA20 encryption as an alternative. One is for computers, the other for phones.

You can use the command "lscpu | grep aes" to check if your computer CPU has dedicated AES circuits.

Hash Algorithms

Today we use SHA hash algorithms.

Cipher Modes

You probably noticed that AES algorithm is somehow connected with "GCM" ( AES256-GCM ). To understand GCM we must talk about cipher modes. Symmetric encryption algorithms can be divided into "stream ciphers" and "block ciphers". "block ciphers" can be further divided into different "cipher modes".

Plaintext and Ciphertext

Plaintext is unencrypted message, like "Hello world!". Ciphertext is encrypted message, something like "lloeH lr!wod".

Stream Ciphers

For stream encryption we need symmetric key, "nonce" and plaintext. Nonce can be any number selected for specific each session. Each session will use different nonce. "Nonce" means number used once.

Algorithm will use nonce and symmetric key to create random stream of ones and zeros. That stream is called "Keystream". Thanks to nonce, this keystream will be different each session.

Keystream will be combined with the message with XOR logic. This will create the "ciphertext".

Plaintext  = 101011111001
Keystream  = 100111000010   # XOR
Ciphertext = 001100111011

For decryption, we need nonce, symmetric key and ciphertext. Nonce is public value and will be delivered to receiver. Using the same ingredients, he will generate the same "keystream". He will then apply XOR between ciphertext and the keystream to get plaintext.Ciphertext = 001100111011
Keystream  = 100111000010   # XOR
Plaintext  = 101011111001         

Why do we Need Nonce?

Let's say that we have 2 plaintexts and a keystream. Keystream only depends on the symmetric key.P1 = 1100P2 = 1010K = 0111
Without nonce, the keystream will be the same for both messages. We will calculate ciphertexts.C1 = 1011C2 = 1101 

Because keystream is the same, the attacker can find out the difference between two plaintexts which is the same as the difference between ciphertexts. Here is the proof.P1 XOR P2 =  C1        XOR  C2
P1 XOR P2 = (P1 XOR K) XOR (P2 XOR K)
P1 XOR P2 =  P1 XOR P2 XOR   K XOR K   # XOR is commutative and associative
P1 XOR P2 =  P1 XOR P2 XOR   0         # because K XOR K = 0
P1 XOR P2 =  P1 XOR P2

                                                                                                                  
So, the difference between 2 plaintexts is:P1 XOR P2 = C1 XOR C2 = 1011 XOR 1101 = 0110

Hacker now knows the difference between two messages. If the hacker guess or discover the content of message P1, he immediately knows the content of the message P2. This is why we need Nonce.

Block Ciphers

Block ciphers will divide data into blocks and each block will be encrypted separately. Block Ciphers are divided into different "cipher modes".

ECB Cipher Mode

ECB Cipher Mode ( Electronic Code Book ) is simple. We divide our message into blocks and we encrypt each block with symmetric key.

Plaintext "110010100111" is divided into 3 blocks.110010100111
We use symmetric key on each block to get 3 ciphertexts.

Problem with ECB is that patterns from the plaintext are preserved in the ciphertext.

CBC Cipher Mode

CBC (Cipher Block Chaining) was invented to solve the problem with ECB revealing data patterns.

We have three plaintexts.Initializing vector IV is randomly created artificial "plaintext".IV = 1011P1 = 1000P2 = 1110P3 = 1001

We will XOR each plaintext with the previous one.P1 XOR IV = 0011P2 XOR P1 = 0110P3 XOR P2 = 0111
We can now use key to encrypt messages. The patterns will be hidden.

Encryption of each block depends on the previous block. That is why we can not parallelize this calculation. That makes the calculation slow.

CRT Cipher Mode

"Counter" mode is using approach similar to stream ciphers. First, we generate one keystream. We add counters to that keystream.

Keystream = "0110"0110001011000201100030110004
We encrypt these combinations "keystream+counter" by using symmetric key.0110001002101000103011004001

Now we have encrypted keystreams that can be XOR-ed with the plaintext.

The random part of the keystream is saved with the first block of data, and is sent to receiver. Receiver will need that keystream for decryption. So, the keystream is not hidden, but what is important is that for each block we will use different keystream because of the counter.

Each "keystream+counter" combination can be encrypted on different CPU core, so we will achieve high parallelization.

GCM Cipher Mode

All previous cipher modes are solving the problem of encryption. We can also solve the problem of integrity. Someone can tamper with our ciphertext so the edited message will be sent, and the receiver will not be able to notice that.

Galois/Counter mode is made to solve two problems. This Cipher Mode introduce so-called "Authenticated encryption". This is complex algorithm that can at the same time both encrypt the data and authenticate it. GCM is based on the CRT cipher mode.

Experience showed that separate algorithms for encryption and authentication are not the best approach. Hacker can use separation of these two algorithms to find cracks in our protection. It is much better to do encryption and authentication in one step.

Beside "Authenticated encryption" we also need same unencrypted data, that is needed for decryption. Such data we call "Associated data". Together "Authenticated encryption AE" and "Associated data AD", make AEAD. When we look at some of the cipher suites, we will see this AEAD label:

MAC

On the image above we can see "Mac=AEAD" for one suite, and "Mac=SHA384" for another. "Mac" means "Message Authentication Code". "Mac" refers to a way how we provide integrity of data.

When we talked about signatures, we said that signature is encrypted combination of the hash and identification data. For calculation of a hash, we need hash algorithm like "SHA384". This was the old way of providing integrity. Before, encryption and hashing were separate activities.

"HMAC" is hashed based "Mac". This refers to those old algorithms. In modern cipher suites we don't use "HMAC". We use newer technologies which are labeled as AEAD. AEAD is faster and more secure than "HMAC".

Today we use methods that provide Encryption and Authentication in one algorithm. That is what AEAD algorithms are about. Modern cipher suites use something like "AES256-GCM" or "CHACHA20-POLY1305" because these are modern AEAD algorithms.

When we look at the first cipher suite from the image above "DHE-RSA-AES128-GCM-SHA256", we can see that "Mac=AEAD". In this case SHA256 refers to hash algorithm used for something else ( for example, for initializing vector, or for keystream ), and is not used for providing the integrity of messages.

Stream vs Block Ciphers

There is not much difference between stream and block ciphers. For example, POLY1305 is a stream cipher. It is used together with CHACHA20 encryption and that is why is popular on phones. GCM is block cipher, and is used on computers with AES, because computer CPUs have hardware support for AES.

L0020 Symmetric and Asymmetric Keys

Authentication Problem

How to Encrypt a Document with Asymmetric Keys?

Using RSA algorithm, I will create private and public key. I will call them PrivEncryptKey and PubEncryptKey.I will personaly deliver my PubEncryptKey to coworker.She will use RSA algorithm and PubEncryptKey to encrypt the document.

She will email me this encrypted document. The only person who can decrypt this document is the one with the PrivEncryptKey. If I receive this document, I will be able to decrypt it.

This solved the privacy problem, but what about authentication? When I receive an encrypted document, I want to know with certainty who is the person who sent me the document.

How my Coworker Can Prove Her Identity?

In this case, we won't be doing any encryption. This time, we're looking for a way to authenticate Anna when she sends the document.

My colleague will create hash code of the document using SHA algorithm.Our goal is to somehow bind that hash code with the identity of the person sending the document.
'8a12' + "Anna"

My coworker will create another pair of keys. I will call them PrivIdentKey and PubIdentKey.Anna now has two keys. She will personally give me her PubIdentKey. I will use this key to validate her identity.Anna will use PrivIdentKey to encrypt "hash+identity". She is using RSA algorithm. The result of encryption is a signature. Anna signed document hash code.

She will now send me 2 things: the document, and the signature.I already have Annas PubIdentKey. I will use that key to decrypt her signature. This will give me document hash code and her identity.

We now know that Anna signed the hash code. The last step is to prove that the document Anna have sent to me, is connected to that hash code.I will now calculate the hash code of the document using the same SHA algorithm. If that result is the same as the hash code from the signature, that will tell me that this document was sent by Anna.

Visible Sign on a Document

Identity information is not just about cyber security. Identity is important for classification, organization, and storage of documents. So, it's nice to visibly tag documents with some identity information.

Two-side Communication, Encrypted and Authenticated

To achieve both Encryption and Authentication we need two pairs of keys. One pair belongs to receiver and is used for encryption ( PrivEncrypKey, PubEncryptKey ). The other pair belongs to sender and is used for authentication ( PrivIdentKey , PubIdentKey  ). This is enough for one-side communication. In the real world, for two side-communication 4 pairs of keys are used. Having separate pair of keys for each function, makes key management much easier.

You can notice that there is no real need for 4 pair of keys. Two pairs would do the job, because Encryption keys can also be used for Authentication, but just like I said, it is easer if we have a separate pair of keys for each function.

What is Wrong with the Simple Example?

There is a problem with this simple example that will occur when the other person is far away. We cannot deliver our public keys in person. If we send those keys by email, that defeats the purpose. Then the communication will be insecure again, the other person will have no guarantee that the public key is authentic. To solve this problem, we need Certification Authority. A CA is a "mutual friend" who is trusted by both parties.

Certification Authority ( CA )

A certification authority is an organization that is large, reputable, and trustworthy. It can be a government, a private company, or the organization we work for. The certification authority will sign our public key, thus proving its authenticity.

Each key, including PubEncryptKey, is one big hexadecimal number. That is why we can treat PubEncryptKey as a file.Inside of that file we will add identity data. We want to bind public key of a person with his identity data.We can now calculate a hash code that includes the public key and identity data.

CA organization has its own private and public key.CA will do the binding. CA will use its private key to encrypt hash code. That will give us a guarantee that the public key is genuine.

Certification is the same as signing. Instead of some business document, this time we are signing combination of a person's public key and his identity information.Public key, identity and signature together make a Certificate.

The CA will use its private key to make the certificate. It will also securely deliver its own public key to the remote person safely. The validation process is now a two-step process:
– First, use the CA's public key to verify the person's certificate.
– Use the public key, which was contained within the certificate, for encryption/authentication.

CA, together with their clients makes PKI. PKI is "Public Key Infrastructure". PKI includes software, hardware, policies, standards, professional associations and everything else that is needed to manage digital certificates.

Symmetric Keys vs Asymmetric Keys

We can't use symmetric keys for authentication, but this is not the biggest drawback. The biggest drawback of symmetric keys is their scalability. If we have 100 people who need to communicate securely, and any two of them need to have their own unique key pair, then the number of keys needed is astronomical. If we were to use the same key for 100 people, then the probability that the key will be compromised is high.

Asymmetric keys scale much better. Each person needs to have their own key pair, and that is enough for communication between any two people.

But, on the other side, there are two important advantages of the symmetric keys.
1) Encryption and Decryption with symmetric keys is much faster.
2) Encrypted files have the same size as unencrypted files. This is not true for asymmetric cryptography where encryption enlarge the file size.

Hybrid Cryptography

The solution to "Symmetric vs Asymmetric" conflict is to combine Symmetric and Asymmetric cryptography:

1) Use symmetric encryption when you want to share a lot of data, especially if you have a secure way to share symmetric key between people.
2) Use asymmetric encryption for sending small but highly sensitive pieces of data.

You can already see that these two methods complement each other. This is especially true when dealing with servers. Servers are made to provide huge quantities of data, so they really need this hybrid cryptography. This is how secure client-server communication works:

Server uses asymmetric cryptography for initial exchange of the symmetric keys. After that, data is exchanged using more efficient symmetric cryptography. This combination is called "hybrid encryption". The process is like this:
1. Client asks Server for its certificate.
2. Server sends the Client the signed certificate.
3. Client use CA public key to check that certificate.
4. Client creates random symmetric key.
5. Client encrypts that key using the server public key.
6. Client sends that encrypted symmetric key to server.
7. Both sides now have the same key and they continue communicating by using symmetric cryptography.

How Does the Client Check Server Certificate?

Inside the server certificate we have a lot of different information. Client will compare them:
– Is IP/domain of the server the same as in the certificate.
– Is certificate valid. Certificate is valid only between the dates written inside of the certificate.
– Is certificate prematurely revoked. Revoked certificates are listed in online registries. The client must check online if our certificate is revoked.
Owner: db.company.local
Public key: ABC123...
Issued by: MyCompanyCA
Valid until: 2028

Serial number: 883
                                       

Key Exchange

Symmetric cryptography does not have a secure way to exchange keys between two parties. Asymmetric cryptography is great at this. We saw that the RSA algorithm can be used to exchange keys (the key is just another document). Today we have an even better algorithm for this purpose. The Diffie-Hellman algorithm is another asymmetric cryptographic algorithm that is based on a private and a public key. This algorithm is special because it allows users to decide on a shared symmetric key, without ever sending that key over the network. This is great because no network hacker can steal our symmetric key.

Diffie-Hellman Algorithm ( DF )

Prime Number "P" and Generator "G"

First, we must choose one prime number. I will choose 23. When we divide random number X with this number 23, the reminder will be one of the numbers 0,1,2…20,21,22.0   <=    MOD( X, 23 )   <=   22

Next, we need "Generator" number. This number can generate all of these numbers 1-22 ( zero is always excluded ). I will use number 5. Let's test:

5^1MOD23
5
5^2MOD23
2
5^3MOD23
10
5^4MOD23
4
5^5MOD23
20
5^6MOD23
8
5^7MOD23
17
5^8MOD23
16
5^9MOD23
11
5^10MOD23
9
5^11MOD23
22
5^12MOD23
18
5^13MOD23
21
5^14MOD23
13
5^15MOD23
19
5^16MOD23
3
5^17MOD23
15
5^18MOD23
6
5^19MOD23
7
5^20MOD23
12
5^21MOD23
14
5^22MOD23
1

We will get results 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22. We got each number 1-22 exactly once.

In production, we need huge numbers for "P" and "G". It is hard to find numbers that match requested criteria. That is why today we use modern version of DF algorithm that is called "Elliptic-curve Diffie-Hellman". This algorithm always uses the same predefined numbers for "P" and "G".

Numbers "P" and "G" are public numbers. We don't have to hide them. Both parties know what are those numbers, and both parties are using the same pair of these numbers.

Private Numbers

The next step is that each party must choose their private key. That should be a number between 1 and ( P – 2 ). I will choose numbers 4 and 7, both of those numbers are less then 21 ( 23 -2 ). Parties must keep these numbers hidden.

Public Numbers

Each party will now independently calculate their public numbers using the formula "G ^ Private MOD P".

Party A:    5 ^ 4 MOD 23 = 4
                                       
Party B:     5 ^ 7 MOD 23 = 17

Parties will exchange their public numbers. Only private numbers are hidden, everything else is shared =>

Calculating Symmetric Key

Each party will now calculate the same symmetric key.
For calculation they need their private key, public key of the opposite party, and "P".
Party A:
( Public B ^ Private A ) MOD P
Party B:
( Public A ^ Private B ) MOD P
Let's confirm that shared keys will be the same.( 17 ^ 4 ) MOD 23 = 8( 4 ^ 7 ) MOD 23 = 8

L0010 Intro to OpenSSL Cryptography

Cryptography secures communication by converting information into an unreadable format. OpenSSL je the most popular cryptography library. When we connect to HTTPS websites, secure email servers, secured databases or VPN connections, we are most likely using OpenSSL.

We can use OpenSSL as an application library, or we can use it through its command-line interface.

Cryptography Techniques

One-Way Function

If you spill milk, it's very difficult to collect it. If you break a plate, it's almost impossible to put the pieces back together. One-way functions are like that. It's easy to make a change, but it's not easy to undo it.
If it is easy to calculate "y=f(x)", but it is difficult to calculate "x=f-1(y)", then we have one-way function. There are two important types of one-way functions:
1) one-way functions where solving the reverse function is impossible task.
2) one-way functions where we can easily reverse the change if we know a secret piece of information. These are so-called trapdoor functions.

Hash Function

Hash function is an example of the irreversible function.

A hash function takes some data and transforms
it into a result that has specific characteristics.
The result is called hash code (or digest).
'Good morning' -> '51ef''Bonjour' -> 'f48d''Dobro jutro' -> '88bf'

These are the qualities of good hash function:

1) Function is one-way. It is impossible to reconstruct data from the hash code.'51ef' -> 'Good morning'     # not possible
2) Function is deterministic. Same input always gives the same output.'Bonjour' -> 'f48d', 'Bonjour' -> 'f48d'    #each time
3) Small change in input creates a huge change in output.'Bonjour' -> 'f48d', 'Zonjour' -> '7fbd'  #totaly different code
4) Probability for two same results, for different arguments, is small.'Bonjour' -> 'f48d', 'Buongiorno' -> 'f48d'   #unlikely
5) Hash code will be small ( 30-40 characters ), and always of the same size. This makes it practical and standardized for different tools to use it.'51ef', 'f48d', '88bf'   # always 4 characters
6) If we have a text and a hash, we can not easily find some other text that would have the same hash.'Bonjour' -> 'f48d'  # it is hard to find other message with the same hash
7) Hash can be calculated quickly and easily. 

I'll give you an example of a simple, but bad hash function. This function will replace each letter with the number of its position in the alphabet. It will add those numbers together and take the last digit from the result. It has many of the qualities listed above. In the example below, we can see that it lacks quality number 4).

A   p    p    l    e
1 + 16 + 16 + 12 + 5 = 50
O    r    a   n    g   e
15 + 18 + 1 + 14 + 7 + 5 = 60
Hash for the word "Apple" is 0, and hash for the word "Orange" is 0, too.

Other names for hash function are Checksum, Fingerprint or Digest function. We can use hash to label and recognize some data.

Trapdoor Function

Let's say we have two prime numbers. I'll use "p = 47" and "q = 59". If we multiply them, we get "2773". If I tell you that my number is "2773" and that this number is the product of two prime numbers, will it be feasible for you to find the two numbers?

You can use a computer to try to find a number that divides "2773". The brute force approach will always work, but only if the number is small enough. If the number is larger, even a computer won't help you.

The solution is to get a secret key from me. If I tell you that the value of "p" is "47", then you can easily calculate that "q = 2773 / 47 = 59". This makes this multiplication easy to inverse, but only if you have the secret key.

Encryption

Encryption is a way of scrambling data so that only authorized parties can understand the information. Here are some examples. Only the person who has the key will be able to read these encrypted messages.

Substitution Encryption

I will write two phrases.The Big BangThe Raising Sun
I will use "Webding" font for these phrases.

This is simple substitution encryption. Each letter is replaced with a different graphical sign.

XOR Encryption

I will write the number 14 using its binary representation.1110   # zero is representing FALSE and one is representing TRUE
This will be my password. I will again use binary syntax.0011   # zero is representing FALSE and one is representing TRUE

XOR operator is working by this logic.
Only if arguments are different, it will return TRUE.
XOR( FALSE, FALSE )XOR( TRUE, TRUE )XOR( FALSE, TRUE )XOR( TRUE, FALSE )
FALSEFALSETRUETRUE

We can combine the number 1110 and password 0011 with XOR operator, to encrypt the number. Encrypted number will be 1101.XOR( 1, 0 )XOR( 1, 0 )XOR( 1, 1 )XOR( 0, 1 )
1                  1                  0                  1                  

I will now show you how to use hashing and encryption with OpenSSL.

OpenSSL

OpenSSL Installation

I am using Ubuntu as my operational system. Let's see if the OpenSSL is already installed. Usually, it is.

openssl version
We can add option "-a" to get more information about OpenSSL.
If your system doesn't have OpenSSL, you can easily install it with this line:

# sudo apt install openssl

OpenSSL Commands

This is how we can list all of the OpenSSL commands.  
openssl help

This will show us all of the Standard, Digest and Cipher commands.
It is also possible to limit this output to only those commands that interest us.
openssl list -standard-commands
openssl list -digest-commands
openssl list -cipher-commands

For specific command we can get help like this:  

openssl dgst -help

OpenSSL Man Pages

We can get Man pages for OpenSSL with this command.
man openssl  

For specific command we can see Man pages like this:  
man openssl-dgst

OpenSSL Hashing

I will first create one file, and I will place it on the Desktop.  
seq 100 > /home/fff/Desktop/sequence1.txt  
This file will contain numbers 1-100, although the content is not important.
I will also create another version of this file that will have the number "9999" in the first line. I will name it "sequence2.txt".

For hash creation, we will use "dgst" command. We can see on the image the hash that was created. We can run this command several times and each time we will get the same result. The hashing algorithm is deterministic.

cd /home/fff/Desktop
openssl dgst -sha256 sequence1.txt
Currently we have files "sequence1.txt" and "sequence2.txt". They are almost the same. But their hashes will not be similar, they will be totally different.
openssl dgst -sha256 sequence2.txt

All of the hashes will be of the same size, 64 hexadecimal characters.
echo -n "Hello, World!" | openssl sha256

Hash Algorithms

We are using the command "dgst" to create a hash. We can also provide the hash algorithm. There are many algorithms, we used "sha256" algorithm.   We can get the list of hash algorithms with this command:
openssl list -digest-algorithms

OpenSSL Encryption

This command will encrypt the file "sequence1.txt" by using "-aes-256-cbc" algorithm. We will be asked to enter our password twice.
openssl enc -aes-256-cbc -in sequence1.txt -out sequence1.enc

Notice that we are getting a warning to use "-iter" or "-pbkdf2". To encrypt data, AES algorithm must use 256-bit key, so the first step is to transform our password into this key, using hash algorithm. Transformation of the password into key is much more computationally demanding if we use "-pbkdf2" option. We should always use it because it will slow down hacker. To understand why is that important, we must first learn what is a "salt".

Salt

For safety reasons passwords are never saved as the plain text. They are first recalculated into hash code and then saved. When the user provides his password, computer will use algorithm to find hash code of that password and then it will compare that hash code with the saved one. In that way computer can identify the correct password.

A hacker can create a collection of commonly used passwords. He can then pre-compute hash codes for each of them. If the hash code of a stolen user's hash code, matches one of the pre-computed values, the hacker will immediately know what the password is. This allows the hacker to reverse the hash function. We want to prevent this.

Solution is to make hash codes more random and unpredictable. This can be done with a "salt". Salt is a random string that is concatenated to a password. Instead of the password being "pass123", now it will become "pass123KX8G#A". AES-256 key will be calculated by hashing this salted password.

Now, hacker must use different strategy. The hacker will add the salt to each of the most often used passwords. Then he will calculate hash code for the password + salt combination. This calculation takes same time, but we can make it even longer if we use "-pbkdf2". Usage of "-pbkdf2" means that creation of AES-256 key takes more computational power. Thanks to salt and "pbkdf2", a hacker will be forced to spend a few seconds for each password. That will make impossible for him to brut force the password.

But where is the salt stored? The answer is that salt string "KX8G#A" will be saved together with an encrypted file. The "salt" itself is not encrypted. Anyone, who has encrypted file, can read the salt. When the user tries to decrypt the file, his password will be combined with a salt to generate salted password, that will be used for decryption.

Now, that we now about "-pbkdf2" and "-salt" we should add them to our command.

openssl enc -aes-256-cbc -pbkdf2 -salt -in sequence1.txt -out sequence1.enc     # the old file will be overwritten

Encrypted File


binary file
The result of the "enc" command will be a binary file. We can choose to generate "base64" encrypted file, if we use "-a" option.
openssl enc -aes-256-cbc -pbkdf2 -salt -a -in sequence1.txt -out sequence1base64.enc
Now, our file is textual file, we can copy-paste it anywhere =>                                                                                                                

OpenSSL Decryption

For decryption we have to use "-d" option.                                                                                                                     
openssl enc -d -aes-256-cbc -pbkdf2 -in sequence1.enc -out sequence1decr.txt
Because the key was created with "-pbkdf2" option, we must use it during the decryption.
This command will confirm that there is no difference between the original and decrypted file.
diff sequence1.txt sequence1decr.txt

Above, we decrypted binary file. For decrypting "base64" file we have to use "-a" option.
openssl enc -d -aes-256-cbc -pbkdf2 -a -in sequence1base64.enc -out sequence1base64.txt

Encryption Algorithms

This is how we can find the list of all of the encryption algorithms.  

openssl list -cipher-algorithms  

Symmetric vs Asymmetric Keys

When we used "enc" OpenSSL command, we only provided privacy. It is the same as if the users exchanged their files inside of the encrypted ZIP file.
This kind of encryption is based on the symmetric keys, because there is a password that must be known by both of the parties.

For authentication, we must use asymmetric keys. In that case, there are two keys. One is the private key; the other is the public key. The private key is something that we hide and don't share with others. A person can use the private key to identify themselves. Public key is used to verify that identity.

To understand how private/public keys are related and generated, we'll look at the mathematics of the RSA algorithm for creating asymmetric keys. This isn't something we have to know, but it's really interesting to know.

RSA Algorithm

We will start by choosing two random prime numbers. I will choose 3 and 11. We will label them with P = 3 and Q = 11.

From P and Q we will calculate their product and their "Totient". "Totient" is a special mathematical property.PQN ( Product )              T ( Totient )                                  
311P * Q = 3 * 11 = 33( P – 1 ) ( Q – 1 ) = 2 * 10 = 20

Public Exponent "E"

P and Q will help us find E (the public exponent) and D (the private exponent). First, we will choose a public exponent. The public exponent must satisfy conditions below. The number 7 satisfies all of these conditions, so that will be our public exponent.

1) The public exponent E must be a prime number. 7 is a prime number.
2) It must be less than Totient ( 7 < 20 ).
3) Totient cannot be divided by the public exponent ( 20 / 7 = 2,857 ).

Private Exponent "D"

For private exponent "D" there is only one condition.
This equation must be satisfied: "MOD( D * E, T ) = 1".
There are many values for D that will satisfy this condition.
D = 3MOD( 3 * 7, 20 ) = 1
D = 23MOD( 23 * 7, 20 )  = 1
D = 43MOD( 43 * 7, 20 ) = 1
D = 63MOD( 63 * 7, 20 ) = 1

Each time we increase the number D by +20, we get a candidate. I will use the smallest number D = 3.

RSA Encryption

I will encrypt number "16".MOD( 16 ^ D, N ) = MOD( 16 ^ 3, 33 ) = 25The number "16" encrypted is "25".

RSA Decryption

I will decrypt number "25".MOD( 25 ^ E, N ) = MOD( 25 ^ 7, 33 ) = 16The number "25" decrypted is "16".

For encryption, we need to know the private key. For decryption, we only need to know the public key. This property will help us use asymmetric keys for authentication.

Some Consideration for RSA Math

Modulus

When doing encryption and decryption we use Modulus function. We write Modulus function like this MOD(). This is the syntax that we use in spreadsheet programs. In mathematics we use different syntax:

MOD( 16 ^ D, N ) = 16 ^ D MOD NThis is the reason why in RSA terminology "Modulus" is a name for the number N. When we say "Modulus", we mean the number N.
MOD( 25 ^ E, N ) = 25 ^ E MOD N

Private and Public Key

For encryption we need private exponent D and Modulus N. Together they make a private key ( D, N ).

Similar to that, for decryption we need public exponent E and Modulus N. Together they are a public key ( E, N ).

Public Key is Derived from Private Key

This is something we hear often in lessons about cryptography. This is not true for RSA keys. For RSA keys, both keys are calculated based on the secret values for P and Q.

Every Asymmetric Key is Using One Way-Function

But where is the one-way function in the RSA algorithm? Let's say that the hacker knows the public key ( E, N ), and he wants to find the private key ( D, N ). Public key is not something that is a secret, only private key is secret.

Private key depends on Totient T. MOD( D * E, T ) = 1Totient T depends on P and Q.
( P – 1 ) ( Q – 1 )
P and Q are factors of Modulus.
P * Q = N 
In the encryption example above we already saw that it hard to find P and Q, even with the help of a computer.

Modulus is calculated by the one-way function. It is easy to calculate N = f( P, Q ), but it is hard to calculate ( P, Q ) = f-1( N ).

RSA Keys are Commutative

We can do encryption with private exponent D = 3, and we can do decryption with public exponent E = 7. It is also possible for them to reverse their roles. We can encrypt with 7, and decrypt with 3. This is something that is unique for RSA asymmetric keys.

0005 MonetDB Benchmark

Benchmark Data

For this benchmark we will use sales data from the fictitious company "Contoso". We can download our database from the github. If we go to this address, we will find there compressed CSV files with the data. In total there are 8 files of 500 MB, and one smaller file with 250 MB ( 4250 MB in total ).  

https://github.com/sql-bi/Contoso-Data-Generator-V2-Data/releases/tag/ready-to-use-data

When we unzip these files, inside we will find 8 CSV files. This is sales cube with tables that can show us sales and orders per product, customer, date and store.

Three big tables are "Orders" ( 88M ), "Sales" ( 211M ) and "OrderRows" ( 211M ). Dimension table "Customer" has 2M rows, and all the other dimension tables are small.

Not all of the columns are shown on the image.

——————————————————————————————
In CSV file "date.csv" I will change the names of columns month=>month2 and year=>year2, because MonetDB will not accept original names. "Month" and "Year" are reserved words.

Machine Hardware

For this benchmark we will use CPU with 8 cores and 64 GB of RAM.

Our operational system is Zorin 18.

Creating Tables and Loading CSV Files

OrderRows Table

CREATE TABLE orderrows (
OrderKey BIGINT NOT NULL,
LineNumber SMALLINT NOT NULL,
ProductKey SMALLINT NOT NULL,
Quantity SMALLINT NOT NULL,
UnitPrice REAL NOT NULL, --DECIMAL(8,4)

NetPrice REAL NOT NULL, --DECIMAL(10,6)
UnitCost REAL NOT NULL --DECIMAL(8,4)
);
First, I will create table for OrderRows in the MonetDB. I will not create primary and foreign key constraints this time.

I will fill this table from my CSV file with "COPY INTO" statement.  

COPY OFFSET 2 INTO orderrows
FROM '/home/fff/Desktop/CSVs/orderrows.csv'
USING DELIMITERS ',', E'\n', '"'

NULL AS ''; 

Import of this 211M rows table will last only one minute ( 56.241 sec ). Amazing.

Other Tables

I will leave a file for download at the end of this article. That file will have SQL for creation and import of all of the Contoso tables.

Bellow we can see time for import for two other larger files. Smaller dimension tables are imported almost instantly.

Sales (211M) table will need almost 5 minutes to be imported.
Orders (88M) CSV table will be imported in 62 seconds.

Query Benchmarking

Cold Start

I will now restart my computer. I want to make sure to run a cold query. This simple query bellow will run for 10 seconds. MonetDB database becomes faster as more queries are executed. This ability of MonetDB is called "cracking". MonetDB will automatically sort, group and index columns during the SELECT queries. That will make subsequent queries faster.  

SELECT * FROM sales LIMIT 1;

If we run this query again, it will be executed in just 1.3 miliseconds. This is not the result of query caching. If we make a query that takes 2 or 3 rows, we will again see these exceptional speeds.

SELECT * FROM sales LIMIT 2;
SELECT * FROM sales LIMIT 3;

Aggregated Queries in MonetDB

If we aggregate two columns in the "sales" table, that query will touch 211M rows. It will be fast ( 2.268 sec. ), but we can repeat it to get only 94.915 ms.

SELECT SUM( quantity ), AVG( unitprice ) FROM sales;

I will run the same query, but this time with a filter.
SELECT SUM( quantity ), AVG( unitprice )
FROM sales WHERE orderdate <= '2020-05-25';

                                                                                          
We will get the result even faster. This proves that the result is not cached. MonetDB run the query again, but this time "cracking" made our query faster.

It's hard to make a benchmark when execution times are constantly changing. So, from now on I will focus on the fastest times.

How Database Reports Execution Time

SELECT * FROM sales LIMIT 1000000;   --13 ms
SELECT * FROM sales LIMIT 2000000;  --24 ms
                                                                                       
MonetDB is reporting that the second query is slower than the first one. That is something that we are expecting. The problem is that according to my computer clock the first query was finished after 7 seconds, and the second one after 15 seconds.

Databases only report the time spent to produce the results in the memory. It will not include the time needed to print the result in the shell or any other client. That is why MonetDB is reporting 13 ms, but I can see the result only after 7 seconds. MonetDB has command to suppress printing of the result in the shell. I will use that command ( command explained here ) next, to test reading the whole tables.

This is how long it takes MonetDB to read a large number of rows. Columnar databases are better suited for aggregate queries, but we can see that MonetDB is capable of performing OLTP types of queries quite well.

I will disable my command, so we can again see the results of our queries.

Joins

SELECT productkey, SUM( quantity ), AVG( netprice )
FROM sales GROUP BY productkey;
This query will execute for 340 ms. If we want to see brands then we have to make a join between "product" and "sales" tables.

SELECT brand, SUM( quantity ), AVG( netprice )
FROM sales INNER JOIN product
   ON sales.productkey = product.productkey GROUP BY brand;

                                                                 
The query with a join will last more than 1 second. We can speed it up if we create a foreign key constraint.

ALTER TABLE product ADD CONSTRAINT product_pk PRIMARY KEY ( productkey );
ALTER TABLE sales ADD CONSTRAINT FKfromProduct FOREIGN KEY ( productkey )

REFERENCES product ( productkey );
Now that we have foreign key constraint,
the query from before will become 200 ms
faster. That is 20% faster.

Query from before is a traditional analytical query. If we look at system monitor, we will see that during the execution of this query the load will be equally distributed between CPU cores. MonetDB is capable to significantly parallelize query execution. That means that our individual queries can be speed up with a CPU that has even more cores.

DISTINCT, LIKE, ROLLUP

From the table "customer" we can list distinct continents and genders in 3.841 ms.  
                                                           
SELECT DISTINCT continent, gender FROM customer;
We can get distinct combinations of storekey and currency code from "sales" table in half of the second.  

SELECT DISTINCT storekey, currencycode
FROM sales;

If we want to count unique combinations of the orderkey and currencycode, then our query will be slow, it will last almost 11 seconds. But this query has to count 88 million rows.

SELECT COUNT( * ) FROM
    ( SELECT DISTINCT orderkey, currencycode
      FROM sales );
Query like this will also last 11 seconds.
                                                                                 
SELECT COUNT( * ) FROM
 ( SELECT orderkey, currencycode
   FROM sales
   GROUP BY orderkey, currencycode );

LIKE operator allows usage of the wild cards. Sign "_" will replace one letter.  

SELECT currencycode, SUM( quantity ), MAX( unitprice )
FROM sales
WHERE currencycode LIKE '_U_' GROUP BY currencycode;

If we use the sign "%" that replaces several characters, then the speed will drop, almost double.  

SELECT currencycode, SUM( quantity ), MAX( unitprice )
FROM sales
WHERE currencycode LIKE '%U_' GROUP BY currencycode;

Before we test ROLLUP, I will create foreign key constraint between "customer" and "sales" tables.  

ALTER TABLE customer ADD CONSTRAINT customer_pk PRIMARY KEY ( customerkey );
ALTER TABLE sales ADD CONSTRAINT FKfromCustomer FOREIGN KEY ( customerkey ) REFERENCES customer ( customerkey );

This time we have unusually slow query. It will take full 10 seconds.
SELECT continent, title, SUM( quantity )
FROM customer INNER JOIN sales
   ON customer.customerkey = sales.customerkey
GROUP BY ROLLUP( continent, title );
——————————————————————————————————————————–
Query with union would be much better choice for this. Only 1.837 seconds.
SELECT continent, title, SUM( quantity )
FROM sales INNER JOIN customer ON sales.customerkey = customer.customerkey
GROUP BY continent, title
UNION
SELECT continent, null, SUM( quantity )
FROM sales INNER JOIN customer ON sales.customerkey = customer.customerkey
GROUP BY continent
UNION

SELECT null, null, SUM( quantity ) FROM sales;
 

This show us that there is still room
for improvements in MonetDB optimizer.

Window Functions

I will first add foreign key constraint between "sales" and "date" tables.  

ALTER TABLE date ADD CONSTRAINT date_pk PRIMARY KEY ( date );
ALTER TABLE sales ADD CONSTRAINT FKfromDate FOREIGN KEY ( orderdate ) REFERENCES date ( date );

We can use LAG function to compare sales for the current and the previous row. Each value from quantity column will have a pair in the BeforeQty column, except in the first row ( no previous ). Quantity in that first row will make a difference. This query will execute in 2 seconds.  

SELECT ( SUM( Qty ) - SUM( BeforeQty ) ) AS Difference FROM
( SELECT Quantity AS Qty,
  LAG( Quantity, -1 ) OVER ( ORDER BY date ) AS BeforeQty                                  
  FROM date INNER JOIN sales ON date.date = sales.orderdate );

For each row in the table, we will calculate the average quantity of the previous 6 rows and the current row. At the end will see sums of the quantity and these rolling averages. This query will last 29 seconds.

SELECT SUM( Quantity ) AS "SumQty", SUM( AvgBefore7Qty ) AS "SumAvgBefore7Qty" FROM
( SELECT Date, Quantity,
     AVG( Quantity ) OVER
         ( ORDER BY Date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
             AS AvgBefore7Qty
FROM date INNER JOIN sales ON date.date = sales.orderdate );

Updates

MonetDB should be slow for updates, but it managed to update 44 milion rows for just 4.19 seconds.
UPDATE sales SET currencycode = 'EU' WHERE currencycode = 'EUR';

We can confirm that all of the values 'EUR' are updated to 'EU'.  

SELECT DISTINCT currencycode FROM sales;

Problematic Queries

Double Grouping

Double grouping is when we first group our data, and then we group that result. For example, we will total sales quantity per customerkey, and then we will count customers per total quantity. We will count how many customers have the same total quantity.

This query is problematic because while the first grouping can be fast, the second one could be much longer. The result of the first grouping will have 2M rows, because we have so much customers. In the second stage, we have to group these 2M rows, and that is when I expect the performance to become bad.

SELECT customer.customerkey, SUM( quantity ) AS TotQty
FROM customer INNER JOIN sales ON customer.customerkey = sales.customerkey

GROUP BY customer.customerkey;     
In the first phase I will measure how
much time is needed to group by customer.
It is 5 seconds because there are 2 million customers.

Second phase:
SELECT TotQty, COUNT( customerkey ) FROM
( SELECT customer.customerkey, SUM( quantity ) AS TotQty  
   FROM customer INNER JOIN sales ON customer.customerkey = sales.customerkey
   GROUP BY customer.customerkey ) as FirstPhase
GROUP BY TotQty;  


We can see on the image that we have 2,663 customers with total quantity of 333 items, and only two with 1,130 items. The time for execution is again 5 seconds. This is something I didn't expect. I am pleasantly surprised. I can tell you that these kinds of queries are problematic for Power BI database ( SSAS ).

Aggregated Query from Two Fact Tables ( Stitch Query )

This time I will create foreign key constraint on the "OrderRows" (211M) table. I want to aggregate sales and orderrows per product brend.
ALTER TABLE orderrows ADD CONSTRAINT FK_Product FOREIGN KEY ( productkey ) REFERENCES product ( productkey );

"Stitch" query is when we aggregate two fact tables per the same dimension and we get two data sets as a result. Then we join those two data sets in the final result. This is how we aggregate values from two fact tables.

Query bellow will last 7.5 seconds. This is longer than I expected. If we ran subqueries separately the time would be just 900 ms each. Because we only have 15 brands, it is surprising that it will take 5 seconds just to join two small tables.
SELECT S.brand, Sq, Oq FROM
( SELECT Brand, SUM( quantity ) Sq FROM Product INNER JOIN Sales ON Product.Productkey = Sales.ProductKey GROUP BY Brand ) S
INNER JOIN
( SELECT Brand, SUM( quantity ) Oq FROM Product INNER JOIN Orderrows ON Product.Productkey = OrderRows.ProductKey GROUP BY Brand ) O
ON S.Brand = O.Brand;
If we "UNION ALL" our subqueries, the execution will last 7.5 seconds, too.
SELECT Brand, SUM( quantity ) Sq FROM Product INNER JOIN Sales ON Product.Productkey = Sales.ProductKey GROUP BY Brand
UNION ALL
SELECT Brand, SUM( quantity ) Oq FROM Product INNER JOIN Orderrows ON Product.Productkey = OrderRows.ProductKey GROUP BY Brand;

I have tried to read two small subqueries into python, and then to join them with pandas. Python reported execution time of just 1.2 seconds. It is strange that we can get the final result faster by combining MonetDB and Pandas, then just by using MonetDB.

WITH S AS                                                                                                                  
( SELECT productkey, SUM( quantity ) AS Sq FROM Sales GROUP BY productkey ),

O AS
( SELECT productkey, SUM( quantity ) AS Oq FROM Orderrows GROUP BY productkey ),
PS AS
( SELECT brand, SUM( Sq ) AS SQty FROM Product INNER JOIN S ON Product.productkey = S.productkey GROUP BY brand ),
PO AS
( SELECT brand, SUM( Oq ) AS OQty FROM Product INNER JOIN O ON Product.productkey = O.productkey GROUP BY brand )
SELECT PS.brand, Sqty, OQty FROM PS INNER JOIN PO ON PS.brand = PO.brand;
We can reduce our fact tables by grouping them by productkey and then following the same logic. This approach would speed up our query to 5.5 seconds.

WITH S AS ( SELECT productkey, SUM(quantity) AS Sq
            FROM sales
            GROUP BY productkey ),
O AS ( SELECT productkey, SUM(quantlty) AS Oq
       FROM orderrows
       GROUP BY productkey )
SELECT P.brand, SUM(S.Sq) AS Sq, SUM(O.Oq) AS Oq
FROM product P
 LEFT JOIN S ON S.productkey = P.productkey
 LEFT JOIN O ON O.productkey = P.productkey
GROUP BY P.brand;
This would be the fastest
version of this query. It would
execute in only 3 seconds.

In this query, we would use the
the last subquery to join reduced
sales and orderRows tables, with
the product table.

INSERT INTO SELECT

I will use "INSERT INTO SELECT" to make "Sales" table bigger.  Before doing that, I will remove FK constraints. I will also change optimizer.
ALTER TABLE sales DROP CONSTRAINT fkfromproduct;
ALTER TABLE sales DROP CONSTRAINT fkfromcustomer;
ALTER TABLE sales DROP CONSTRAINT fkfromdate;
SET sys.optimizer = 'minimal_pipe';
I will now run this statement to make my sales table twice bigger.
INSERT INTO sales SELECT * FROM sales;
MonetDB needed 5 minutes to do this.

I will do this 1 more time. That will double the number of rows to 844M. That was done in 9:48 minutes.
Then, I will again read from the CSV file into this table. That will add another 211M rows, so in total "sales" table will now have one billion rows.

I will recreate foreign key constraint toward "product" table.
ALTER TABLE sales ADD CONSTRAINT FKfromProduct FOREIGN KEY ( productkey ) REFERENCES product ( productkey );

I will run now this query twice. The first time it will end after 28 seconds, and the second time after 5,5 seconds.
SELECT brand, SUM( quantity ), AVG( netprice )
FROM sales INNER JOIN product
   ON sales.productkey = product.productkey
GROUP BY brand;

SELECT color, SUM( quantity ), AVG( netprice ) FROM product INNER JOIN sales
   ON sales.productkey = product.productkey
GROUP BY color;
Immediately after, I run the same query, by it was grouped by color. The time was again 5 seconds.

We can see that performance is good, even with 1B rows.

Conclusions

We can conclude some things:
– MonetDB is usually very fast.
– Initially, until the database worm up, queries can be slow.
– We should always set foreign key constraints to achieve speed boost.
– Some kinds of queries are better optimized than others.
– MonetDB does not use much memory. During the import of the "sales" table, the RAM usage increased from 4 to 13 GB. It was the same during this last, 1B rows, query. At other times, the usage was much less.

0000 MonetDB Introduction

Bundled Products vs Products in Bulk

Stores like to sell products as a bundle. For example, the store will sell a box with several decorations as one product. Store will benefit from this because:
– Stacking and scanning products is easier when the are bundled ( effort- ).
– The buyer will spent less time in the store choosing decorations ( speed+ ).
– We can sell more decorations by bundling less popular decorations with the more popular ones ( sale+ ).
But bundles make production planning harder.
– We have to unbundle data about products to find out how much each individual shape/color was sold ( effort+ ).
– We are usually looking at sale for a longer period of time. Because of quantity of data, unbundling will make our database real slow ( speed- ).
– We have to read data about all the shapes/colors, although we just want to analyze the sale of one of the shapes/colors ( analysis- ).

Data in Bundle or in Bulk

We can treat transactions as one bundle product. Product code, quantity and price are one bundle. We want to be able to quickly save this data bundle.We can achieve this by saving our transactions as separate rows in a database. That is how we can quickly save or retrieve individual transaction as a bundle.

For production planning we will differently organize our data. We will organize it into columns. If we want to find out how many products, we have sold that have the price lower than 3 EUR, we just have to scan the column "Price", and then to find specific positions in the column "Qty".

Each column can be sorted and compressed for even faster retrieval.

We don't even need to read the column "Product".

When we organize data in rows, we use a row-oriented database. When we organize data in columns, we use a columnar database. Data is typically collected in a row-oriented database (Postgres, Oracle, MySQL) and then transferred to a columnar database for analytics ( ClickHouse, DuckDB, Vertica ).

Row Oriented Databases vs Columnar Databases

Row oriented databases:
1) They are great for small writes/reads. Perfect for "insert one order", "update this user", "delete this invoice line" etc.
2) Application code often works with whole objects/rows (User, Order, Invoice), which matches row layout.
3) Great for transaction isolation, replication, ACID complacence, constraints, triggers, foreign keys.
4) We have many users who send queries that touch only one row from a table and expect an immediate response from the database.  

They are best for Cash registers, ERP, CRM, banking systems, ticketing.
Columnar databases:
1) We only read columns we need, and columns can be heavily compressed. That improves IO.
2) CPU can process several values of the same type at once. This is called vectorized execution. Queries with lot of data will work faster.
3) Column scans and aggregations are easy to parallelize across cores and nodes.
4) We have smaller number of queries, but they are much heavier, they touch a lot of data, with lot of joins, but the users are expecting results in 3-4 seconds.  

They are best for sales reports, dashboards, time-series, data mining.

Row oriented databases are catching current state and providing transactional correctness. Columnar databases are for analysis of the historical data. We can also say that row-oriented databases are better in writing data and providing data consistency and integrity. Columnar databases are better in reading huge quantities of data.

OLTP vs OLAP

If we are preparing our database for everyday operations and transactions, then we are making OLTP database. For analytics and BI, we would prepare OLAP database. OLTP is compatible with row-oriented databases, and OLAP with columnar databases.

In the OLTP databases, data is  organized in a lot of small tables. There is no data duplication and every value is written only once.
                                      
Small tables make queries more complex so these databases usually don't grow significantly in size.
In the OLAP databases, we merge small tables to reduce their number. Columnar technology have no problem with tall tables that have a lot of columns.  

By reducing the number of joins, we can query our data with simpler (faster) queries. That is why we organize our tables in a star schema.

OLTP tables are filled with data by users and applications in small transactions. From time to time ( usually nightly ), data is transformed and transported into OLAP databases in batches. This makes data management different between OLTP and OLAP databases. OLTP databases receive data continuously, but OLAP databases receive data periodically and only after data is well-reformed.

OLTP is acronym for "Online Transaction Processing" and OLAP for "Online Analytical Processing". We saw that the difference is made by:
      – Different purpose and usage.
      – Different database technology.
      – Different data organization inside the database.
      – Different data management.

Data Immutability

Columnar ( OLAP ) databases are filled in batches. That doesn't mean that it is not possible to UPDATE or DELETE rows in tables. There are four strategies that OLAP databases use:

1) Data is immutable. We can only insert data in batches, and afterward we can not change individual rows. If data is immutable and presorted then we can achieve the biggest levels of compression. The example of this technology is the database used for Power BI.  2) MonetDB is an example of the OLAP database that is suited for light updates and deletes. When we delete/update some value, MonetDB will label old record as "dead". That record will become invisible to queries. After some time, garbage collection will remove not-needed records.

3) We can divide our columns into small segments. Whenever we want to change some value, we modify the whole segment. This is good solution when we have a lot of hardware power, like cloud providers do. Google Snowflake is an example of such database.    
4) We can have two databases in one. One database is row-oriented, and the other one is columnar. Data is written into row-oriented database, but when we want to read data we read from both databases together. Historical data is read from the columnar database, and today's data is read from the row-oriented database. SAP Hana is using such approach.  This last strategy creates something called "Hybrid Transaction Analytical Processing", or HTAP. HTAP is when a single database can do fast real-time transactions and fast analytics on the same data at the same time.  

In recent years, MonetDB researchers have been gradually adding or experimenting with features that move it slightly toward the HTAP category:  – Better handling of frequent updates and small transactions
– Improved concurrency and snapshot isolation
– Faster incremental data loads
– Optimizations for mixed workloads

MonetDB

If you have one server and install MonetDB on it, you will be able to:
      – Enjoy blazing-fast query performance, even if you have a lot of data and your queries are more complex.
      – Avoid thinking about indexing, compression, statistics tuning, partitioning decisions. MonetDB will do it all automatically.
      – Apply the full power of SQL to all your tables, whether they are carefully modeled or just collected in one place.
      – Spend your money on something else because MonetDB is an open source database under the Mozilla Public License.

MonetDB is a fast, complete SQL, easy-to-maintain, open source analytical database server that can process huge amounts of data on a single server machine.

Hardware and Speed Considerations for MonetDB

MonetDB doesn't have a requirement to keep the whole database in a RAM memory. Parts of data that are already processed will be deleted from memory. MonetDB have capacity to deal with data that is much bigger than the amount of memory on your server machine. Only data that is currently processed will have just-in-memory execution pipelines.

MonetDB, will benefit from the fast NVMe disk, that has sustained performance under write load. Such disk should be accompanied with a lot of RAM memory, so that usage of a disk is minimal.

MonetDB is designed to take the full advantage of your CPU.
– When executing a query or loading data, MonetDB will spread the load across all processor cores, increasing CPU utilization to over 90%. There is a setting that can limit the number of cores used by MonetDB.
– Vectorized query execution means that the processor can process thousands of values ​​with a single instruction. The values ​​must be of the same data type, which is perfect for columnar databases.
– Data is processed in small chunks using simple instructions. This reduces RAM visits and uses the processor's fast L1/L2 memory.
– Late materialization means that we avoid reading data that does not contribute to our query. We will only read the data needed for the final dataset, and skip everything else.
– Partial query results are reused instead of being recomputed.

Zero-Tuning Philosophy

MonetDB will not burden you with indexing strategies, partitioning decisions and vacuuming. MonetDB tries to eliminate complexity. Most workloads run at full speed without manual optimization. Indexes are automatic. Compression is automatic. Memory management is automatic.

Creating indexes manually is problematic because you need to know in advance where to create the indexes. Indexes can slow down updates and deletes because when data is modified, the database must also update the corresponding indexes to reflect these changes. This is something that we especially want to avoid in the columnar databases. If users change their behavior, that can make our indexes ineffective.

Technique that MonetDB use to automatically tune indexes is called database cracking. Cracking means that MonetDB will sort and group data, and create indexes during SELECT queries. If most of the statements on the OLAP databases are SELECT queries, and such queries touch a lot of rows, then it is best to create indexes and tune data during the SELECT queries execution. This is optimal because:

   – The parts of a database that are heavily used will be tuned the best. We will not spend effort on data that no one reads.
   – Instead of heaving one huge indexing job, we will have many tiny, incremental reorganizations.
   – After some time, our data will be optimally indexed and sorted, but MonetDB can change strategy if users change their behavior.
   – Cracking is especially powerful in columnar databases like MonetDB, where each column is stored separately.

Cracking is powerful but not ideal for everything:

   – Heavy transactional workloads (many updates) disrupt adaptive patterns.
   – Distributed cracking across many nodes is still complex.
   – Highly unpredictable workloads (all queries unique) limit its benefits.

Comparison of MonetDB and Power BI

Power BI database ( SSAS Tabular )  is in-memory database, that is using compressed columnar tables, and is optimized for BI models ( dimensions, measures, heirarchies ). Power BI needs the whole model loaded in the memory, but columns are heavily compressed, so Power BI doesn't have huge memory footprint. For many calculations Power BI doesn't even need to decompress columns, so it can do its work while maintaining really fast IO.

Power BI likes table relationships and measures defined in advance, and is not optimized for arbitrary queries.  It is not intended for complex joins outside the model. If we spend time creating optimal model, and we wait for our model to process/refresh during the load, we will get database that is optimized for:

   – measure evaluation
   – filters
   – slice and dice

On the other side MonetDB is optimized for raw analytical SQL on large tables, without modeling overhead.

MonetDB Imperfections

As columnar server, MonetDB suffers from all of the shortcomings that columnar servers have. MonetDB is not good in transactional traffic, and lot of deletes and updates. MonetDB is not perfect for reports that return huge tables with lot of columns. MonetDB is best for short, aggregated analytical queries.

If you have massive amounts of data, you will need a computer cluster, and cloud scalability. This is something where MonetDB doesn't shine. MonetDB is best if you have one powerful server machine, and you want to run complex analytics on it. Distributed databases are better in scaling, but because their setup is more complex and they are spread over many computers, they usually have less rich SQL capabilities and other limitations.

MonetDB does not support replication, but it does support distributed operation across multiple machines via sharding. Sharding will speed up some queries, but not all. If we want to set up a cluster with MonetDB, partitioning and sharding must be done carefully and manually. If possible, it is better to have a single powerful server than to resort to sharding and expensive network equipment.

MonetDB Market Position

You should use MonetDB if you want to:
   – Self-hosting an analytical database on your server.
   – You run complex ad-hoc queries, window functions, joins, and aggregations.
   – You don't want to design cubes or DAX, you just want fast SQL.
   – Avoid vendor lock by using fully open source software.  
MonetDB is best for:
   – Data engineers
   – BI developers
   – Researchers
   – Small/medium businesses
   – Python users

MonetDB supports SQL, ODBC, JDBC and many programming languages ( python, java, R, ruby, PHP… ). It can be easily integrated with different software, but the support of 3rd party software, clients and ORMs is limited. This is the consequence of the MonetDB origin which was research and science oriented. MonetDB was developed on the CWI institute in the Netherland. Development was driven by innovation and curiosity, and not by commercialization and marketing. This is why you can say that MonetDB is the fastest database you've never heard of. But that development lasted for 30 years and today MonetDB is complete and powerful database system.

MonetDB Features

 Here, I will list features of the MonetDB server, and I will direct you toward blog posts about specific feature.

1) Blog posts 0010, 0020 and 0030 will teach you how to install MonetDB, how to create a database, and how to fill database with a sample data. On the other side, installation of MonetDB through docker is explained in the last blog post 0600.

2) MonetDB can be augmented by using python language. There are different ways how that can be achieved. Blog post 0040 will explain how to connect to MonetDB from python.

Blog post 0360 will teach us how to use python to fetch data from different sources into MonetDB.Beside using python to fetch data, we can use python to create custom functions in MonetDB. That is explained in the blog post 0430.We can create inline or aggregated Python UDFs.
 

3) Blog post 0050 is about identifiers and constants. MonetDB supports different data types.

Strings0060Time0060, 0070JSON0090URL ( https://www.google.com )0100
Numbers0060Autonumber0080UUID ( universally unique identifier )0090Network ( IP addresses )0100

4) How to create and alter a table, and set table and column constraints is explained in blog posts 0110 and 0320.

CREATE TABLECREATE TABLE AS SELECTALTER TABLEConstraints: PK,FK,Unique,NULL,read only,DEFAULTCHECK constraint is explained in 0520

MonetDB also supports some special kinds of tables.
   – Temporary tables are tables with limited lifetime. They are described in 0370.
   – If we have several small tables with the same structure, we can connect them into one big virtual table ( partitioning ). This is covered in 0380.
   – Unlogged tables are special tables that can be used for fast writes, updates and deletes. We can read about them in 0390.
   – Views are explained in 0300.
   – MERGE and REMOTE tables are special tables that are used for sharding in MonetDB. Sharding is a way to distribute MonetDB work on a cluster of    computers. We can read about them in 0480.

5) SELECT, WHERE, HAVING, LIMIT;OFFSET, GROUP BY, ORDER BY, are described in 0120, 0150.

JOINS0130UNION, INTERSECT, EXCEPT0140INSERT, INSERT INTO, UPDATE, DELETE0150Subqueries0160

6) Article 0170 will teach as about ANALYZE, SAMPLE and PREPARE.
   – ANALYZE is used to update MonetDB statistics. That statistic is used by MonetDB to optimize queries.
   – SAMPLE is used to create a sample of rows from some table.
   – PREPARE is a way to prefabricate our statement so that when we execute it, it is running faster.

7) MERGE statement, CTE and GROUPING SETS can be considered as composite SQL statements, that do several things at once.

MERGE is used to partially synchronize two tables.0180CTE is a construction that will break long SQL statements into many smaller ones. Recursive CTEs are supported 0510.0190GROUPING SETS will help us to hierarchically group our data.0490

8) In SQL, running totals and moving averages are calculated by using WINDOW functions. Theory and syntax of window functions are presented in 0200, 0220. Window function can be divided into Aggregate 0230, Ranking 0240 and Offset 0250 window functions.

9) MonetDB is rich with built-in functions. They can be divided into Aggregate 0210, Mathematical 0260,  String 0270, Comparison 0280, functions. Time functions are explained in 0070.

10) Transactions are explained in 0290, Indexes in 0300, Schemas in 0310,

Transactions are a way to protect consistency and integrity of our data.Indexes are usually made by MonetDB automatically. Still, we can create some special types of indexes by our selves.Schemas are logical parts of our database.

11) Blog posts 0330, 0340, 0350 are about importing and exporting data to/from MonetDB. We can import/export data to/from CSV files or a binary format. It is also possible to load data into MonetDB from different programming languages ( we have covered python and SQL ).

12) Procedural SQL is a way to introduce procedural paradigm into SQL. Procedural paradigm is when we have to explain to database what to do instead of just describing our demands with SQL query. With procedural SQL we can make:

   – Custom functions ( 0400, 0410, 0420 ).
   – Procedures ( 0440 ). Procedures are sets of statements that are executed together.
   – Triggers ( 0450 ). Triggers are procedures that run automatically after some event.

CREATE FUNCTIONCREATE PROCEDURECREATE TRIGGERRETURNDECLARE TABLEDECLARE VARIABLECASEWHILEIF

13) Creating users and setting their rights is explained in blog posts 0460, 0470.

CREATE USERALTER USERGRANTREVOKECREATE ROLESET ROLE

14) Articles 0500, 0510 will teach us how to create ODBC and JDBC connections to MonetDB. We will also learn about file_loader and proto_loader functions. With the file_loader and proto_loader functions, we can treat CSV files and tables in other ODBC databases as if they were local MonetDB tables. Article 0530 will show us how to encrypt connection with MonetDB using TLS encryption.

15) Every database need backup. That is explained in 0540 and 0550.

16) For administration we have to learn three console applications:

   – Monetdbd ( 0560 ) is a linux daemon. This is the main application used to start and control MonetDB.
   – Monetdb ( 0570 ) is console application used to work with specific database.
   – Mclient ( 0580 ) is client application that we can use to send queries to MonetDB.

17) Different system and session procedures and commands will help us to monitor and control user sessions and queries. They are explained in 0590.