NML Says

Data Security 2 - Encryption - TLS

References for this Part

Jean-Philippe Aumasson. Serious Cryptography. No Starch Press, 2018. Chapters 2-5, 13.

RFC4880

The GNU Privacy Handbook

Short Video on GNUPG

(https://cryptojs.gitbook.io/docs/)

(https://www.thesslstore.com/blog/difference-encryption-hashing-salting/)

(https://www.ssl2buy.com/wiki/ssl-tls-handshake-how-does-it-work)

(https://developer.mozilla.org/en-US/docs/Web/Security/Transport_Layer_Security)

Transport Layer Security, TLS 1.2 and 1.3 (Explained by Example) – YouTube

Model Solutions Previous Lesson

The required functions are written in a library file (JS):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'use strict';

module.exports = {
        alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',

        caesarE: function (key, inputtext) {
                let outputtext = '';
                inputtext = inputtext.toUpperCase();

                for (let char of inputtext) {
                        if (this.alphabet.indexOf(char) === -1) { 
                                outputtext += char; 
                                continue;
                        }

                        let i = this.alphabet.indexOf(char);
                        i += key + this.alphabet.length; 
                        i %= this.alphabet.length;
                        outputtext += this.alphabet[i];
                }
                return outputtext;
        },

        caesarD: function(key, inputtext) {
                return this.caesarE(-key, inputtext);
        },

        vigeE: function (key, inputtext) {
                let outputtext = '';
                inputtext = inputtext.toUpperCase();

                for (let i = 0, ki = 0;  i < inputtext.length; i++) {
                        let char = inputtext[i];
                        if (!this.alphabet.includes(char)) { 
                                outputtext += char; 
                                continue;
                        }
                        let keychar = key[ki++ % key.length];
                        let j = this.alphabet.indexOf(char);
                        j += this.alphabet.indexOf(keychar)
                        j %= this.alphabet.length;
                        outputtext += this.alphabet[j];
                }
                return outputtext;
        },

        vigeD: function (key, inputtext) {
                let outputtext = '';
                inputtext = inputtext.toUpperCase();

                for (let i = 0, ki = 0;  i < inputtext.length; i++) {
                        let char = inputtext[i];
                        if (!this.alphabet.includes(char)) { 
                                outputtext += char; 
                                continue;
                        }
                        let keychar = key[ki++ % key.length];
                        let j = this.alphabet.indexOf(char);
                        j -= this.alphabet.indexOf(keychar);
                        j += this.alphabet.length;
                        j %= this.alphabet.length;
                        outputtext += this.alphabet[j];
                }
                return outputtext;
        }
}

and the testing program:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
'use strict';

var lib = require('./jslib.js');

let c, k, p, s;

k = 3;
p = 'abc';
console.log(p);
c = lib.caesarE(k, p);
console.log(c);
p = lib.caesarD(k, c);
console.log(p);

p = 'blåbærgrød er ikke kød og pålæg';
console.log(p);
c = lib.caesarE(k, p);
console.log(c);
p = lib.caesarD(k, c);
console.log(p);

// improv: blank into the alphabet would eliminate spaces in output

// make alphabet length -1 loop to test all possible keys
c = 'Olq tlk kpn, tpa uhcu ly huklyz vn qln rhu nvka spkl rhmml. Qln nåy aps mvkivsk ocly apyzkhn hmalu vn qln ufkly kla.';
console.log(c);

for (let i = 1; i < lib.alphabet.length; i++) {
        p = lib.caesarD(i, c);
        console.log(`key = ${i}:  ${p}`);
}

p = 'crypto';
k = 'DUH';
c = lib.vigeE(k, p);
console.log(c);

p = 'They drink the tea';
k = 'DUH';
console.log(p);
c = lib.vigeE(k, p);
console.log(c);
p = lib.vigeD(k, c);
console.log(p);

Encryption

The are four cornerstones of modern data security, they are:

Confidentiality
When or if we need to restict knowledge of certain data to a limited target group, the technology must make it possible.
Authenticity
We must be able to ascertain that the source of data is who they claim to be, and the source must be able to trust that the recipients who can read the data, are indeed entitled to that.
Integrity
The software involved must be able to substantiate that data has not been interfered with while in transit from the source to the intended target.
Non Repudiation
The source of the data must not be able to deny being the source.

Intro, Getting Started

Modern cryptography is based on discoveries made in the late 60’s and 70’s. These principles have been implemented into software that has not changed substantially since then. The algorithms are well know by now, and on principle they must be. The element that makes ciphers har to crack are the keys involved. The longer the safer. The idea is that if it takes so long to crack the code, so to speak, that the result is no longer relevant, we have won.

In latter years there has been discussions about the effects of the upcoming quantom computing on the cryptographical security. There are indications that we might eventually have to think again, but hard facts remain to be seen. On that background let us dive in.

The basis of this walk through is an implementation of the principles called GnuPG, standing on the shoulders of Phil Zimmermann’s PGP, Pretty Good Privacy.

Generate Keypair

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$ gpg --gen-key
gpg (GnuPG) 2.4.5; Copyright (C) 2024 g10 Code GmbH
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

gpg: directory '/home/nml/.gnupg' created
Note: Use "gpg --full-generate-key" for a full featured key generation dialog.

GnuPG skal konstruere et bruger-id for at identificere din nøgle.

Fødselsnavn: Niels Muller Larsen
E-post-adresse: arosano@protonmail.com
Du valgte denne BRUGER-ID:
    "Niels Muller Larsen <arosano@protonmail.com>"

Change (N)ame, (E)mail, or (O)kay/(Q)uit? O
Vi skal oprette en masse tilfældige byte. Det er en god ide at udføre
nogle andre handlinger (tryk på tastaturet, flyt musen, brug diskene)
under oprettelse af primtallet; dette giver det vilkårlig
taloprettelsesprogram en bedre mulighed for at opnå nok entropi.
Vi skal oprette en masse tilfældige byte. Det er en god ide at udføre
nogle andre handlinger (tryk på tastaturet, flyt musen, brug diskene)
under oprettelse af primtallet; dette giver det vilkårlig
taloprettelsesprogram en bedre mulighed for at opnå nok entropi.
gpg: /home/nml/.gnupg/trustdb.gpg: trustdb oprettet
gpg: directory '/home/nml/.gnupg/openpgp-revocs.d' created
gpg: revocation certificate stored as '/home/nml/.gnupg/openpgp-revocs.d/A5631066A9C81E06EC70921BC376C92824ACFB59.rev'
offentlig og hemmelig nøgle oprettet og underskrevet.

pub   ed25519 2025-01-26 [SC] [udløber: 2028-01-26]
      A5631066A9C81E06EC70921BC376C92824ACFB59
uid                      Niels Muller Larsen <arosano@protonmail.com>
sub   cv25519 2025-01-26 [E] [udløber: 2028-01-26]

The result of the above is a directory in your home directory

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
$ tree .gnupg
.gnupg
|-- S.gpg-agent
|-- S.gpg-agent.browser
|-- S.gpg-agent.extra
|-- S.gpg-agent.ssh
|-- S.keyboxd
|-- common.conf
|-- openpgp-revocs.d
|   `-- A5631066A9C81E06EC70921BC376C92824ACFB59.rev
|-- private-keys-v1.d
|   |-- 188CF32C987AE6CA915843D38666998BDE38AABB.key
|   `-- D103C06882F6A95C7D4E872710C6D5D1534118B0.key
|-- public-keys.d
|   |-- pubring.db
|   `-- pubring.db.lock
`-- trustdb.gpg

3 directories, 12 files

Exchange Keys - Exporting a Public Key

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
$ gpg --output public_key.asc --export --armor  arosano@protonmail.com
$ cat public_key.asc
-----BEGIN PGP PUBLIC KEY BLOCK-----

mDMEZ5ZLuxYJKwYBBAHaRw8BAQdAxshgXzjasIg+B/hoOXFdUKuMTJKiff7+1FSf
nmK3JGq0LE5pZWxzIE11bGxlciBMYXJzZW4gPGFyb3Nhbm9AcHJvdG9ubWFpbC5j
b20+iJkEExYKAEEWIQSlYxBmqcgeBuxwkhvDdskoJKz7WQUCZ5ZLuwIbAwUJBaOa
gAULCQgHAgIiAgYVCgkICwIEFgIDAQIeBwIXgAAKCRDDdskoJKz7WbtJAQCcdxqa
3yv0RWcRRHjtLoybD+RuvlewKVKr2aofcCxIWwD9EnR1VcZhL/mnFh11rZnyEtkm
lOa0lXvl9Bi5NxxMTAK4OARnlku7EgorBgEEAZdVAQUBAQdAJq8rjyaiO/QgjSeh
sgY1jXyq+Ts8nls7CM77ow+OrxwDAQgHiH4EGBYKACYWIQSlYxBmqcgeBuxwkhvD
dskoJKz7WQUCZ5ZLuwIbDAUJBaOagAAKCRDDdskoJKz7Wft7AP9GMPu/fz3ts5kl
ICnWRlOtL/HszPDSScq1B4y2Q6MZCAEA4yaFFtfGvMODCYHfBvQYYxn3vp0WFVVi
njG+mLKR6gQ=
=sT25
-----END PGP PUBLIC KEY BLOCK-----

Exchange Keys - Importing a Public Key

1
2
3
4
$ gpg --import ./public_html/x15.dk/downloads/keynml.asc
gpg: nøgle 6E253ADBD4DB4A5E: offentlig nøgle »Niels Muller Larsen <nml@acm.org>« importeret
gpg:  Totalt antal behandl.: 1
gpg:            importerede: 1

The prerequisite is, of course, that someone mailed you their public key.

After importing a key, you should confirm it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$ gpg --edit-key nml@acm.org
gpg (GnuPG) 2.4.5; Copyright (C) 2024 g10 Code GmbH
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.


pub  dsa1024/6E253ADBD4DB4A5E
     oprettet: 2002-06-20  udløber: aldrig      brug: SCA 
     troværdighed: ukendt        validitet: ukendt
sub  elg1024/8816EBC07E735829
     oprettet: 2002-06-20  udløber: aldrig      brug: ER  
[  ukendt] (1). Niels Muller Larsen <nml@acm.org>

gpg> fpr
pub   dsa1024/6E253ADBD4DB4A5E 2002-06-20 Niels Muller Larsen <nml@acm.org>
Primær nøglefingeraftryk: CD95 2D91 2BCD F1AC 8BB8  311A 6E25 3ADB D4DB 4A5E

gpg> sign

pub  dsa1024/6E253ADBD4DB4A5E
     oprettet: 2002-06-20  udløber: aldrig      brug: SCA 
     troværdighed: ukendt        validitet: ukendt
Primær nøglefingeraftryk: CD95 2D91 2BCD F1AC 8BB8  311A 6E25 3ADB D4DB 4A5E

     Niels Muller Larsen <nml@acm.org>

Er du sikker på, at du ønsker at underskrive denne nøgle
med din nøgle »Niels Muller Larsen <arosano@protonmail.com>« (C376C92824ACFB59)

Underskriv? (j/N) j

gpg> quit
Gem ændringer? (j/N) j

Encrypt Document

You encrypt with the recipients public key:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$ echo "lad os møde i kantinen kl 10:55" > tmp/message_to_friend.txt
~ $ gpg --encrypt --recipient nml@acm.org --output tmp/mtf.gpg tmp/message_to_friend.txt 
~ $ cat tmp/message_to_friend.txt
lad os møde i kantinen kl 10:55
~ $ cat tmp/mtf.gpg
����~sX)��b�´G����ЗxL�
                      Ä��vu�����kZº%
                                    hR��+A���o/ k��2{�T�)��z�Is���Tau'{����񓺦�G�N�T�����3������mK�
   ����A¥g:j�(h��:����OK�   �籗��q����        $²%V�m
Fd�n®]d�/���U                         ��56��Q?
�([Š����       �WU�˺�9���ҥ1B�,¶E±w��,��j«_W�K���F��Mg|��

Decrypt Document

Upon receiving encrypted messages you decrypt with

1
$ gpg --decrypt tester.txt.gpg

which wil decrypt directly to the terminal screen. If you want to save the received message after decryption, you do:

1
$ gpg --output tester.plain.txt --decrypt tester.txt.gpg

Making and Verifying Signatures

Signing a document is done with the signer’s private key:

1
$ gpg --output message_to_friend.txt.signed --sign message_to_friend.txt

The output document is now signed, ie encrypted with the owners private key. The owners public key, which is obtainable by anyone is now the only key in the world that can make plaintext out of the signed document.

The recipient may verify:

1
2
3
4
$ gpg --verify message_to_friend.txt.signed
gpg: Underskrift lavet Sun Jan 26 16:57:04 2025 CET
gpg:                bruger EDDSA nøgle A5631066A9C81E06EC70921BC376C92824ACFB59
gpg: God underskrift fra »Niels Muller Larsen <arosano@protonmail.com>« [ultimativ]

or, if you want to read the message, you must decrypt it too:

1
2
3
4
5
6
7
8
$ gpg --output message_to_friend.verified.decrypted --decrypt  message_to_friend.txt.s>
File 'message_to_friend.verified.decrypted' exists. Overskriv? (j/N) n
gpg: Underskrift lavet Sun Jan 26 16:57:04 2025 CET
gpg:                bruger EDDSA nøgle A5631066A9C81E06EC70921BC376C92824ACFB59
gpg: God underskrift fra »Niels Muller Larsen <arosano@protonmail.com>« [ultimativ]
$ cat  message_to_friend.verified.decrypted                                            
lad os møde i kantinen kl 10:55
$

Assymmetric Encryption ctr Signing

To highlight the differences between encryption and signing:

Encryption
You encrypt with recipients public key. Only one person, the intended recipient, can decrypt with his corresponding private key. This ensures confidentiality.
Signing
You sign with your own private key. Then you may send the signed document to one or to many recipients. They may all either just verify, or decrypt with your public key. This ensures authenticity, integrity, and non repudiation.

The GNU Privacy Handbook has much useful information about

TLS, Transport Layer Security

Whatis?

The webpage https://en.wikipedia.org/wiki/Transport_Layer_Security has in its description section a brief overview of what Transport Layer Security, TLS, is. Then it adds history from the SSL ancestor til today, as well as schematically showing current browser coverage.

The transport layer is a layer in the reference model describing the way the internet software is organized. The name of that model, TCP/IP, is coined by the two protocol names that makes it all possible. TCP is a transport protocol, and the TLS is active on the same layer of the protocol. It provides a service to the layer above it, where the HTTP resides.

Howto?

Easy! We don’t do a thing as developers except using the https protocol over http. This requires a certificate from a certificate vendor. The certificate, like trust for someone’s public key, enables the user to trust that your site really belongs to you.

The actual setup of a TLS communication is done via a TLS handshake that plays as follows(https://www.ssl2buy.com/wiki/ssl-tls-handshake-how-does-it-work)

  1. The user starts the handshake process by sending a “Hello” message. This message contains the TLS type and cipher suites that the user supports. It also includes a string of arbitrary bytes, called “client random.”
  2. In its reply, the server sends the text with its SSL certificate. The text also contains the cipher suite chosen for this process and a string of random bytes generated by the server referred to as “server random.”
  3. The user’s browser authenticates the SSL certificate provided by the server and the certificate authority that has issued it. This proves that the server is who it states to be, and the client is interacting with the license holder.
  4. The client sends another message (premaster secret) encoded with the SSL certificate’s public key that can only be decoded by the private key, which is held by the server.
  5. The server reads the message using its private key.
  6. After this, a session key is created using client random, server random, and the premaster secret.
  7. Both server and client send a “finished” message, encoded with the session key.
  8. The SSL handshake is completed successfully, and both parties continue communicating safely, using the session keys.

Using TLS

In order to use TLS, there is really not much developer work involved. Links to own pages need to substitute https for http in order to invoke TLS. Then it happens automatically. There is a prerequisite involved, the site must have a certificate installed. This is really not developer work, but rather the job of the site administration. I highly recommend that you take a detailed look at https://letsencrypt.org/ for details on that.

Generally you may be able to buy certificates from your hosting provider. They are not free, normally. You may have noticed, btw, that in some clouds, your hosted site will automatically be an https site.

Exercises

The rules for handing in assignments may be found in the README

Exercise DS.2.0

Download and install GnuPG from https://www.gnupg.org/download/, find the appropriate version in the section: GnuPG binary releases.

Generate a keypair for yourself, and export your public key to an asc, ASCII Armored, file. Use your regular email address when generating your keypair.

Then publish your exported public key to either:

If you get a verification email, don’t ignore it.

Exercise DS.2.1

Create a text file, and encrypt it with your own public key, use your email as recipient. Give the encrypted file the name SecE1.enc.txt. Then open the encrypted file in your favorite editor. What happens?

Then decrypt the file into a file differently name than the original file. Verify that the content has become itself again.

Finally, encrypt the original file with arosano@protonmail.com as the recipient. You may get the public key from: https://keys.openpgp.org Name the output SecE1a.enc.txt.

Both encrypted files go into the repo.

Exercise DS.2.2

Take the text of this assignment, and put it into a txt document. Then sign it with a regular digital signature, name the output SecE2.sign.txt, and put it into the repo.

Exercise DS.2.3

Create a short document, and clearsign it into SecE3.sig.txt. The document should give a possible use case for clearsign.

Exercise DS.2.4

Create a short document, and detached sign it into SecE4.det.sig.txt. The document should give a possible use case for detached signatures.