This commit is contained in:
billbuchanan
2021-01-18 20:47:18 +00:00
parent cd6a51b318
commit 44789e8d3a
521 changed files with 44505 additions and 2 deletions

135
README.md
View File

@@ -1,2 +1,133 @@
# appliedcrypto
First
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
# e-Security Module
## Outline details
Some of the associated material will be hosted on this site:
https://asecuritysite.com/esecurity
This repository contains the code and labs for the module. Open up your Ubuntu instance, and downloaded from:
<pre>
git clone https://github.com/billbuchanan/esecurity.git
</pre>
If you need to update the code, go into the esecurity folder, and run:
<pre>
git pull
</pre>
Make your own VM:
* sudo apt install python3-pip
* pip3 install pycrytodome
* pip3 install padding
* pip3 install libnum
* pip3 install passlib
The VM for the module can be downloaded [here](https://livenapierac-my.sharepoint.com/:u:/g/personal/b_buchanan_napier_ac_uk/Ed074id3TQVNneDepApeUa8B1TMsUw4P7nXtIZTDzFkkig?e=WEpvHj)
## Draft Timetable
<p>The following is the draft timetable:</p>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
<td width="5%" bgcolor="#990000" class="table1"><strong>No</strong></td>
<td width="15%" bgcolor="#990000" class="table1"><strong>Date</strong></td>
<td width="50%" bgcolor="#990000" class="table1"><strong>Subject</strong></td>
<td width="30%" bgcolor="#990000" class="table1"><strong>Lab</strong></td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>1</strong></td>
<td bgcolor="#990000" class="table1"><strong>17 Jan 2020 </strong></td>
<td>Ciphers and Fundamentals <a href="https://github.com/billbuchanan/esecurity/tree/master/unit01_cipher_fundamentals">Unit</a></td>
<td>Lab [<a href="https://github.com/billbuchanan/esecurity/blob/master/unit01_cipher_fundamentals/lab/new_lab01.pdf" target="_blank">Link</a>] Demo [<a href="https://www.youtube.com/watch?v=v6H7lHblKes" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>2</strong></td>
<td bgcolor="#990000" class="table1"><strong>24 Jan 2020 </strong></td>
<td>Symmetric Key <a href="https://github.com/billbuchanan/esecurity/tree/master/unit02_symmetric">Unit</a></td>
<td>Lab [<a href="https://github.com/billbuchanan/esecurity/blob/master/unit02_symmetric/lab/new_lab02.pdf" target="_blank">Link</a>] Demo [<a href="https://www.youtube.com/watch?v=N3UADaXmOik" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>3</strong></td>
<td bgcolor="#990000" class="table1"><strong>31 Jan 2020 </strong></td>
<td>Hashing and MAC <a href="https://github.com/billbuchanan/esecurity/tree/master/unit03_hashing">Unit</a></td>
<td>Lab [<a href="https://github.com/billbuchanan/esecurity/blob/master/unit03_hashing/lab/new_lab03.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>4</strong></td>
<td bgcolor="#990000" class="table1"><strong>7 Feb 2020 </strong></td>
<td>Asymmetric (Public) Key <a href="https://github.com/billbuchanan/esecurity/tree/master/unit04_public_key">Unit</a></td>
<td>Lab [<a href="https://asecuritysite.com/public/new_lab04.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>5</strong></td>
<td bgcolor="#990000" class="table1"><strong>14 Feb 2020 </strong></td>
<td>Key Exchange <a href="https://github.com/billbuchanan/esecurity/tree/master/unit05_key_exchange">Unit</a></td>
<td>Lab [<a href="https://github.com/billbuchanan/esecurity/tree/master/unit05_key_exchange/lab" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>6</strong></td>
<td bgcolor="#990000" class="table1"><strong>21 Feb 2020</strong></td>
<td>Guest lecture</td>
<td>Mini-project/Coursework [<a href="https://github.com/billbuchanan/esecurity/tree/master/unit05a_mini_project" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>7</strong></td>
<td bgcolor="#990000" class="table1"><strong>28 Feb 2020 </strong></td>
<td>Trust and Digital Certificates <a href="https://github.com/billbuchanan/esecurity/tree/master/unit06_trust_dig_cert">Unit</a></td>
<td>Lab [<a href="https://github.com/billbuchanan/esecurity/tree/master/unit06_trust_dig_cert/lab" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>8</strong></td>
<td bgcolor="#990000" class="table1"><strong>6 Mar 2020</strong></td>
<td>Tunnelling <a href="hhttps://github.com/billbuchanan/esecurity/tree/master/unit07_tunnelling">Unit</a></td>
<td>Lab [<a href="https://github.com/billbuchanan/esecurity/tree/master/unit07_tunnelling/lab" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>9</strong></td>
<td bgcolor="#990000" class="table1"><strong>13 Mar 2020</strong></td>
<td>Test 1 (Units 1-5) [<a href="https://github.com/billbuchanan/esecurity/tree/master/z_assessments/test01" target="_blank">Study guide</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>10</strong></td>
<td bgcolor="#990000" class="table1"><strong>20 Mar 2020 </strong></td>
<td>Blockchain <a href="https://asecuritysite.com/esecurity/unit08">Unit</a></td>
<td>Lab [<a href="https://asecuritysite.com/public/new_lab08_linux.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>11</strong></td>
<td bgcolor="#990000" class="table1"><strong>27 Mar 2020 </strong></td>
<td>Future Cryptography <a href="https://asecuritysite.com/esecurity/unit09">Unit</a></td>
<td>Lab [<a href="https://asecuritysite.com/public/new_lab09.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>12</strong></td>
<td bgcolor="#990000" class="table1"><strong>3 April 2020 </strong></td>
<td>Tokens, Authorization and Docker <a href="https://asecuritysite.com/esecurity/unit10">Unit</a></td>
<td>Lab [<a href="https://asecuritysite.com/public/unit10_tokens.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>13</strong></td>
<td bgcolor="#990000" class="table1"><strong>10 April 2020 </strong></td>
<td>Trusted Hosts <a href="https://asecuritysite.com//esecurity/unit11">Unit</a></td>
<td></td>
</tr>
<tr><td colspan="3">Easter Break</td></tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>14</strong></td>
<td bgcolor="#990000" class="table1"><strong>Week beginning 27 April 2020</strong></td>
<td colspan="2"></td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>15</strong></td>
<td bgcolor="#990000" class="table1"><strong>Week beginning 4 May 2020 (TBC)</strong></td>
<td>Coursework Hand-in [<a href="https://asecuritysite.com//esecurity/cw" target="_blank">Draft</a>]</td>
</tr>
</table>

View File

@@ -0,0 +1,133 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
# Unit 0: Introduction
## Units
The units involved in the module are:
* Ciphers and Fundamentals.
* Symmetric (Secret) Key. AES, ChaCha20.
* Hashing and MAC. MD5, SHA-1, SHA-256.
* Asymmetric (Public) Key. RSA and Elliptic Curve.
* Key Exchange. Diffie-Hellman, ECDH.
* Trust and Digital Certificates.
* Tunnelling. Tunnelling, including SSL/TLS.
* Cryptocurrencies and Blockchain. Outline of cryptocurrencies, Bitcoins, Ethereum and more.
* Future Cryptography. Outline of areas such as Homomorphic Encryption, Zero-knowledge proofs and Quantum-robust cryptography.
* Host security.
The module uses Slack as the main communication channel and which can be accessed [here](esecurity2020.slack.com). There is also a WebEx session each Monday at 6:30pm.
## Module outline
An introduction video is here:
[![](http://img.youtube.com/vi/z9DaFxDuxxA/0.jpg)](http://www.youtube.com/watch?v=z9DaFxDuxxA "")
We will be using a Ubuntu machine for the practical elements of the module. The VM can either be sourced on vSoC or can be downloaded from [here](https://livenapierac-my.sharepoint.com/:u:/g/personal/b_buchanan_napier_ac_uk/Ed074id3TQVNneDepApeUa8B1TMsUw4P7nXtIZTDzFkkig?e=yyElRx). You can download VMWare Workstation or VMWare Fusion from [here](https://softcentre.soc.napier.ac.uk/users.cgi). A demo of using the VM is here:
[![](http://img.youtube.com/vi/tIQYpjaELcA/0.jpg)](http://www.youtube.com/watch?v=tIQYpjaELcA "")
## Draft Timetable
<p>The following is the draft timetable:</p>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
<td width="5%" bgcolor="#990000" class="table1"><strong>No</strong></td>
<td width="15%" bgcolor="#990000" class="table1"><strong>Date</strong></td>
<td width="50%" bgcolor="#990000" class="table1"><strong>Subject</strong></td>
<td width="30%" bgcolor="#990000" class="table1"><strong>Lab</strong></td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>1</strong></td>
<td bgcolor="#990000" class="table1"><strong>17 Jan 2020 </strong></td>
<td>Ciphers and Fundamentals <a href="https://github.com/billbuchanan/esecurity/tree/master/unit01_cipher_fundamentals">Unit</a></td>
<td>Lab [<a href="https://github.com/billbuchanan/esecurity/blob/master/unit01_cipher_fundamentals/lab/new_lab01.pdf" target="_blank">Link</a>] Demo [<a href="https://www.youtube.com/watch?v=v6H7lHblKes" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>2</strong></td>
<td bgcolor="#990000" class="table1"><strong>24 Jan 2020 </strong></td>
<td>Symmetric Key <a href="https://github.com/billbuchanan/esecurity/tree/master/unit02_symmetric">Unit</a></td>
<td>Lab [<a href="https://github.com/billbuchanan/esecurity/blob/master/unit02_symmetric/lab/new_lab02.pdf" target="_blank">Link</a>] Demo [<a href="https://www.youtube.com/watch?v=N3UADaXmOik" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>3</strong></td>
<td bgcolor="#990000" class="table1"><strong>31 Jan 2020 </strong></td>
<td>Hashing and MAC <a href="https://github.com/billbuchanan/esecurity/tree/master/unit03_hashing">Unit</a></td>
<td>Lab [<a href="https://github.com/billbuchanan/esecurity/blob/master/unit03_hashing/lab/new_lab03.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>4</strong></td>
<td bgcolor="#990000" class="table1"><strong>7 Feb 2020 </strong></td>
<td>Asymmetric (Public) Key <a href="https://github.com/billbuchanan/esecurity/tree/master/unit04_public_key">Unit</a></td>
<td>Lab [<a href="https://asecuritysite.com/public/new_lab04.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>5</strong></td>
<td bgcolor="#990000" class="table1"><strong>14 Feb 2020 </strong></td>
<td>Key Exchange <a href="https://asecuritysite.com/esecurity/unit05">Unit</a></td>
<td>Lab [<a href="https://asecuritysite.com/public/new_lab05.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>6</strong></td>
<td bgcolor="#990000" class="table1"><strong>21 Feb 2020</strong></td>
<td>Guest lecture</td>
<td>Mini-project/Coursework [<a href="https://asecuritysite.com/public/lab_mini_project.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>7</strong></td>
<td bgcolor="#990000" class="table1"><strong>28 Feb 2020 </strong></td>
<td>Trust and Digital Certificates <a href="https://asecuritysite.com/esecurity/unit06">Unit</a></td>
<td>Lab [<a href="https://asecuritysite.com/public/new_lab06.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>8</strong></td>
<td bgcolor="#990000" class="table1"><strong>6 Mar 2020</strong></td>
<td>Tunnelling <a href="https://asecuritysite.com/esecurity/unit07">Unit</a></td>
<td>Lab [<a href="https://asecuritysite.com//public/new_lab07.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>9</strong></td>
<td bgcolor="#990000" class="table1"><strong>13 Mar 2020</strong></td>
<td>Test 1 (Units 1-5) [<a href="https://asecuritysite.com/esecurity/guide" target="_blank">Study guide</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>10</strong></td>
<td bgcolor="#990000" class="table1"><strong>20 Mar 2020 </strong></td>
<td>Blockchain <a href="https://asecuritysite.com/esecurity/unit08">Unit</a></td>
<td>Lab [<a href="https://asecuritysite.com/public/new_lab08_linux.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>11</strong></td>
<td bgcolor="#990000" class="table1"><strong>27 Mar 2020 </strong></td>
<td>Future Cryptography <a href="https://asecuritysite.com/esecurity/unit09">Unit</a></td>
<td>Lab [<a href="https://asecuritysite.com/public/new_lab09.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>12</strong></td>
<td bgcolor="#990000" class="table1"><strong>3 April 2020 </strong></td>
<td>Tokens, Authorization and Docker <a href="https://asecuritysite.com/esecurity/unit10">Unit</a></td>
<td>Lab [<a href="https://asecuritysite.com/public/unit10_tokens.pdf" target="_blank">Link</a>]</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>13</strong></td>
<td bgcolor="#990000" class="table1"><strong>10 April 2020 </strong></td>
<td>Trusted Hosts <a href="https://asecuritysite.com//esecurity/unit11">Unit</a></td>
<td></td>
</tr>
<tr><td colspan="3">Easter Break</td></tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>14</strong></td>
<td bgcolor="#990000" class="table1"><strong>Week beginning 27 April 2020 (TBC)</strong></td>
<td colspan="2">Test 2 (Units 6-10)</td>
</tr>
<tr>
<td bgcolor="#990000" class="table1"><strong>15</strong></td>
<td bgcolor="#990000" class="table1"><strong>Week beginning 4 May 2020 (TBC)</strong></td>
<td>Coursework Hand-in [<a href="https//asecuritysite.com//esecurity/cw" target="_blank">Draft</a>]</td>
</tr>
</table>
Any questions, contact us on Slack?

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,105 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
# Unit 1: Cipher Fundamentals
The key concepts are:
* Ciphers.
* Encoding methods (ASCII, UTF-16, Base64, Hex).
* Prime Numbers.
* GCD.
* Large numbers.
* Random Number Generators.
* Data Integrity (CRC-32).
* Frequency Analysis.
* Key-based encryption.
* Key sizes.
## What you should know at the end of unit?
* **Understand the conversion of characters between hex, decimal and octal**. Sample question: Convert "hello" into a hex stream. Related material: [here](https://asecuritysite.com/Coding/ascii).
* *Why are we studying this?* Encrypted content is converted into a range of different formats, so we need to understand the process of taking plain text and then converting it into other encoding formats. Encryption keys, ciphertext and digital certificates are examples of binary content which must be represented in a text format.
* **Compute the GCD for values**. Sample question: What is the GCD for 42 and 56? Related material: [here](https://asecuritysite.com/encryption/gcd).
* *Why are we studying this?* GCD is a fundamental building block used in public key encryption, where we must find two numbers who do not share a common divisor. When we look at public key encryption we will see how GCD is used.
* **Compute the MOD for values**. Sample question: What is the result of 13 MOD 7?
* *Why are we studying this?* Within many of the public key methods we use the MOD operator with a prime number, and where it is difficult to find the value of x for Y=g<sup>x</sup>(mod p), even though we know Y, g and p.
* **Understand how to manually convert from ASCII to Base-64, and vice-versa**. Sample question: What is the Base-64 conversion of “hello”? [here](https://asecuritysite.com/Coding/ascii).
* *Why are we studying this?* Base-64 is used extensively in encryption, and many of the keys and cipher text are transported and stored in a Base-64 format.
* **Calculate the time taken to crack a code given a time to try each key, and for the number of processing elements**. Sample question: If it takes 100 years to crack a cipher code, and computing power doubles each year. How long will it take to crack a code after five years?
* *Why are we studying this?* We always need to understand the strengths of your encrypted data, especially in the face of GPU based crackers, so we need to understand how quickly it will take to crack our cipher.
## Presentations
* Week 1 Presentation (PDF): [here](https://github.com/billbuchanan/esecurity/tree/master/unit01_cipher_fundamentals/lecture)
* Week 1 Presentation (video): [here](https://www.youtube.com/watch?v=zqmjUpJNcJA)
* Week 1 Class Lecture (video): [here](https://youtu.be/3hkRjzl8B8w)
## Lab
* Week 1 Lab (PDF): [here](https://github.com/billbuchanan/esecurity/tree/master/unit01_cipher_fundamentals/lab) [demo](https://www.youtube.com/watch?v=v6H7lHblKes)
## Sample exam questions
1. Using the table [here](https://asecuritysite.com/public/test_table.pdf), what is the Base-64 encoding for "test"?
1. Using the table [here](https://asecuritysite.com/public/test_table.pdf), is the Base-64 encoding for "help"?
1. If it takes 1ns to test an encryption key. How long will it take to crack a 32-bit key?
1. If it takes 10ns to test an encryption key. How long will it take to crack a 20-bit key?
1. Bob tells Alice that she won't be able to view the cipher text, but when she looks at the messages, they seem to be full of printable characters. What format is Bob likely to be using for the encoding of the cipher text, and what would you ask Alice to look for, in order to confirm your guess?
1. Alice has been reading her crypto books, and she reads that there should be an '=' symbol at the end of the encoding. She observes her encoding of cipher messages to Bob, and sees that some do not have an '=' sign at the end. Is there a problem with her encoder? If not, how often, on average, should she see an '=' sign at the end of her ciphered messages?
1. Bob has two numbers which give a GCD of 1. Trent says that this happens because the numbers are prime. Is Trent correct? Explain your answer.
1. Bob deals in Bitcoins and tells Alice that he has a Base-58 ID? Alice says he is crazy, and has only heard of Base-64. What is Base-58 and how does it differ from Base-64?
1. Bob encrypted a message in 1980, and it took a million years to crack at the time. Assuming that computing power doubles each year, do you think the message will be safe against cracking for existing computer systems?
## Tests
* Take fun cipher code challenge: [here](https://asecuritysite.com/challenges/hex). Go see what score you can achieved. If you can get more than 30, you are doing every well. Something over 90 enters a genius level.
* Five minute challenge: [here](https://asecuritysite.com/challenges/scramb). See if you can solve a scrambled alphabet cipher in just five minutes.
* Test 1 (Caesar): [here](https://asecuritysite.com/tests/tests?sortBy=caesar)
* Test 2 (Hex): [here](https://asecuritysite.com/tests/tests?sortBy=hex01)
Note: There will be no cipher challenges in the assessments, and these tests are just a bit of fun, and for background.
## Answers
Q1
<pre>
test -> 01110100 01100101 01110011 01110100
test -> 011101 000110 010101 110011 011101 00
test -> d G V z d A ==
</pre>
Q2
<pre>
help -> 01101000 01100101 01101100 01110000
help -> 011101 000110 010101 110011 011101 00
help -> a G V s c A ==
</pre>
Q3
<pre>
Max time to crack = 1e-9 x 2^32
Max time to crack = 4.3 seconds
</pre>
Q4
<pre>
Max time to crack = 10e-9 x 2^20
Max time to crack = 0.01 seconds
</pre>
Q8: Have a look [here](https://asecuritysite.com/encryption/base58)

View File

@@ -0,0 +1,392 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
# Lab 1: Cipher Fundamentals
Objective: The key objective of this lab is to be introduced to some of the fundamental principles involved in cryptography, including the usage of Base-64, hexadecimal, the modulus operator some basic operators (such as AND, OR, X-OR, Rotate Right and Rotate Left), and prime numbers. This lab also involves cracking puzzles, and which have been added to get you to think about the methods involved in cipher cracking. You can undertake the additional challenges if you want to further develop your cryptography skills.
Go to **vsoc.napier.ac.uk** and find your folder. Run your Ubuntu instance [demo](https://youtu.be/v6H7lHblKes). Lab demo: (Note that you will be using Ubuntu, while the demo shows Kali). A demo of the lab is [here](https://www.youtube.com/watch?v=v6H7lHblKes).
## Introduction
Note: Some of the code in this example uses Python 2.7. If you are using Python 3, remember and put parenthesis around the print statement string, such as print (hex(val)).
### A.1 Is prime?
Using: http://asecuritysite.com/Encryption/testprime
Test for the following prime numbers:
91: [Yes] [No]
421: [Yes] [No]
1449: [Yes] [No]
### A.2 gcd
Using: http://asecuritysite.com/Encryption/gcd
Determine the GCD for the following:
88, 46:
105, 35:
### A.3 Base-64 convertor
Using: http://asecuritysite.com/coding/ascii
Determine the Base 64 and Hex values for the following strings:
Hello:
hello:
HELLO:
### A.4 Base-64 convertor
Using: http://asecuritysite.com/coding/ascii
Determine the following ASCII strings for these encoded formats:
<pre>
bGxveWRz
6E6170696572
01000001 01101110 01101011 01101100 01100101 00110001 00110010 00110011
</pre>
### A.5 The mod operatpor
Using Python, what is the result of 53,431 (mod 453)?
In Python, this is:
```python
print (53431 % 453)
```
### A.6 Bitwise operations
Using Python, what is the results of the following:
```python
print (0x43 | 0x21)
print (0x43 & 0x21)
print (0x43 ^ 0x21)
```
In this case, "|" does a bitwise OR, "&" does a bitwise AND, and "^" does a bitwise X-OR. Using a pen and paper, prove that these results are correct. Results:
### A.7 Hex, Oct, Char and Binary
Using Python, what is the hex, octal, character, and binary equivalents of the value of 93:
```python
val1=93
print ("Dec:\t",val1)
print ("Bin:\t",bin(val1))
print ("Hex:\t",hex(val1))
print ("Oct:\t",oct(val1))
print ("Char:\t",chr(val1))
```
Results:
### A.8 Node.js
JavaScript is often used in cryptography. Using node.js, repeat A.7.
```node
val=93
console.log(val.toString(2))
console.log(val.toString(16))
console.log(val.toString(8))
console.log(String.fromCharCode(val))
```
This program will use node.js. Create a file named a_08.js and then run with:
<pre>
node a_08.js
</pre>
Results:
### A.9 Base64
Using Python, what is the Base-64 conversion for the string of “crypto”?
```python
import base64
str="crypto"
print (base64.b64encode(str))
```
Result:
### A.10 Base64
If we use a string of "crypto1", what do you observe from the Base64 conversion compared to the result in the previous question (A.9)?
Observation:
### A.11 Bit shift
Using Python, using a decimal value of 41, determine the result of a shift left by one bit, a shift left by two bits, a right shift by one bit, and a right shift by two bits:
Web link (Bit shift): https://asecuritysite.com/comms/shift
Decimal form: 41
Shift left (1):
Shift left (2):
Shift right(1):
Shift right(2):
Why would a shift left or shift right operator not be used on its own in cryptography?
### A.12 Factors
In several cases in cryptography, we try and factorize a value into its factors. An example is 15, and which has factors of 5 and 3. Using the Python program defined in the following link, determine the factors of 432:
Web link (Factorization): https://asecuritysite.com/encryption/factors
Think of two extremely large values and determine their factors.
### A.13 Compression
Another format we can use for our data is compression, and we can do the compression before or after the encryption process. One of the most popular methods is gzip compress, and which uses the LZ method to reduce the number of bits used. For this we will use node.js. Create a file named a_13.js and determine what the following Base64 conversions are when they are uncompressed (Hint: they are cities of the World):
Web link (Compression): https://asecuritysite.com/encryption/gzip
Take a string of “abc” and compress it, and now keep building up the string with the same sequence (such as “abcabc…”). What do you observe from the length of the compression string if you use a random characters of the same length as an input:
<pre>
eJzzyc9Lyc8DAAgpAms=
eJxzSi3KycwDAAfXAl0=
eJzzSy1XiMwvygYADKUC8A==
</pre>
## B GCD
GCD is known as the greatest common divisor, or greatest common factor (gcf), and is the largest positive integer that divides into two numbers without a remain-der. For example, the GCD of 9 and 15 is 3. It is used many encryption algorithms, and a sample algorithm to determine the GCD of two values (a and b) is given on:
Web link (GCD): http://asecuritysite.com/encryption/gcd
### B.1 Write a Python program to determine the GCD for the following:
4105 and 10:
4539 and 6:
### B.2 Two numbers are co-prime if they do not share co-factors, apart from 1, which is gcd(a,b)=1.
Determine if the following values are co-prime:
5435 and 634: Yes/No
## C Modulus and Exponentiation
The mod operator results in the remainder of an integer divide. For example, 31 divided by 8 is 3 remainder 7, thus 31 mod 8 equals 7. Often in cryptography the mod operation uses a prime number, such as:
Result = value<sup>x</sup> mod (prime number)
For example, if we have a prime number of 269, and a value of 8 with an x value of 5, the result of this operation will be:
Result = 85 mod 269 = 219
With prime numbers, if we know the result, it is difficult to find the value of x even though we have the other values, as many values of x can produce the same result. It is this feature which makes it difficult to determine a secret value (in this case the secret is x).
Exponentiation ciphers use a form of:
C = M<sup>e</sup> mod p
to encrypt and decrypt a message (M) using a key of e and a prime number p.
### C.1 What is the result of the following:
8<sup>13</sup> mod 271:
12<sup>23</sup> mod 973:
### C.2 Implement a Python program which will determine the result of:
M<sup>e</sup> mod p
The program should check that p is a prime number.Is the result of 8<sup>5</sup> mod 269 equal to 219?
Yes/No
### C.3 Proving
Now prove the following:
* message = 5, e=5, p = 53. Ans: 51
* message = 4, e=11, p = 79. Ans: 36
* message = 101, e=7, p = 293. Ans: 176
An outline of the Python 2.7 code is:
```python
message = raw_input('Enter message: ')
e = raw_input('Enter exponent: ')
p = raw_input('Enter prime ')
cipher = (int(message) ** int(e)) % int(p)
print (cipher)
```
Note: In Python 3.x, we using input() instead of raw_input().
## D Simple prime number test
A prime number is a value which only has factors of 1 and itself. Prime numbers are used fairly extensively in cryptography, as computers struggle to factorize them when they are multiplied together. The simplest test for a prime number is to divide the value from all the integers from 2 to the value divided by 2. If any of the results leaves no remainder, the value is a prime, otherwise it is composite. We can obviously improve on this by getting rid of even numbers which are greater than 2, and also that the highest value to be tested is the square root of the value.
So, if n = 37, then our maximum value will be , which, when rounded down is 6. So, we can try: 2, 3, and 5, of which of none of these divide exactly into 37, so it is a prime number. Now lets try 55, we will then be 2, 3, 5 and 7. In this case 5 does divide exactly in 55, so the value is not prime.
Another improvement we can make is that prime numbers (apart from 2 and 3) fit into the equation of:
6k ± 1
where k=0 gives 0 and 1, k=1 gives 5 and 7, k=2 gives 11 and 13, k=3 gives 17 and 19, and so on. Thus we can test if we can divide by 2 and then by 3, and then check all the numbers of 6k ± 1 up to X.
Web link (Prime Numbers): http://asecuritysite.com/encryption/isprime
### D.1 Using the equation of 6k ± 1. Determine the prime numbers up to 100:
Prime numbers:
### D.2 Implement a Python program which will calculate the prime numbers up to 1000:
Define the highest prime number generated:
A prime sieve creates all the prime numbers up to a given limit. It progressively removes composite numbers until it only has prime numbers left, and it is the most efficient way to generate a range of prime numbers. The following provides a fast method to determine the prime numbers up to a give value (test):
```python
import sys
test=1000
if (len(sys.argv)>1):
test=int(sys.argv[1])
def sieve_for_primes_to(n):
size = n//2
sieve = [1]*size
limit = int(n**0.5)
for i in range(1,limit):
if sieve[i]:
val = 2*i+1
tmp = ((size-1) - i)//val
sieve[i+val::val] = [0]*tmp
return [2] + [i*2+1 for i, v in enumerate(sieve) if v and i>0]
print (sieve_for_primes_to(test))
```
### D.3 Implement the Python code given above and determine the highest prime number possible in the following ranges:
Up to 100:
Up to 1,000:
Up to 5,000:
Up to 10,000:
The Miller-Rabin Test for Primes is an efficient method in testing for a prime number. Access the following page and download the Python script.
Web link (Miller-Radin): http://asecuritysite.com/encryption/rabin
Using this determine the following:
### D.4 Prime numbers
Which of the following numbers are prime numbers:
Is 5 prime? Yes/No
Is 7919 prime? Yes/No
Is 858,599,509 prime? Yes/No
Is 982,451,653 prime? Yes/No
Is 982,451,652 prime? Yes/No
## E Random numbers
Within cryptography random numbers are used to generate things like encryption keys. If the generation of these keys could be predicted in some way, it may be possible to guess it. The two main types of random number generators are:
* Pseudo-Random Number Generators (PRNGs). Repeats after a given time. Fast. They are also deterministic and periodic, so that the random number generation will eventually repeat.
* True Random Number Generators (TRNGs). This method is a true random number such as for keystroke analysis. It is generally slow but is non-deterministic and aperiodic.
Normally simulation and modelling use PRNG, so that the values generated can be repeated each time, while cryptography, lotteries, gambling and games use TRNG, as each value which is selected at random should not repeat or be predictable. In the generation of encryption keys for public key encryption, a user is typically asked to generate some random activity with their mouse pointer. The random number is then generated on this activity.
Computer programs often struggle to generate TRNG, and hardware generators are sometimes used. One method is to generate a random number based on low-level, statistically random "noise" signals. This includes things like thermal noise, and a photoelectric effect.
Web link (Random number): http://asecuritysite.com/encryption/random
One method of creating a simple random number generator is to use a sequence generator of the form (Linear Congruential Random Numbers):
Where a, c and m are integers, and where X0 is the seed value of the series.
If we take the values of a=21, X0=35, c=31 and m=100 we get a series of:
<pre>
66 17 88 79 90 21 72 43 34 45 76 27 98 89 0 31 82 53
</pre>
Using this example, we get:
<pre>
(21×35+31) mod 100 gives 66
(21×66+31) mod 100 gives 17
(21×17+31) mod 100 gives 88
</pre>
Web link (Linear congruential): http://asecuritysite.com/encryption/linear
### E.1
Implement the Python code given above.
Using: a=21, seed=35, c=31, and m=100, prove that the sequence gives 66 17 88 79 90
Does it generate this sequence?
Yes/No
### E.2 Determine the sequence for:
a=22, seed=35, c=31, and m=100.
First four numbers of sequence?
### E.3
Determine the sequence for:
a=954,365,343, seed=436,241, c=55,119,927, and m=1,000,000.
First four numbers of sequence?
### E.4
Determine the sequence for:
a=2,175,143, seed=3553, c=10,653, and m=1,000,000.
First four numbers of sequence?
## F What I should have learnt from this lab?
The key things learnt:
* Some fundamental principles around number and character formats, including binary, hexadecimal and Base64.
* How to run a Python program and change some of the parameters.
* Some fundamentals around prime numbers and mod operations.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,183 @@
A.6
```python
print 0x43 | 0x21
print 0x43 & 0x21
print 0x43 ^ 0x21
```
A.7
```python
val1=93
print "Dec:\t",val1
print "Bin:\t",bin(val1)
print "Hex:\t",hex(val1)
print "Oct:\t",oct(val1)
print "Char:\t",chr(val1)
```
A.8
```python
val=93
console.log(val.toString(2))
console.log(val.toString(16))
console.log(val.toString(8))
console.log(String.fromCharCode(val))
```
A.9
```python
import base64
str=crypto
print base64.b64encode(val)
```
A.10
```python
import sys
val1="00110101"
if (len(sys.argv)>1):
val1=sys.argv[1]
print "Binary form: \t\t",val1
dec=int(val1,2)
print "Decimal form: \t\t",dec,"\t",bin(dec)[2:10].rjust(8,'0')
res=(dec << 1) & 0xff
print "Shift left (1):\t",res,"\t",bin(res)[2:10].rjust(8,'0')
res=(dec << 2) & 0xff
print "Shift left (2):\t",res,"\t",bin(res)[2:].rjust(8,'0')
res=(dec >> 1) & 0xff
print "Shift right (1):\t",res,"\t",bin(res)[2:10].rjust(8,'0')
res=(dec >> 2) & 0xff
print "Shift right (2):\t",res,"\t",bin(res)[2:10].rjust(8,'0')
```
B.1
```python
def gcd(a, b):
while( b != 0 ):
Remainder = a % b;
a = b;
b = Remainder;
return a;
g = gcd(54,8)
print g
```
C.3
```python
message = raw_input('Enter message: ')
e = raw_input('Enter exponent: ')
p = raw_input('Enter prime ')
cipher = (int(message) ** int(e)) % int(p)
print cipher
```
D.1
```python
import math
def get_if_prime(val):
max = math.sqrt(val);
if (val % 2 == 0):
return (False);
if (val % 3 == 0):
return (False);
for k in range(0, 10000):
testval = 6 * k + 1;
if (testval>max):
break
if (val % testval == 0):
return (False)
testval = 6 * k - 1;
if (testval>max):
break
if (val % testval == 0):
return (False)
return (true)
val=93
res = get_if_prime(val)
if (res==True):
print str(val)+" is prime"
else:
print str(val)+" is not prime"
```
D.2
```python
import sys
test=1000
if (len(sys.argv)>1):
test=int(sys.argv[1])
def sieve_for_primes_to(n):
size = n//2
sieve = [1]*size
limit = int(n**0.5)
for i in range(1,limit):
if sieve[i]:
val = 2*i+1
tmp = ((size-1) - i)//val
sieve[i+val::val] = [0]*tmp
return [2] + [i*2+1 for i, v in enumerate(sieve) if v and i>0]
print sieve_for_primes_to(test)
```
This works because we start with all the odd numbers up to the square root of the limit of the numbers we are looking for. If we have 100, then the size will be 50. We start off with odd numbers (as 2 is the only even prime):
<pre>
3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 .. 99
</pre>
In the first time round we have i equal to 1, and we will jump 3 each time and mark them as not prime:
<pre>
<b>3</b> 5 7 <s>9</s> 11 13 <s>15</s> 17 19 <s>21</s> 23 25 <s>27</s> 29 31 <s>33</s> 35 .. 97 <s>99</s>
</pre>
In the next time round, we will jump 5, starting at 5:
<pre>
3 <b>5</b> 7 X 11 13 <s>X</s> 17 19 X 23 <s>25</s> X 29 31 X <s>35</s> .. 97, X
</pre>
In the next time round, we will jump 7, starting at 7:
<pre>
3 5 <b>7</b> X 11 13 X 17 19 <s>X</s> 23 X X 29 31 X <s>X</s> .. 97 99
</pre>
In the next time round, we will jump 9, starting at 9:
<pre>
3 5 7 <b>X</b> 11 13 X 17 19 X 23 X <s>X</s> 29 31 X X .. 97 99
</pre>
In the end we stop at 19, and with a jump of 19, and add the value of 2 to the discovered prime numbers:
<pre>
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
</pre>
The marking of the factors follows this sequence:
<pre>
[1, 3, 5, 7, 9, 11,13,15,17,19,21,23,25,27,29,31,33,35 .. ]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, <b>1</b>, 1, 1, <b>0</b>, 1, 1, <b>0</b>, 1, 1, <b>0</b>, 1, 1, <b>0</b>, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0]
[1, 1, <b >1</b>, 1, 0, 1, 1, <b>0</b>, 1, 1, 0, 1, <b>0</b>, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0]
[1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0]
[1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0]
[1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0]
[1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0]
[1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0]
</pre>

View File

@@ -0,0 +1,33 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
# 1. Fundamentals
## Outline
The key concepts involved in this unit are:
The key concepts are:
* Ciphers.
* Encoding methods (ASCII, UTF-16, Base64, Hex).
* Prime Numbers.
* GCD.
* Large numbers.
* Random Number Generators.
* Data Integrity (CRC-32).
* Frequency Analysis.
* Key sizes.
## Presentations
* Week 2 Presentation (PDF) - Symmetric Key Encryption: [here](https://github.com/billbuchanan/esecurity/blob/master/unit01_cipher_fundamentals/lecture/chapter01_ciphers_fundamentals.pdf)
* Week 2 Presentation (Video) - Symmetric Key Encryption [here](https://www.youtube.com/watch?v=zqmjUpJNcJA)
* Week 2 Presentation (Lecture - Video) - Symmetric Key Encryption: [here](https://www.youtube.com/watch?v=3hkRjzl8B8w). Recorded on Friday 24 Jan 2020.
## Lectures
The voice-over lecture is here:
[![](http://img.youtube.com/vi/zqmjUpJNcJA/0.jpg)](https://www.youtube.com/watch?v=zqmjUpJNcJA "")
The classroom lecture recorded on 24 Jan 2020 is here:
[![](http://img.youtube.com/vi/3hkRjzl8B8w/0.jpg)](https://www.youtube.com/watch?v=3hkRjzl8B8w "")

View File

@@ -0,0 +1,140 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
A.6
```python
print 0x43 | 0x21
print 0x43 & 0x21
print 0x43 ^ 0x21
```
A.7
```python
val1=93
print "Dec:\t",val1
print "Bin:\t",bin(val1)
print "Hex:\t",hex(val1)
print "Oct:\t",oct(val1)
print "Char:\t",chr(val1)
```
A.8
```python
val=93
console.log(val.toString(2))
console.log(val.toString(16))
console.log(val.toString(8))
console.log(String.fromCharCode(val))
```
A.9
```python
import base64
str="crypto"
print base64.b64encode(val)
```
A.10
```python
import sys
val1="00110101"
if (len(sys.argv)>1):
val1=sys.argv[1]
print "Binary form: \t\t",val1
dec=int(val1,2)
print "Decimal form: \t\t",dec,"\t",bin(dec)[2:10].rjust(8,'0')
res=(dec << 1) & 0xff
print "Shift left (1):\t",res,"\t",bin(res)[2:10].rjust(8,'0')
res=(dec << 2) & 0xff
print "Shift left (2):\t",res,"\t",bin(res)[2:].rjust(8,'0')
res=(dec >> 1) & 0xff
print "Shift right (1):\t",res,"\t",bin(res)[2:10].rjust(8,'0')
res=(dec >> 2) & 0xff
print "Shift right (2):\t",res,"\t",bin(res)[2:10].rjust(8,'0')
```
B.1
```python
def gcd(a, b):
while( b != 0 ):
Remainder = a % b;
a = b;
b = Remainder;
return a;
g = gcd(54,8)
print g
```
C.3
```python
message = raw_input('Enter message: ')
e = raw_input('Enter exponent: ')
p = raw_input('Enter prime ')
cipher = (int(message) ** int(e)) % int(p)
print cipher
```
D.1
```python
import math
def get_if_prime(val):
max = math.sqrt(val);
if (val % 2 == 0):
return (False);
if (val % 3 == 0):
return (False);
for k in range(0, 10000):
testval = 6 * k + 1;
if (testval>max):
break
if (val % testval == 0):
return (False)
testval = 6 * k - 1;
if (testval>max):
break
if (val % testval == 0):
return (False)
return (true)
val=93
res = get_if_prime(val)
if (res==True):
print str(val)+" is prime"
else:
print str(val)+" is not prime"
```
D.2
```python
import sys
test=1000
if (len(sys.argv)>1):
test=int(sys.argv[1])
def sieve_for_primes_to(n):
size = n//2
sieve = [1]*size
limit = int(n**0.5)
for i in range(1,limit):
if sieve[i]:
val = 2*i+1
tmp = ((size-1) - i)//val
sieve[i+val::val] = [0]*tmp
return [2] + [i*2+1 for i, v in enumerate(sieve) if v and i>0]
print sieve_for_primes_to(test)
```

View File

@@ -0,0 +1,6 @@
print (0x43 | 0x21)
print (0x43 & 0x21)
print (0x43 ^ 0x21)

View File

@@ -0,0 +1,11 @@
val1=93
print ("Dec:\t",val1)
print ("Bin:\t",bin(val1))
print ("Hex:\t",hex(val1))
print ("Oct:\t",oct(val1))
print ("Char:\t",chr(val1))

View File

@@ -0,0 +1,9 @@
val=93
console.log(val.toString(2))
console.log(val.toString(16))
console.log(val.toString(8))
console.log(String.fromCharCode(val))

View File

@@ -0,0 +1,3 @@
import base64
str="crypto"
print (base64.b64encode(str))

View File

@@ -0,0 +1,26 @@
# Bit shift
# https://asecuritysite.com/comms/shift
import sys
val1="00110101"
if (len(sys.argv)>1):
val1=sys.argv[1]
print ("Binary form: \t\t",val1)
dec=int(val1,2)
print ("Decimal form: \t\t",dec,"\t",bin(dec)[2:10].rjust(8,'0'))
res=(dec << 1) & 0xff
print ("Shift left (1):\t",res,"\t",bin(res)[2:10].rjust(8,'0'))
res=(dec << 2) & 0xff
print ("Shift left (2):\t",res,"\t",bin(res)[2:].rjust(8,'0'))
res=(dec >> 1) & 0xff
print ("Shift right (1):\t",res,"\t",bin(res)[2:10].rjust(8,'0'))
res=(dec >> 2) & 0xff
print ("Shift right (2):\t",res,"\t",bin(res)[2:10].rjust(8,'0'))

View File

@@ -0,0 +1,38 @@
// Run as node a_13.js Hello zip
// Use npm install gzip
var zlib = require('zlib');
var test="hello";
var flag="zip"
var args = process.argv;
if (args.length>1) test=args[2];
if (args.length>2) flag=args[3];
console.log("Input: ",test);
if (flag=="zip") {
var input = new Buffer.from(test)
zlib.deflate(input, function(err, buf) {
var res=buf.toString('base64');
console.log("Compressed: " ,res );
// console.log("Compressed: " ,buf );
});
}
else {
var input = new Buffer.from(test,'base64')
zlib.inflate(input, function(err, buf) {
if (buf==undefined) console.log("Incorrect format in processing Base64!");
else console.log("Uncompressed:", buf.toString("utf8") );
});
}

View File

@@ -0,0 +1,10 @@
def gcd(a, b):
while( b != 0 ):
Remainder = a % b;
a = b;
b = Remainder;
return a;
g = gcd(54,8)
print (g)

View File

@@ -0,0 +1,6 @@
message = raw_input('Enter message: ')
e = raw_input('Enter exponent: ')
p = raw_input('Enter prime ')
cipher = (int(message) ** int(e)) % int(p)
print (cipher)

View File

@@ -0,0 +1,33 @@
import math
def get_if_prime(val):
max = math.sqrt(val);
if (val % 2 == 0):
return (False);
if (val % 3 == 0):
return (False);
for k in range(0, 10000):
testval = 6 * k + 1;
if (testval>max):
break
if (val % testval == 0):
return (False)
testval = 6 * k - 1;
if (testval>max):
break
if (val % testval == 0):
return (False)
return (true)
val=93
res = get_if_prime(val)
if (res==True):
print str(val)+" is prime"
else:
print str(val)+" is not prime"

View File

@@ -0,0 +1,21 @@
#
import sys
test=1000
if (len(sys.argv)>1):
test=int(sys.argv[1])
def sieve_for_primes_to(n):
size = n//2
sieve = [1]*size
limit = int(n**0.5)
for i in range(1,limit):
if sieve[i]:
val = 2*i+1
tmp = ((size-1) - i)//val
sieve[i+val::val] = [0]*tmp
return [2] + [i*2+1 for i, v in enumerate(sieve) if v and i>0]
print sieve_for_primes_to(test)

View File

@@ -0,0 +1,51 @@
# http://asecuritysite.com/encryption/rabin
import random
import sys
_mrpt_num_trials = 5 # number of bases to test
testval=97
def is_probable_prime(n):
assert n >= 2
# special case 2
if n == 2:
return True
# ensure n is odd
if n % 2 == 0:
return False
# write n-1 as 2**s * d
# repeatedly try to divide n-1 by 2
s = 0
d = n-1
while True:
quotient, remainder = divmod(d, 2)
if remainder == 1:
break
s += 1
d = quotient
assert(2**s * d == n-1)
# test the base a to see whether it is a witness for the compositeness of n
def try_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True # n is definitely composite
for i in range(_mrpt_num_trials):
a = random.randrange(2, n)
if try_composite(a):
return False
return True
rtn=is_probable_prime(testval)
if (rtn==True):
print str(testval) + " is a prime"
else:
print str(testval) + " is not a prime"

View File

@@ -0,0 +1,17 @@
import math
def gen_linear(a, seed,c, m):
x=seed
res=""
for i in range(0,200):
val = (a * x + c) % m
res += str(val) + " "
x = val;
return (res)
a=21
X0=35
c=31
m=100
res=gen_linear(a,X0,c,m)
print (res)

View File

@@ -0,0 +1,84 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
# Unit 2: Symmetric Key
The key concepts involved are defining key entropy; key generators (such as using hashing methods to generate keys based on passphrases); symmetric key methods (AES, Twofish, 3DES, RC4 and ChaCha20); stream or block encryption; symmetric key modes (ECB/CBC/OFB); and salting/IV.
<!---
Back-up of content: [here](https://asecuritysite.com/csn11117/unit02)
-->
## What you should know at the end of unit?
* The differences between a stream cipher and a block cipher.
* How salting is used to change the cipher blocks.
* Use openssl to perform practical operations.
* Understand the encoding formats used for cipher text and keys.
* Define the difference between cipher block modes, such as between ECB and CBC.
## Presentations
* Week 2 Presentation (PPTX) - Symmetric Key Encryption: [here](https://github.com/billbuchanan/esecurity/blob/master/unit02_symmetric/lecture/chapter02_secret.pptx)
* Week 2 Presentation (Video) - Symmetric Key Encryption [here](https://youtu.be/nLRV34K3xIo)
* Week 2 Presentation (Lecture - Video) - Symmetric Key Encryption: [here](https://youtu.be/CCOt8Xk3ZVU)
## Lab
* Unit 2 Lab (PDF): [here](https://github.com/billbuchanan/esecurity/blob/master/unit02_symmetric/lab/new_lab02.pdf)
* Unit 2 Lab (Video): [here](https://youtu.be/N3UADaXmOik)
## Quick demos
* Introduction to AES: [here](https://www.youtube.com/watch?v=rSyvUYbMok8)
* Padding in ciphers: [here](https://www.youtube.com/watch?v=R3NosHMSi0o)
* Why EDE in 3DES?: [here](https://www.youtube.com/watch?v=ttayDxqfQkA)
## Sample exam questions
The following are sample exam questions for symmetric key:
* Explain the differences between stream and block ciphers, and why salt is required within the encryption process.
* **Where would I find this info?** Have a look at the penguin in [Unit 2](https://asecuritysite.com/public/chapter02_secret.pdf) (Slide 31), and here's an outline of the problem with ECB in this related [article](https://medium.com/asecuritysite-when-bob-met-alice/when-is-high-grade-encryption-not-high-grade-when-its-ecb-e1509ec56930?source=friends_link&sk=31ec28f1c2be74a81e53c67e71d5b259).
* What are the possible advantages of using stream ciphers over block ciphers?
* Bob encrypts his data using secret key encryption and sends it to Alice. Every time he produces the cipher text it changes, and he is worried that Alice will not be able to decipher the cipher text. He encrypts "Hello" and gets a different cipher stream each time. Why does the cipher text change, and why is she still able to decrypt it, even though it changes each time?
* AES uses an S-box to scramble the bits. How are the S-boxes for the encryption and decryption process linked?
* Bob is sending encrypted data to Alice, and Eve is listening. After listening for a while, Eve is able to send a valid encrypted message to Alice. By outlining ECB, discuss how this might be possible.
* **Where would I find this info?** Have a look at the penguin in [Unit 2](https://asecuritysite.com/public/chapter02_secret.pdf) (Slide 31), and here's an outline of the problem with ECB in this related article.
* Bob is using a password to generate a 128-bit encryption key. Explain why the key space is unlikely to be 2<sup>128</sup>, and why key entropy could be used to measure the equivalent key size.
* **Where would I find this info?** This is related to key entropy [here](https://asecuritysite.com/encryption/en), and try and understand how key entropy relates to the strength of the encryption.
* Bob says that the number of bytes used for the cipher text will change directly with the number of bytes used in the plain text. Alice disagrees and says that most encryption methods involve having block sizes. Who is correct? Explain why.
* With block encryption, how do we know where the ciphered data actually ends? Does it just use an end-of-file character or a NULL character?
* Alice says she is confused that Bob is sending her the same message as a cipher, but every time the cipher text changes. Apart from using the shared encryption key, what does Alice use to decipher the cipher text?
* Bob tells Alice that she won't be able to view the cipher text, but when she looks at the messages, they seem to be full of printable characters. What format is Bob likely to be using for the encoding of the cipher text, and what would you ask Alice to look for, in order to confirm your guess?
* Which of these is correct for CMS padding: "68656c6c6f3132330808080808080808", "68656c6c6f3132330909090909090909", and "68656c6c6f3132330A0A0A0A0A0A0A0A".
* **Where would I find information on this?** Look [here](https://asecuritysite.com/encryption/padding).
* Bob wants to cipher "edinburgh" with the key of "hello123" for a 256-bit AES key, and his encoding gives him "6564696e6275726768". What will be the padding that will be added?
* Eve says she thinks she can determine the number of characters within some ciphered plain-text. Is she correct? If so, how many plain-text characters were there in this ciphered message: "6920776f756c64206c696b6520746f2074616b65206120627265616b04040404".
* RC4 is a stream cipher, which is one of the recommended ciphers for IoT devices. Bob says that it has an infinitely long encryption key, and that his devices will not be able to cope with this size of key. How would you convince him that IoT devices will be able to cope with RC4?
* RC4 is used within Wifi systems. With WEP, a 40-bit encryption key which was shared over the network, and which had a 24-bit IV value. In relation to the key size, the scope of the key, and the size of the IV, what do you think were the fundamental problems with this setup?
* Bob says that he can creat two ciphers from a file with the word "hello", and which will always create the same cipher. If the cipher is "Z8onq9tXC3CL2oOwqLLWbg==" and the key is "password", which is the missing part of the command he used (find the replacement for [OPTION1] and [OPTION2]):
<pre>
openssl enc -e -[OPTION1] -in test.txt -pass pass:password -nosalt -[OPTION2]
</pre>
The following are encrypted with aes-256-cbc or 3-DES and have a password of "napier", "123456" or "password". Decode them:
* U2FsdGVkX18K9Dy9I/CewpNH2svvjyhNG3Bod77+uYo=
* U2FsdGVkX18pmUpnI7iopG3gsHVQPT1zyRwjlvAJ+aI=
* U2FsdGVkX19XlsCN50CFxZlBcCplPs9/
Please note: In the file you create, put one new line after the Base64 text. For example the answer to the first one is:
<pre>
openssl enc -d -aes-256-cbc -in test.txt -pass pass:123456 -base64
</pre>
## Addendum
In the lecture, the slide at the end of Unit 2 (Symmetric Key) should be (for an eight character password and with [a-z]):
![](https://github.com/billbuchanan/esecurity/blob/master/z_associated/unit02_update.png)
## Tests
* Test (Symmetric Key Encryption): [here](https://asecuritysite.com/tests/tests?sortBy=cryptobook02)
Note: There will be no multiple choice questions in the tests.

View File

@@ -0,0 +1,671 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
# Lab 2: Symmetric Key
Objective: The key objective of this lab is to understand the range of symmetric key methods used within symmetric key encryption. We will introduce block ciphers, stream ciphers and padding. The key tools used include OpenSSL, Python and JavaScript. Overall Python 2.7 has been used for the sample examples, but it should be easy to convert these to Python 3.x.
Lab Demo: [here](https://youtu.be/N3UADaXmOik)
## A OpenSSL
OpenSSL is a standard tool that we used in encryption. It supports many of the standard symmetric key methods, including AES, 3DES and ChaCha20.
### A.1
Using:
* openssl list-cipher-commands
* openssl version
Outline five encryption methods that are supported:
Outline the version of OpenSSL:
### A.2
Using openssl and the command in the form:
<pre>
openssl prime hex 1111
</pre>
Check if the following are prime numbers:
* 42 [Yes][No]
* 1421 [Yes][No]
### A.3
Now create a file named myfile.txt (using nano).
Next encrypt with aes-256-cbc
<pre>
openssl enc -aes-256-cbc -in myfile.txt -out encrypted.bin
</pre>
and enter your password.
Use the following command to view the output file:
<pre>
cat encrypted.bin
</pre>
Is it easy to write out or transmit the output: [Yes][No]
### A.4
Now repeat the previous command and add the base64 option.
<pre>
openssl enc -aes-256-cbc -in myfile.txt -out encrypted.bin base64
</pre>
Use following command to view the output file:
<pre>
cat encrypted.bin
</pre>
Is it easy to write out or transmit the output: [Yes][No]
### A.5
Now Repeat the previous command and observe the encrypted output.
<pre>
openssl enc -aes-256-cbc -in myfile.txt -out encrypted.bin base64
</pre>
Has the output changed? [Yes][No]
Why has it changed?
### A.6
Now let's decrypt the encrypted file with the correct format:
<pre>
openssl enc -d -aes-256-cbc -in encrypted.bin -pass pass:napier -base64
</pre>
Has the output been decrypted correctly?
What happens when you use the wrong password?
### A.7
Now encrypt a file with Blowfish and see if you can decrypt it.
Did you manage to decrypt the file? [Yes][No]
## B Padding (AES)
With encryption, we normally use a block cipher, and where we must pad the end blocks to make sure that the data fits into a whole number of block. Some background material is here:
Web link (Padding): http://asecuritysite.com/encryption/padding
In the first part of this tutorial we will investigate padding blocks:
### B.1
With AES which uses a 256-bit key, what is the normal block size (in bytes).
Block size (bytes):
Number of hex characters for block size:
### B.2
Go to: Web link (AES Padding): http://asecuritysite.com/encryption/padding
Using 256-bit AES encryption, and a message of “kettle” and a password of “oxtail”, determine the cipher using the differing padding methods (you only need to show the first six hex characters).
If you like, copy and paste the Python code from the page, and run it on your Ubuntu instance.
CMS:
Null:
Space:
### B.3
For the following words, estimate how many hex characters will be used for the 256-bit AES encryption:
Number of hex characters:
“fox”:
“foxtrot”:
“foxtrotanteater”:
“foxtrotanteatercastle”:
### B.4
With 256-bit AES, for n characters in a string, how would you generalise the calculation of the number of hex characters in the cipher text.
How many Base-64 characters would be used (remember 6 bits are used to represent a Base-64 character): Hex characters:
Base-64 characters:
## C Padding (DES)
In the first part of this lab we will investigate padding blocks.
### C.1
With DES which uses a 64-bit key, what is the normal block size (in bytes):
Block size (bytes):
Number of hex characters for block size:
### C.2
Go to: Web link (DES Padding): http://asecuritysite.com/encryption/padding_des
Using 64-bit DES key encryption, and a message of “kettle” and a password of “oxtail”, determine the cipher using the differing padding methods.
If you like, copy and paste the Python code from the page, and run it on your Ubuntu instance.
CMS:
Null:
Space:
### C.3
For the following words, estimate how many hex characters will be used for the 64-bit key DES encryption:
Number of hex characters:
“fox”:
“foxtrot”:
“foxtrotanteater”:
“foxtrotanteatercastle”:
### C.4
With 64-bit DES, for n characters in a string, how would you generalise the calculation of the number of hex characters in the cipher text.
How many Base-64 characters would be used (remember 6 bits are used to represent a Base-64 character): Hex characters:
Base-64 characters:
## D Python Coding (Encrypting)
In this part of the lab, we will investigate the usage of Python code to perform different padding methods and using AES. First download the code from:
Web link (Cipher code): http://asecuritysite.com/cipher01.zip
The code should be:
```python
from Crypto.Cipher import AES
import hashlib
import sys
import binascii
import Padding
val='hello'
password='hello'
plaintext=val
def encrypt(plaintext,key, mode):
encobj = AES.new(key,mode)
return(encobj.encrypt(plaintext))
def decrypt(ciphertext,key, mode):
encobj = AES.new(key,mode)
return(encobj.decrypt(ciphertext))
key = hashlib.sha256(password).digest()
plaintext = Padding.appendPadding(plaintext,blocksize=Padding.AES_blocksize,mode='CMS')
print "After padding (CMS): "+binascii.hexlify(bytearray(plaintext))
ciphertext = encrypt(plaintext,key,AES.MODE_ECB)
print "Cipher (ECB): "+binascii.hexlify(bytearray(ciphertext))
plaintext = decrypt(ciphertext,key,AES.MODE_ECB)
plaintext = Padding.removePadding(plaintext,mode='CMS')
print " decrypt: "+plaintext
plaintext=val
```
Now update the code so that you can enter a string and the program will show the cipher text. The format will be something like:
<pre>
python cipher01.py hello mykey
</pre>
where “hello” is the plain text, and “mykey” is the key. A possible integration is:
```python
import sys
if (len(sys.argv)>1):
val=sys.argv[1]
if (len(sys.argv)>2):
password=sys.argv[2]
```
Now determine the cipher text for the following (the first example has already been completed):
Message Key CMS Cipher
hello hello123
0a7ec77951291795bac6690c9e7f4c0d
inkwell orange
security qwerty
Africa changeme
Now copy your code and modify it so that it implements 64-bit DES and complete the table (Ref to: http://asecuritysite.com/encryption/padding_des):
Message Key CMS Cipher
hello hello123 8f770898ddb9fb38
inkwell orange
security qwerty
Africa changeme
Now modify the code so that the user can enter the values from the keyboard, such as with:
```python
cipher=raw_input('Enter cipher:')
password=raw_input('Enter password:')
```
## E Python Coding (Decrypting)
Now modify your coding for 256-bit AES ECB encryption, so that you can enter the cipher text, and an encryption key, and the code will decrypt to provide the result. You should use CMS for padding. With this, determine the plaintext for the following (note, all the plain text values are countries around the World):
CMS Cipher (256-bit AES ECB) Key Plain text
b436bd84d16db330359edebf49725c62 “hello”
4bb2eb68fccd6187ef8738c40de12a6b “ankle”
029c4dd71cdae632ec33e2be7674cc14 “changeme”
d8f11e13d25771e83898efdbad0e522c “123456”
Now modify your coding for 64-bit DES ECB encryption, so that you can enter the cipher text, and an encryption key, and the code will decrypt to provide the result. You should use CMS for padding. With this, determine the plaintext for the following (note, all the plain text values are countries around the World):
CMS Cipher (64-bit DES ECB) Key Plain text
f37ee42f2267458d “hello”
67b7d1162394b868 “ankle”
ac9feb702ba2ecc0 “changeme”
de89513fbd17d0dc “123456”
Now update your program, so that it takes a cipher string in Base-64 and converts it to a hex string and then decrypts it. From this now decrypt the following Base-64 encoded cipher streams (which should give countries of the World):
CMS Cipher (256-bit AES ECB) Key Plain text
/vA6BD+ZXu8j6KrTHi1Y+w== “hello”
nitTRpxMhGlaRkuyXWYxtA== “ankle”
irwjGCAu+mmdNeu6Hq6ciw== “changeme”
5I71KpfT6RdM/xhUJ5IKCQ== “123456”
PS … remember to add "import base64".
## F Catching exceptions
If we try “1jDmCTD1IfbXbyyHgAyrdg==” with a passphrase of “hello”, we should get a country. What happens when we try the wrong passphrase?
Output when we use “hello”:
Output when we use “hello1”:
Now catch the exception with an exception handler:
```python
try:
plaintext = Padding.removePadding(plaintext,mode='CMS')
print " decrypt: "+plaintext
except:
print("Error!")
```
Now implement a Python program which will try various keys for a cipher text input, and show the decrypted text. The keys tried should be:
["hello","ankle","changeme","123456"]
Run the program and try to crack:
<pre>
1jDmCTD1IfbXbyyHgAyrdg==
</pre>
What is the password:
## G Stream Ciphers
The Chacha20 cipher is a stream cipher which uses a 256-bit key and a 64-bit nonce (salt value). Currently AES has a virtual monopoly on secret key encryption. There would be major problems, though, if this was cracked. Along with this AES has been shown to be weak around cache-collision attacks. Google thus propose ChaCha20 as an alternative, and actively use it within TLS connections. Currently it is three times faster than software-enabled AES and is not sensitive to timing attacks. It operates by creating a key stream which is then X-ORed with the plaintext. It has been standardised with RFC 7539.
### G.1 We can use node.js to implement ChaCha20:
```javascript
var chacha20 = require("chacha20");
var crypto = require('crypto');
var keyname="test";
var plaintext = "testing";
var args = process.argv;
if (args.length>2) plaintext=args[2];
if (args.length>3) keyname=args[3];
var key = crypto.createHash('sha256').update(keyname).digest();
var nonce = new Buffer.alloc(8);
nonce.fill(0);
console.log( key);
var ciphertext = chacha20.encrypt(key, nonce, new Buffer.from(plaintext));
console.log("Ciphertext:\t",ciphertext.toString("hex"));
console.log("Decipher\t",chacha20.decrypt(key,
nonce, ciphertext).toString());
```
If we use a key of "qwerty", can you find the well-known fruits (in lower case) of the following ChaCha20 cipher streams:
<pre>
e47a2bfe646a
ea783afc66
e96924f16d6e
</pre>
What are the fruits?
What can you say about the length of the cipher stream as related to the plaintext?
How are we generating the key and what is the key length?
What is the first two bytes of the key if we use a pass-phrase of “qwerty”?
What is the salt used in the same code?
How would you change the program so that the cipher stream was shown in in Base64?
How many bits will the salt use? You may have to look at the node.js documentation on the method for this.
### G.2
RC4 is a standard stream cipher and can be used for light-weight cryptography. It can have a variable key size. The following is a node.js implementation:
```javascript
// RC4
var crypto = require('crypto');
var keyname="test";
var plaintext = "testing";
var args = process.argv;
if (args.length>2) plaintext=args[2];
if (args.length>3) keyname=args[3];
var key = crypto.createHash('sha256').update(keyname).digest();
var cipher = crypto.createCipheriv('rc4', key,'' );
var ciphertext = cipher.update( plaintext, 'utf8', 'hex');
console.log("Ciphertext:\t",ciphertext);
var decipher = crypto.createDecipheriv('rc4', key,'' );
var text = decipher.update( ciphertext, 'hex','utf8');
console.log("Decipher:\t",text);
```
For a password of "napier", find out the fruits used for these RC4 cipher streams:
<pre>
8d1cc8bdf6da
911adbb2e6dda57cdaad
8907deba
</pre>
What are the fruits?
What happens to the cipher when you add an IV (salt) string?
For light-weight cryptography, what is the advantage of having a variable key size:
How might we change the program to implement RC4 with a 128-bit key?
## H Node.js for encryption
Node.js can be used as a back-end encryption method. In the following we use the crypto module (which can be installed with “npm crypto”, if it has not been installed). The following defines a message, a passphrase and the encryption method.
```javascript
var crypto = require("crypto");
function encryptText(algor, key, iv, text, encoding) {
var cipher = crypto.createCipheriv(algor, key, iv);
encoding = encoding || "binary";
var result = cipher.update(text, "utf8", encoding);
result += cipher.final(encoding);
return result;
}
function decryptText(algor, key, iv, text, encoding) {
var decipher = crypto.createDecipheriv(algor, key, iv);
encoding = encoding || "binary";
var result = decipher.update(text, encoding);
result += decipher.final();
return result;
}
var data = "This is a test";
var password = "hello";
var algorithm = "aes256"
#const args = process.argv.slice(3);
#data = args[0];
#password = args[1];
#algorithm = args[2];
console.log("\nText:\t\t" + data);
console.log("Password:\t" + password);
console.log("Type:\t\t" + algorithm);
var hash,key;
if (algorithm.includes("256"))
{
hash = crypto.createHash('sha256');
hash.update(password);
key = new Buffer.alloc(32,hash.digest('hex'),'hex');
}
else if (algorithm.includes("192"))
{
hash = crypto.createHash('sha192');
hash.update(password);
key = new Buffer.alloc(24,hash.digest('hex'),'hex');
}
else if (algorithm.includes("128"))
{
hash = crypto.createHash('md5');
hash.update(password);
key = new Buffer.alloc(16,hash.digest('hex'),'hex');
}
const iv=new Buffer.alloc(16,crypto.pseudoRandomBytes(16));
console.log("Key:\t\t"+key.toString('base64'));
console.log("Salt:\t\t"+iv.toString('base64'));
var encText = encryptText(algorithm, key, iv, data, "base64");
console.log("\n================");
console.log("\nEncrypted:\t" + encText);
var decText = decryptText(algorithm, key, iv, encText, "base64");
console.log("\nDecrypted:\t" + decText);
```
Save the file as "h_01.js" and run the program with:
<pre>
node h_01.js
</pre>
Now complete the following table:
Text Pass phrase Type Ciphertext and salt (just define first four characters of each)
This is a test hello Aes128
France Qwerty123 Aes192
Germany Testing123 Aes256
Now reset the IV (the salt value) to an empty string (“”), and complete the table:
Text Pass phrase Type Ciphertext
This is a test hello Aes128
France Qwerty123 Aes192
Germany Testing123 Aes256
Does the ciphertext change when we have a fixed IV value?
Using an Internet search, list ten other encryption algorithms which can be used with createCipheriv:
## I Reflective questions
1. If we have five a values (“aaaaa”). What will be the padding value used for 256-bit AES with CMS:
2. If we have six a values (“aaaaaa”). What will be the hex values used for the plain text:
3. The following cipher text is 256-bit AES ECB for a number of spaces (0x20):
<pre>
c3f791fad9f9392116b2d12c8f6c4b3dc3f791fad9f9392116b2d12c8f6c4b3dc3f791fad9f9392116b2d12c8f6c4b3dc3f791fad9f9392116b2d12c8f6c4b3da3c788929dd8a9022bf04ebf1c98a4e4
</pre>
What can you observe from the cipher text:
What is the range that is possible for the number of spaces which have been used:
How might you crack a byte stream sequence like this:
4. For ChaCha20, we only generate a key stream. How is the ciphertext then created:
## J What I should have learnt from this lab?
The key things learnt:
• How to encrypt and decrypt with symmetric key encryption, and where we use a passphrase to generate the encryption key.
• How padding is used within the encryption and decryption processes.
• The core difference between a block cipher and a stream cipher.
## Notes
The code can be downloaded from:
git clone https://github.com/billbuchanan/esecurity
If you need to update the code, go into the esecurity folder, and run:
git pull
To install a Python library use:
pip install libname
To install a Node.js package, use:
npm install libname
## Possible solutions
Have a look at: https://github.com/billbuchanan/esecurity/blob/master/unit02_symmetric/lab/possible_ans.md

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,674 @@
<!---
B.4
```python
print (chars//16+1)*32
```
--->
<!---
C.4
```python
print (chars//16+1)*16
```
--->
Commands in Section A:
* openssl list-cipher-commands
* openssl version
* openssl prime hex 1111
* openssl enc -aes-256-cbc -in myfile.txt -out encrypted.bin
* openssl enc -aes-256-cbc -in myfile.txt -out encrypted.bin base64
* openssl enc -d -aes-256-cbc -in encrypted.bin -pass pass:napier -base64
## A.1
<pre>
$ openssl list-cipher-commands
aes-128-cbc
aes-128-ecb
aes-192-cbc
aes-192-ecb
aes-256-cbc
aes-256-ecb
base64
bf
bf-cbc
bf-cfb
bf-ecb
bf-ofb
camellia-128-cbc
camellia-128-ecb
camellia-192-cbc
camellia-192-ecb
camellia-256-cbc
camellia-256-ecb
cast
cast-cbc
cast5-cbc
cast5-cfb
cast5-ecb
cast5-ofb
des
des-cbc
des-cfb
des-ecb
des-ede
des-ede-cbc
des-ede-cfb
des-ede-ofb
des-ede3
des-ede3-cbc
des-ede3-cfb
des-ede3-ofb
des-ofb
des3
desx
rc2
rc2-40-cbc
rc2-64-cbc
rc2-cbc
rc2-cfb
rc2-ecb
rc2-ofb
rc4
rc4-40
seed
seed-cbc
seed-cfb
seed-ecb
seed-ofb
</pre>
And:
<pre>
napier@napier-virtual-machine:~$ openssl version
OpenSSL 1.0.2g 1 Mar 2016
</pre>
## A.3
<pre>
napier@napier-virtual-machine:~$ nano myfile.txt
napier@napier-virtual-machine:~$ openssl enc -aes-256-cbc -in myfile.txt -out encrypted.bin
enter aes-256-cbc encryption password: napier
Verifying - enter aes-256-cbc encryption password:
napier@napier-virtual-machine:~$ cat encrypted.bin
Salted__<12><>kBֿ<42><D6BF>O<EFBFBD>;<3B>|`<02>"<22><><EFBFBD><EFBFBD>ե
napier@napier-virtual-machine:~$ openssl enc -d -aes-256-cbc -in encrypted.bin
enter aes-256-cbc decryption password: napier
Hello
</pre>
## A.4
<pre>
napier@napier-virtual-machine:~$ openssl enc -aes-256-cbc -in myfile.txt -out encrypted.bin -base64
enter aes-256-cbc encryption password:
Verifying - enter aes-256-cbc encryption password:
napier@napier-virtual-machine:~$ cat encrypted.bin
U2FsdGVkX18Z7N1ZzT9+up7rmoTInUto8HAflAvIEPE=
napier@napier-virtual-machine:~$ openssl enc -d -aes-256-cbc -in encrypted.bin -base64
enter aes-256-cbc decryption password: napier
Hello
</pre>
## A.7
We can use the -bf-cbc option for Blowfish:
<pre>
openssl enc -bf-cbc -in myfile.txt -out encrypted1.bin
openssl enc -d -bf-cbc -pass pass:password -in encrypted1.bin
</pre>
A sample run is:
<pre>
$ openssl enc -bf-cbc -in myfile.txt -out encrypted1.bin
enter bf-cbc encryption password: password
Verifying - enter bf-cbc encryption password: password
$ openssl enc -d -bf-cbc -pass pass:password -in encrypted1.bin
Hello
</pre>
## B.2
You may need to install "Crypto" with:
<pre>
pip install pycrypto
</pre>
And Padding with:
<pre>
pip install padding
</pre>
```python
from Crypto.Cipher import AES
import hashlib
import sys
import binascii
import Padding
val='hello'
password='hello'
plaintext=val
def encrypt(plaintext,key, mode):
encobj = AES.new(key,mode)
return(encobj.encrypt(plaintext))
def decrypt(ciphertext,key, mode):
encobj = AES.new(key,mode)
return(encobj.decrypt(ciphertext))
key = hashlib.sha256(password).digest()
plaintext = Padding.appendPadding(plaintext,blocksize=Padding.AES_blocksize,mode='CMS')
print "After padding (CMS): "+binascii.hexlify(bytearray(plaintext))
ciphertext = encrypt(plaintext,key,AES.MODE_ECB)
print "Cipher (ECB): "+binascii.hexlify(bytearray(ciphertext))
plaintext = decrypt(ciphertext,key,AES.MODE_ECB)
plaintext = Padding.removePadding(plaintext,mode='CMS')
print " decrypt: "+plaintext
plaintext=val
plaintext = Padding.appendPadding(plaintext,blocksize=Padding.AES_blocksize,mode='ZeroLen')
print "\nAfter padding (Bit): "+binascii.hexlify(bytearray(plaintext))
ciphertext = encrypt(plaintext,key,AES.MODE_ECB)
print "Cipher (ECB): "+binascii.hexlify(bytearray(ciphertext))
plaintext = decrypt(ciphertext,key,AES.MODE_ECB)
plaintext = Padding.removePadding(plaintext,blocksize=Padding.AES_blocksize,mode='ZeroLen')
print " decrypt: "+plaintext
plaintext=val
plaintext = Padding.appendPadding(plaintext,blocksize=Padding.AES_blocksize,mode='Space')
print "\nAfter padding (Null): "+binascii.hexlify(bytearray(plaintext))
ciphertext = encrypt(plaintext,key,AES.MODE_ECB)
print "Cipher (ECB): "+binascii.hexlify(bytearray(ciphertext))
plaintext = decrypt(ciphertext,key,AES.MODE_ECB)
plaintext = Padding.removePadding(plaintext,blocksize=Padding.AES_blocksize,mode='Space')
print " decrypt: "+plaintext
plaintext=val
plaintext = Padding.appendPadding(plaintext,blocksize=Padding.AES_blocksize,mode='Random')
print "\nAfter padding (Random): "+binascii.hexlify(bytearray(plaintext))
ciphertext = encrypt(plaintext,key,AES.MODE_ECB)
print "Cipher (ECB): "+binascii.hexlify(bytearray(ciphertext))
plaintext = decrypt(ciphertext,key,AES.MODE_ECB)
plaintext = Padding.removePadding(plaintext,mode='Random')
print " decrypt: "+plaintext
```
## C.2
```python
from Crypto.Cipher import DES
import hashlib
import sys
import binascii
import Padding
val='hello'
password='hello'
plaintext=val
def encrypt(plaintext,key, mode):
encobj = DES.new(key,mode)
return(encobj.encrypt(plaintext))
def decrypt(ciphertext,key, mode):
encobj = DES.new(key,mode)
return(encobj.decrypt(ciphertext))
print "\nDES"
key = hashlib.sha256(password).digest()[:8]
plaintext = Padding.appendPadding(plaintext,blocksize=Padding.DES_blocksize,mode='CMS')
print "After padding (CMS): "+binascii.hexlify(bytearray(plaintext))
ciphertext = encrypt(plaintext,key,DES.MODE_ECB)
print "Cipher (ECB): "+binascii.hexlify(bytearray(ciphertext))
plaintext = decrypt(ciphertext,key,DES.MODE_ECB)
plaintext = Padding.removePadding(plaintext,mode='CMS')
print " decrypt: "+plaintext
```
## D.1
```python
from Crypto.Cipher import AES
import hashlib
import sys
import binascii
import Padding
val='hello'
password='hello'
if (len(sys.argv)>1):
val=sys.argv[1]
if (len(sys.argv)>2):
password=sys.argv[2]
plaintext=val
def encrypt(plaintext,key, mode):
encobj = AES.new(key,mode)
return(encobj.encrypt(plaintext))
def decrypt(ciphertext,key, mode):
encobj = AES.new(key,mode)
return(encobj.decrypt(ciphertext))
key = hashlib.sha256(password).digest()
plaintext = Padding.appendPadding(plaintext,blocksize=Padding.AES_blocksize,mode='CMS')
print "After padding (CMS): "+binascii.hexlify(bytearray(plaintext))
ciphertext = encrypt(plaintext,key,AES.MODE_ECB)
print "Cipher (ECB): "+binascii.hexlify(bytearray(ciphertext))
plaintext = decrypt(ciphertext,key,AES.MODE_ECB)
plaintext = Padding.removePadding(plaintext,mode='CMS')
print " decrypt: "+plaintext
plaintext=val
```
A sample run is:
<pre>
napier@napier-virtual-machine:~$ python d1.py hello hello123
After padding (CMS): 68656c6c6f0b0b0b0b0b0b0b0b0b0b0b
Cipher (ECB): 0a7ec77951291795bac6690c9e7f4c0d
decrypt: hello
napier@napier-virtual-machine:~$ python d1.py inkwell orange
After padding (CMS): 696e6b77656c6c090909090909090909
Cipher (ECB): 484299ceec1ad83b1ce848b0a9733c8d
decrypt: inkwell
napier@napier-virtual-machine:~$ python d1.py security qwerty
After padding (CMS): 73656375726974790808080808080808
Cipher (ECB): 6be35165e2c9a624de4f401692fe7161
decrypt: security
napier@napier-virtual-machine:~$ python d1.py Africa changme
After padding (CMS): 4166726963610a0a0a0a0a0a0a0a0a0a
Cipher (ECB): ab453ac52cd3b1a61b35d6e85e4568f8
decrypt: Africa
</pre>
## D.2
Sample code is:
```python
from Crypto.Cipher import DES
import hashlib
import sys
import binascii
import Padding
val='hello'
password='hello'
if (len(sys.argv)>1):
val=sys.argv[1]
if (len(sys.argv)>2):
password=sys.argv[2]
plaintext=val
def encrypt(plaintext,key, mode):
encobj = DES.new(key,mode)
return(encobj.encrypt(plaintext))
def decrypt(ciphertext,key, mode):
encobj = DES.new(key,mode)
return(encobj.decrypt(ciphertext))
key = hashlib.sha256(password).digest()
plaintext = Padding.appendPadding(plaintext,blocksize=Padding.DES_blocksize,mode='CMS')
print "After padding (CMS): "+binascii.hexlify(bytearray(plaintext))
ciphertext = encrypt(plaintext,key[:8],DES.MODE_ECB)
print "Cipher (ECB): "+binascii.hexlify(bytearray(ciphertext))
plaintext = decrypt(ciphertext,key[:8],DES.MODE_ECB)
plaintext = Padding.removePadding(plaintext,mode='CMS')
print " decrypt: "+plaintext
plaintext=val
```
A sample run is:
<pre>
napier@napier-virtual-machine:~$ python d2.py hello hello123
After padding (CMS): 68656c6c6f030303
Cipher (ECB): 8f770898ddb9fb38
decrypt: hello
napier@napier-virtual-machine:~$ python d2.py inkwell orange
After padding (CMS): 696e6b77656c6c01
Cipher (ECB): 1086a73ab5273254
decrypt: inkwell
napier@napier-virtual-machine:~$ python d2.py security qwerty
After padding (CMS): 73656375726974790808080808080808
Cipher (ECB): d19c86b3fc7e924f148652c183caa922
decrypt: security
napier@napier-virtual-machine:~$ python d2.py Africa changeme
After padding (CMS): 4166726963610202
Cipher (ECB): 6e11929fe6a3c081
decrypt: Africa
</pre>
## D.3
Answer:
* /vA6BD+ZXu8j6KrTHi1Y+w== - italy
```python
from Crypto.Cipher import AES
import hashlib
import sys
import binascii
import Padding
import base64
val='fox'
password='hello'
cipher=''
import sys
if (len(sys.argv)>1):
cipher=(sys.argv[1])
if (len(sys.argv)>2):
password=(sys.argv[2])
plaintext=val
def encrypt(plaintext,key, mode):
encobj = AES.new(key,mode)
return(encobj.encrypt(plaintext))
def decrypt(ciphertext,key, mode):
encobj = AES.new(key,mode)
return(encobj.decrypt(ciphertext))
key = hashlib.sha256(password).digest()
cipher='/vA6BD+ZXu8j6KrTHi1Y+w=='
ciphertext = base64.b64decode(cipher)
plaintext = decrypt(ciphertext,key,AES.MODE_ECB)
print plaintext
plaintext = Padding.removePadding(plaintext,mode='CMS')
print " decrypt: "+plaintext
plaintext=val
```
## E.1
Answers:
* germany
* france
* england
* scotland
Possible solution for E.1:
```python
from Crypto.Cipher import AES
import hashlib
import sys
import binascii
import Padding
val='fox'
password='hello'
cipher='b436bd84d16db330359edebf49725c62'
import sys
if (len(sys.argv)>1):
cipher=(sys.argv[1])
if (len(sys.argv)>2):
password=(sys.argv[2])
plaintext=val
def encrypt(plaintext,key, mode):
encobj = AES.new(key,mode)
return(encobj.encrypt(plaintext))
def decrypt(ciphertext,key, mode):
encobj = AES.new(key,mode)
return(encobj.decrypt(ciphertext))
key = hashlib.sha256(password).digest()
ciphertext=binascii.unhexlify(cipher)
plaintext = decrypt(ciphertext,key,AES.MODE_ECB)
print ('Cipher: '+ cipher)
print ('Password: '+ password)
plaintext = Padding.removePadding(plaintext,mode='CMS')
print (" decrypt: "+plaintext)
```
A sample run gives:
<pre>
Cipher: b436bd84d16db330359edebf49725c62
Password: hello
decrypt: germany
</pre>
## E.2
Answers:
* germany
* france
* england
* scotland
DES uses a 64-bit key, of which we have use 56 bits for the actual key. We thus need to truncate our SHA-256 generated key, down to a 64-bit key. We can do that in Python with [:8]. A possible solution for E.2:
```python
from Crypto.Cipher import DES
import hashlib
import sys
import binascii
import Padding
val='fox'
password='hello'
cipher=''
import sys
def encrypt(plaintext,key, mode):
encobj = DES.new(key,mode)
return(encobj.encrypt(plaintext))
def decrypt(ciphertext,key, mode):
encobj = DES.new(key,mode)
return(encobj.decrypt(ciphertext))
key = hashlib.sha256(password).digest()
ciphertext=binascii.unhexlify("f37ee42f2267458d")
plaintext = decrypt(ciphertext,key[:8],DES.MODE_ECB)
print plaintext
plaintext = Padding.removePadding(plaintext,mode='CMS')
print " decrypt: "+plaintext
plaintext=val
```
## F.1
Plaintext: norway
Key: changeme
A sample code is:
```python
from Crypto.Cipher import AES
import hashlib
import sys
import binascii
import Padding
import base64
def decrypt(ciphertext,key, mode):
encobj = AES.new(key,mode)
return(encobj.decrypt(ciphertext))
pw = ["hello","ankle","changeme","123456"]
c='1jDmCTD1IfbXbyyHgAyrdg=='
for password in pw:
try:
key = hashlib.sha256(password).digest()
cipherhex = base64.b64decode(c).encode('hex')
ciphertext = binascii.unhexlify(cipherhex)
print "Cipher (ECB): "+binascii.hexlify(bytearray(ciphertext))
plaintext = decrypt(ciphertext,key,AES.MODE_ECB)
plaintext = Padding.removePadding(plaintext,mode='CMS')
print " decrypt: "+plaintext
print " Key found: "+password
except:
print(".")
```
## G.1
Answers:
* e47a2bfe646a - orange
* ea783afc66 - apple
* e96924f16d6e - banana
Just convert the hex value to a byte array:
```javascript
var chacha20 = require("chacha20");
var crypto = require('crypto');
var keyname="qwerty";
var key = crypto.createHash('sha256').update(keyname).digest();
var nonce = new Buffer.alloc(8);
nonce.fill(0);
console.log( key);
var ciphertext="e96924f16d6e"
// var ciphertext="ea783afc66"
// var ciphertext="e47a2bfe646a"
console.log("Ciphertext:\t",ciphertext);
console.log("Decipher\t",chacha20.decrypt(key,nonce, new Buffer(ciphertext,"hex")).toString());
```
A sample run is:
<pre>
$ <b>npm install chacha20</b>
$ <b>cat fruit.js</b>
var chacha20 = require("chacha20");
var crypto = require('crypto');
var keyname="qwerty";
var key = crypto.createHash('sha256').update(keyname).digest();
var nonce = new Buffer.alloc(8);
nonce.fill(0);
console.log( key);
var ciphertext="e96924f16d6e"
// var ciphertext="ea783afc66"
// var ciphertext="e47a2bfe646a"
console.log("Ciphertext:\t",ciphertext);
console.log("Decipher\t",chacha20.decrypt(key,nonce, new Buffer(ciphertext,"hex")).toString())
$ <b>node fruit.js</b>
<Buffer 65 e8 4b e3 35 32 fb 78 4c 48 12 96 75 f9 ef f3 a6 82 b2 71 68 c0 ea 74 4b 2c f5 8e e0 23 37 c5>
Ciphertext: e96924f16d6e
Decipher banana
</pre>
## G.2
Answers:
* 8d1cc8bdf6da - orange
* 911adbb2e6dda57cdaad - strawberry
* 8907deba - kiwi
```javascript
// RC4
var crypto = require('crypto');
var keyname="napier";
var key = crypto.createHash('sha256').update(keyname).digest();
var cipher = crypto.createCipheriv('rc4', key,'' );
var ciphertext = '8d1cc8bdf6da'
console.log("Ciphertext:\t",ciphertext);
var decipher = crypto.createDecipheriv('rc4', key,'' );
var text = decipher.update( new Buffer(ciphertext,"hex"), 'hex','utf8');
console.log("Decipher:\t",text);
```
A sample run is:
<pre>
$ <b>nano fruit2.js</b>
$ <b>cat fruit2.js</b>
var crypto = require('crypto');
var keyname="napier";
var key = crypto.createHash('sha256').update(keyname).digest();
var cipher = crypto.createCipheriv('rc4', key,'' );
var ciphertext = '8d1cc8bdf6da'
console.log("Ciphertext:\t",ciphertext);
var decipher = crypto.createDecipheriv('rc4', key,'' );
var text = decipher.update( new Buffer(ciphertext,"hex"), 'hex','utf8');
console.log("Decipher:\t",text);
$ <b>node fruit2.js </b>
Ciphertext: 8d1cc8bdf6da
Decipher: orange
</pre>

View File

@@ -0,0 +1,31 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
# 2. Symmetric Key Encryption
## Outline
The key concepts involved in this unit are:
* Defining key entropy;
* Key generators (such as using hashing methods to generate keys based on passphrases);
* Symmetric key methods (AES, Twofish, 3DES, RC4 and ChaCha20);
* Stream or block encryption;
* Symmetric key modes (ECB/CBC/OFB);
* Salting/IV.
## Presentations
* Week 2 Presentation (PDF) - Symmetric Key Encryption: [here](https://asecuritysite.com/public/chapter02_secret.pdf)
* Week 2 Presentation (Video) - Symmetric Key Encryption [here](https://youtu.be/nLRV34K3xIo)
* Week 2 Presentation (Lecture - Video) - Symmetric Key Encryption: [here](https://youtu.be/CCOt8Xk3ZVU). Recorded on Friday 24 Jan 2020.
## Videos
The voice over lecture is here:
[![](http://img.youtube.com/vi/nLRV34K3xIo/0.jpg)](https://www.youtube.com/watch?v=nLRV34K3xIo "")
And the classroom lecture from 24 Jan 2020 is here:
[![](http://img.youtube.com/vi/CCOt8Xk3ZVU/0.jpg)](https://www.youtube.com/watch?v=CCOt8Xk3ZVU "")

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)

View File

@@ -0,0 +1,2 @@
openssl list-cipher-commands
openssl version

View File

@@ -0,0 +1 @@
openssl prime -hex 1111

View File

@@ -0,0 +1 @@
openssl enc -aes-256-cbc -in myfile.txt -out encrypted.bin

View File

@@ -0,0 +1 @@
openssl enc -aes-256-cbc -in myfile.txt -out encrypted.bin <20>base64

View File

@@ -0,0 +1 @@
openssl enc -aes-256-cbc -in myfile.txt -out encrypted.bin <20>base64

View File

@@ -0,0 +1 @@
openssl enc -d -aes-256-cbc -in encrypted.bin -pass pass:napier -base64

View File

@@ -0,0 +1,5 @@
import passlib.hash;
string="hello"
print ("LM Hash:"+passlib.hash.lmhash.encrypt(string))
print ("NT Hash:"+passlib.hash.nthash.encrypt(string))

View File

@@ -0,0 +1,36 @@
from Crypto.Cipher import AES
import hashlib
import sys
import binascii
import Padding
val='hello'
password='hello'
plaintext=val
def encrypt(plaintext,key, mode):
encobj = AES.new(key,mode)
return(encobj.encrypt(plaintext))
def decrypt(ciphertext,key, mode):
encobj = AES.new(key,mode)
return(encobj.decrypt(ciphertext))
key = hashlib.sha256(password.encode()).digest()
plaintext = Padding.appendPadding(plaintext,blocksize=Padding.AES_blocksize,mode='CMS')
print("After padding (CMS): ",binascii.hexlify(bytearray(plaintext.encode())))
ciphertext = encrypt(plaintext.encode(),key,AES.MODE_ECB)
print("Cipher (ECB): ",binascii.hexlify(bytearray(ciphertext)))
plaintext = decrypt(ciphertext,key,AES.MODE_ECB)
plaintext = Padding.removePadding(plaintext.decode(),mode='CMS')
print(" decrypt: ",plaintext)
plaintext=val

View File

@@ -0,0 +1,20 @@
var chacha20 = require("chacha20");
var crypto = require('crypto');
var keyname="test";
var plaintext = "testing";
var args = process.argv;
if (args.length>2) plaintext=args[2];
if (args.length>3) keyname=args[3];
var key = crypto.createHash('sha256').update(keyname).digest();
var nonce = new Buffer.alloc(8);
nonce.fill(0);
console.log( key);
var ciphertext = chacha20.encrypt(key, nonce, new Buffer.from(plaintext));
console.log("Ciphertext:\t",ciphertext.toString("hex"));
console.log("Decipher\t",chacha20.decrypt(key, nonce, ciphertext).toString());

View File

@@ -0,0 +1,21 @@
// RC4
var crypto = require('crypto');
var keyname="test";
var plaintext = "testing";
var args = process.argv;
if (args.length>1) plaintext=args[2];
if (args.length>2) keyname=args[3];
var key = crypto.createHash('sha256').update(keyname).digest();
var cipher = crypto.createCipheriv('rc4', key,'' );
var ciphertext = cipher.update( plaintext, 'utf8', 'hex');
console.log("Ciphertext:\t",ciphertext);
var decipher = crypto.createDecipheriv('rc4', key,'' );
var text = decipher.update( ciphertext, 'hex','utf8');
console.log("Decipher:\t",text);

View File

@@ -0,0 +1,155 @@
var Chacha20KeySize = 32;
var Chacha20NonceSize = 8;
key = '0000000000000000000000000000000000000000000000000000000000000000';
nce = '0000000000000000';
document.getElementById("val1").innerHTML = nce;
document.getElementById("key").innerHTML = key;
go();
function go() {
n = document.getElementById('val1').value;
k = document.getElementById('key').value;
document.getElementById("encrypted").innerHTML = "Key:\t" + k;
document.getElementById("encrypted").innerHTML += "\nNouce:\t" + n;
n = from_Hex(n);
k = from_Hex(k);
var ctx, out;
out = new Array(k.length);
ctx = chacha20_init(k, n);
chacha20_keystream(ctx, out, out, k.length);
document.getElementById("encrypted").innerHTML += "\n---\nKey generation: " + bytes2hex(out);
}
var Chacha20Ctx = function () {
this.input = new Array(16);
};
function load32(x, i) {
return x[i] | (x[i + 1] << 8) | (x[i + 2] << 16) | (x[i + 3] << 24);
}
function store32(x, i, u) {
x[i] = u & 0xff; u >>>= 8;
x[i + 1] = u & 0xff; u >>>= 8;
x[i + 2] = u & 0xff; u >>>= 8;
x[i + 3] = u & 0xff;
}
function rotl32(v, c) {
return (v << c) | (v >>> (32 - c));
}
function chacha20_round(x, a, b, c, d) {
x[a] += x[b]; x[d] = rotl32(x[d] ^ x[a], 16);
x[c] += x[d]; x[b] = rotl32(x[b] ^ x[c], 12);
x[a] += x[b]; x[d] = rotl32(x[d] ^ x[a], 8);
x[c] += x[d]; x[b] = rotl32(x[b] ^ x[c], 7);
}
function chacha20_init(key, nonce) {
var x = new Chacha20Ctx();
x.input[0] = 1634760805;
x.input[1] = 857760878;
x.input[2] = 2036477234;
x.input[3] = 1797285236;
x.input[12] = 0;
x.input[13] = 0;
x.input[14] = load32(nonce, 0);
x.input[15] = load32(nonce, 4);
for (var i = 0; i < 8; i++) {
x.input[i + 4] = load32(key, i * 4);
}
return x;
}
function chacha20_keystream(ctx, dst, src, len) {
var x = new Array(16);
var buf = new Array(64);
var i = 0, dpos = 0, spos = 0;
while (len > 0) {
for (i = 16; i--;) x[i] = ctx.input[i];
for (i = 20; i > 0; i -= 2) {
chacha20_round(x, 0, 4, 8, 12);
chacha20_round(x, 1, 5, 9, 13);
chacha20_round(x, 2, 6, 10, 14);
chacha20_round(x, 3, 7, 11, 15);
chacha20_round(x, 0, 5, 10, 15);
chacha20_round(x, 1, 6, 11, 12);
chacha20_round(x, 2, 7, 8, 13);
chacha20_round(x, 3, 4, 9, 14);
}
for (i = 16; i--;) x[i] += ctx.input[i];
for (i = 16; i--;) store32(buf, 4 * i, x[i]);
ctx.input[12] += 1;
if (!ctx.input[12]) {
ctx.input[13] += 1;
}
if (len <= 64) {
for (i = len; i--;) {
dst[i + dpos] = src[i + spos] ^ buf[i];
}
return;
}
for (i = 64; i--;) {
dst[i + dpos] = src[i + spos] ^ buf[i];
}
len -= 64;
spos += 64;
dpos += 64;
}
}
//--------------------------- test -----------------------------//
function bytes2hex(blk, dlm) {
return Array.prototype.map.call(new Uint8Array(blk.buffer || blk),
function (s) { return ('00' + s.toString(16)).slice(-2); }).join(dlm || '');
}
function from_Hex(h) {
h.replace(' ', '');
var out = [], len = h.length, w = '';
for (var i = 0; i < len; i += 2) {
w = h[i];
if (((i + 1) >= len) || typeof h[i + 1] === 'undefined') {
w += '0';
} else {
w += h[i + 1];
}
out.push(parseInt(w, 16));
}
return out;
}
function bytesEqual(a, b) {
var dif = 0;
if (a.length !== b.length) return 0;
for (var i = 0; i < a.length; i++) {
dif |= (a[i] ^ b[i]);
}
dif = (dif - 1) >>> 31;
return (dif & 1);
}

View File

@@ -0,0 +1,84 @@
var crypto = require("crypto");
function encryptText(algor, key, iv, text, encoding) {
var cipher = crypto.createCipheriv(algor, key, iv);
encoding = encoding || "binary";
var result = cipher.update(text, "utf8", encoding);
result += cipher.final(encoding);
return result;
}
function decryptText(algor, key, iv, text, encoding) {
var decipher = crypto.createDecipheriv(algor, key, iv);
encoding = encoding || "binary";
var result = decipher.update(text, encoding);
result += decipher.final();
return result;
}
var data = "This is a test";
var password = "hello";
var algorithm = "aes256"
//const args = process.argv.slice(3);
//data = args[0];
//password = args[1];
//algorithm = args[2];
console.log("\nText:\t\t" + data);
console.log("Password:\t" + password);
console.log("Type:\t\t" + algorithm);
var hash,key;
if (algorithm.includes("256"))
{
hash = crypto.createHash('sha256');
hash.update(password);
key = new Buffer.alloc(32,hash.digest('hex'),'hex');
}
else if (algorithm.includes("192"))
{
hash = crypto.createHash('sha192');
hash.update(password);
key = new Buffer.alloc(24,hash.digest('hex'),'hex');
}
else if (algorithm.includes("128"))
{
hash = crypto.createHash('md5');
hash.update(password);
key = new Buffer.alloc(16,hash.digest('hex'),'hex');
}
const iv=new Buffer.alloc(16,crypto.pseudoRandomBytes(16));
console.log("Key:\t\t"+key.toString('base64'));
console.log("Salt:\t\t"+iv.toString('base64'));
var encText = encryptText(algorithm, key, iv, data, "base64");
console.log("\n================");
console.log("\nEncrypted:\t" + encText);
var decText = decryptText(algorithm, key, iv, encText, "base64");
console.log("\nDecrypted:\t" + decText);

View File

@@ -0,0 +1 @@
node_modules

View File

@@ -0,0 +1,7 @@
language: node_js
sudo: false
node_js:
- "0.10"
- "0.12"
- "4"

4
unit02_symmetric/src/node_modules/chacha20/Makefile generated vendored Normal file
View File

@@ -0,0 +1,4 @@
test:
./node_modules/.bin/mocha --reporter list
.PHONY: test

24
unit02_symmetric/src/node_modules/chacha20/README.md generated vendored Normal file
View File

@@ -0,0 +1,24 @@
Pure javascript implementation of [ChaCha20](http://cr.yp.to/chacha.html) originally written by [@devi](https://github.com/devi/chacha20poly1305) supporting [draft-irtf-cfrg-chacha20-poly1305-01](https://tools.ietf.org/html/draft-irtf-cfrg-chacha20-poly1305-01).
Being packaged here as a simple node.js and browserify module.
## Usage
````
var chacha20 = require("chacha20");
var key = new Buffer(32);
key.fill(0);
var nonce = new Buffer(8);
nonce.fill(0);
var plaintext = "testing";
// pass in buffers, returns a buffer
var ciphertext = chacha20.encrypt(key, nonce, new Buffer(plaintext));
console.log(ciphertext.toString("hex")); // prints "02dd93d9c99f5a"
console.log(chacha20.decrypt(key, nonce, ciphertext).toString()); // prints "testing"
````
## Nonce Size
The handling of the nonce differs between the [reference](http://cr.yp.to/chacha.html) and [IETF Draft](https://tools.ietf.org/html/draft-irtf-cfrg-chacha20-poly1305-01#section-2.3), where the reference uses an 8-byte nonce and the draft uses a 12-byte one with the first 4 bytes being a `sender` unique identifier. Passing a difference nonce buffer size will choose either mode.

116
unit02_symmetric/src/node_modules/chacha20/chacha20.js generated vendored Normal file
View File

@@ -0,0 +1,116 @@
/* chacha20 - 256 bits */
// Written in 2014 by Devi Mandiri. Public domain.
//
// Implementation derived from chacha-ref.c version 20080118
// See for details: http://cr.yp.to/chacha/chacha-20080128.pdf
function U8TO32_LE(x, i) {
return x[i] | (x[i+1]<<8) | (x[i+2]<<16) | (x[i+3]<<24);
}
function U32TO8_LE(x, i, u) {
x[i] = u; u >>>= 8;
x[i+1] = u; u >>>= 8;
x[i+2] = u; u >>>= 8;
x[i+3] = u;
}
function ROTATE(v, c) {
return (v << c) | (v >>> (32 - c));
}
var Chacha20 = function(key, nonce, counter) {
this.input = new Uint32Array(16);
// https://tools.ietf.org/html/draft-irtf-cfrg-chacha20-poly1305-01#section-2.3
this.input[0] = 1634760805;
this.input[1] = 857760878;
this.input[2] = 2036477234;
this.input[3] = 1797285236;
this.input[4] = U8TO32_LE(key, 0);
this.input[5] = U8TO32_LE(key, 4);
this.input[6] = U8TO32_LE(key, 8);
this.input[7] = U8TO32_LE(key, 12);
this.input[8] = U8TO32_LE(key, 16);
this.input[9] = U8TO32_LE(key, 20);
this.input[10] = U8TO32_LE(key, 24);
this.input[11] = U8TO32_LE(key, 28);
// be compatible with the reference ChaCha depending on the nonce size
if(nonce.length == 12)
{
this.input[12] = counter;
this.input[13] = U8TO32_LE(nonce, 0);
this.input[14] = U8TO32_LE(nonce, 4);
this.input[15] = U8TO32_LE(nonce, 8);
}else{
this.input[12] = counter;
this.input[13] = 0;
this.input[14] = U8TO32_LE(nonce, 0);
this.input[15] = U8TO32_LE(nonce, 4);
}
};
Chacha20.prototype.quarterRound = function(x, a, b, c, d) {
x[a] += x[b]; x[d] = ROTATE(x[d] ^ x[a], 16);
x[c] += x[d]; x[b] = ROTATE(x[b] ^ x[c], 12);
x[a] += x[b]; x[d] = ROTATE(x[d] ^ x[a], 8);
x[c] += x[d]; x[b] = ROTATE(x[b] ^ x[c], 7);
};
Chacha20.prototype.encrypt = function(dst, src, len) {
var x = new Uint32Array(16);
var output = new Uint8Array(64);
var i, dpos = 0, spos = 0;
while (len > 0 ) {
for (i = 16; i--;) x[i] = this.input[i];
for (i = 20; i > 0; i -= 2) {
this.quarterRound(x, 0, 4, 8,12);
this.quarterRound(x, 1, 5, 9,13);
this.quarterRound(x, 2, 6,10,14);
this.quarterRound(x, 3, 7,11,15);
this.quarterRound(x, 0, 5,10,15);
this.quarterRound(x, 1, 6,11,12);
this.quarterRound(x, 2, 7, 8,13);
this.quarterRound(x, 3, 4, 9,14);
}
for (i = 16; i--;) x[i] += this.input[i];
for (i = 16; i--;) U32TO8_LE(output, 4*i, x[i]);
this.input[12] += 1;
if (!this.input[12]) {
this.input[13] += 1;
}
if (len <= 64) {
for (i = len; i--;) {
dst[i+dpos] = src[i+spos] ^ output[i];
}
return;
}
for (i = 64; i--;) {
dst[i+dpos] = src[i+spos] ^ output[i];
}
len -= 64;
spos += 64;
dpos += 64;
}
};
Chacha20.prototype.keystream = function(dst, len) {
for (var i = 0; i < len; ++i) dst[i] = 0;
this.encrypt(dst, dst, len);
};
// additions to make it easier and export it as a module
exports.Cipher = Chacha20;
exports.encrypt = exports.decrypt = function(key, nonce, data)
{
var cipher = new Chacha20(key, nonce);
var ret = new Buffer(data.length);
cipher.encrypt(ret, data, data.length);
return ret;
}

View File

@@ -0,0 +1,71 @@
{
"_from": "chacha20",
"_id": "chacha20@0.1.4",
"_inBundle": false,
"_integrity": "sha1-CuFHSawjxESRL9xIKWhGFkn2nhg=",
"_location": "/chacha20",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "chacha20",
"name": "chacha20",
"escapedName": "chacha20",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/chacha20/-/chacha20-0.1.4.tgz",
"_shasum": "0ae14749ac23c444912fdc482968461649f69e18",
"_spec": "chacha20",
"_where": "/Users/billbuchanan/Dropbox/csn11117/2020/unit02_symmetric/src",
"author": {
"name": "Devi Mandiri",
"email": "me@devi.web.id",
"url": "https://github.com/devi"
},
"bugs": {
"url": "https://github.com/quartzjer/chacha20/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "A pure JavaScript implementation of the ChaCha20 cipher",
"devDependencies": {
"chai": "*",
"mocha": "*"
},
"engines": {
"node": ">=0.10.x",
"npm": ">=1.2.x"
},
"homepage": "https://github.com/quartzjer/chacha20",
"keywords": [
"chacha",
"chacha20",
"salsa20",
"browserify"
],
"license": "CC0-1.0",
"main": "chacha20.js",
"maintainers": [
{
"name": "Jeremie Miller",
"email": "jeremie@jabber.org",
"url": "http://jeremie.com/"
}
],
"name": "chacha20",
"repository": {
"type": "git",
"url": "git+https://github.com/quartzjer/chacha20.git"
},
"scripts": {
"test": "mocha"
},
"version": "0.1.4"
}

View File

@@ -0,0 +1,263 @@
var expect = require('chai').expect;
var chacha20 = require('..');
describe('chacha20', function(){
it('exports an object', function(){
expect(chacha20).to.be.a('object');
});
it('reference tests', function(){
var key = new Buffer(32);
key.fill(0);
var nonce = new Buffer(8);
nonce.fill(0);
var data = "\0\0\0\0\0\0\0\0\0"; // 9
var out = chacha20.encrypt(key, nonce, new Buffer(data));
expect(out.toString('hex')).to.be.equal("76b8e0ada0f13d9040");
expect(chacha20.decrypt(key, nonce, out).toString()).to.be.equal(data);
key.fill(0xff);
nonce.fill(0xff);
var ff = new Buffer(9);
ff.fill(0xff);
var out = chacha20.encrypt(key, nonce, ff);
expect(out.toString('hex')).to.be.equal("2640c09431912f4abd");
expect(chacha20.decrypt(key, nonce, out).toString("hex")).to.be.equal(ff.toString("hex"));
});
it('draft tests', function(){
var key = new Buffer(32);
key.fill(0);
var nonce = new Buffer(12);
nonce.fill(0);
var data = "\0\0\0\0\0\0\0\0\0"; // 9
var out = chacha20.encrypt(key, nonce, new Buffer(data));
expect(out.toString('hex')).to.be.equal("76b8e0ada0f13d9040");
expect(chacha20.decrypt(key, nonce, out).toString()).to.be.equal(data);
key.fill(0xff);
nonce.fill(0xff);
var ff = new Buffer(9);
ff.fill(0xff);
var out = chacha20.encrypt(key, nonce, ff);
expect(out.toString('hex')).to.be.equal("2919cb6a15012803c4");
expect(chacha20.decrypt(key, nonce, out).toString("hex")).to.be.equal(ff.toString("hex"));
});
it('original tests', function(){
var Chacha20 = chacha20.Cipher;
//--------------------------- test -----------------------------//
function fromHex(h) {
h = h.replace(/([^0-9a-f])/g, '');
var out = [], len = h.length, w = '';
for (var i = 0; i < len; i += 2) {
w = h[i];
if (((i+1) >= len) || typeof h[i+1] === 'undefined') {
w += '0';
} else {
w += h[i+1];
}
out.push(parseInt(w, 16));
}
return out;
}
function bytesEqual(a, b) {
var dif = 0;
if (a.length !== b.length) return 0;
for (var i = 0; i < a.length; i++) {
dif |= (a[i] ^ b[i]);
}
dif = (dif - 1) >>> 31;
return (dif & 1);
}
function printHex(num, len, padlen, block) {
var ret = '', pad = '', i;
for (i=0; i<padlen;i++) pad += '0';
i = 0;
while (i < len) {
var h = num[i].toString(16);
ret += (pad + h).slice(-padlen);
ret += ((i%block) === block-1) ? '\n' : ' ';
i++;
}
console.log(ret);
}
function decodeUTF8(s) {
var i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length);
for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
return b;
}
function chacha20_block_test() {
console.log('chacha20 block test');
var testVectors = [
{
key: '00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12:13:14:15:16:17:18:19:1a:1b:1c:1d:1e:1f',
nonce: '00:00:00:09:00:00:00:4a:00:00:00:00',
counter: 1,
expected: '10 f1 e7 e4 d1 3b 59 15 50 0f dd 1f a3 20 71 c4'+
'c7 d1 f4 c7 33 c0 68 03 04 22 aa 9a c3 d4 6c 4e'+
'd2 82 64 46 07 9f aa 09 14 c2 d7 05 d9 8b 02 a2'+
'b5 12 9c d1 de 16 4e b9 cb d0 83 e8 a2 50 3c 4e'
},
{
key: '00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00'+
'00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00',
nonce: '00 00 00 00 00 00 00 00 00 00 00 00',
counter: 1,
expected: '9f 07 e7 be 55 51 38 7a 98 ba 97 7c 73 2d 08 0d'+
'cb 0f 29 a0 48 e3 65 69 12 c6 53 3e 32 ee 7a ed'+
'29 b7 21 76 9c e6 4e 43 d5 71 33 b0 74 d8 39 d5'+
'31 ed 1f 28 51 0a fb 45 ac e1 0a 1f 4b 79 4d 6f'
},
{
key: '00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00'+
'00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01',
nonce: '00 00 00 00 00 00 00 00 00 00 00 00',
counter: 1,
expected: '3a eb 52 24 ec f8 49 92 9b 9d 82 8d b1 ce d4 dd'+
'83 20 25 e8 01 8b 81 60 b8 22 84 f3 c9 49 aa 5a'+
'8e ca 00 bb b4 a7 3b da d1 92 b5 c4 2f 73 f2 fd'+
'4e 27 36 44 c8 b3 61 25 a6 4a dd eb 00 6c 13 a0'
},
{
key: '00 ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00'+
'00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00',
nonce: '00 00 00 00 00 00 00 00 00 00 00 00',
counter: 2,
expected: '72 d5 4d fb f1 2e c4 4b 36 26 92 df 94 13 7f 32'+
'8f ea 8d a7 39 90 26 5e c1 bb be a1 ae 9a f0 ca'+
'13 b2 5a a2 6c b4 a6 48 cb 9b 9d 1b e6 5b 2c 09'+
'24 a6 6c 54 d5 45 ec 1b 73 74 f4 87 2e 99 f0 96'
},
{
key: '00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00'+
'00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00',
nonce: '00 00 00 00 00 00 00 00 00 00 00 02',
counter: 0,
expected: 'c2 c6 4d 37 8c d5 36 37 4a e2 04 b9 ef 93 3f cd'+
'1a 8b 22 88 b3 df a4 96 72 ab 76 5b 54 ee 27 c7'+
'8a 97 0e 0e 95 5c 14 f3 a8 8e 74 1b 97 c2 86 f7'+
'5f 8f c2 99 e8 14 83 62 fa 19 8a 39 53 1b ed 6d'
}
];
for (var i = 0; i < testVectors.length; i++) {
var key = fromHex(testVectors[i].key),
nonce = fromHex(testVectors[i].nonce),
counter = testVectors[i].counter,
expected = fromHex(testVectors[i].expected),
len = expected.length,
output = new Uint8Array(len);
var ctx = new Chacha20(key, nonce, counter);
ctx.keystream(output, len);
if (bytesEqual(output, expected) !== 1) {
console.log(i, 'ERROR');
} else {
console.log(i, 'OK');
}
}
}
function chacha20_encryption_test() {
console.log('chacha20 encryption test');
var testVectors = [
{
key: '00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00'+
'00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00',
nonce: '00 00 00 00 00 00 00 00 00 00 00 00',
counter: 0,
plaintext: '00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00'+
'00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00'+
'00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00'+
'00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00',
expected: '76 b8 e0 ad a0 f1 3d 90 40 5d 6a e5 53 86 bd 28'+
'bd d2 19 b8 a0 8d ed 1a a8 36 ef cc 8b 77 0d c7'+
'da 41 59 7c 51 57 48 8d 77 24 e0 3f b8 d8 4a 37'+
'6a 43 b8 f4 15 18 a1 1c c3 87 b6 69 b2 ee 65 86'
},
{
key: '00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12:13:14:15:16:17:18:19:1a:1b:1c:1d:1e:1f',
nonce: '00:00:00:00:00:00:00:4a:00:00:00:00',
counter: 1,
plaintext: '4c 61 64 69 65 73 20 61 6e 64 20 47 65 6e 74 6c'+
'65 6d 65 6e 20 6f 66 20 74 68 65 20 63 6c 61 73'+
'73 20 6f 66 20 27 39 39 3a 20 49 66 20 49 20 63'+
'6f 75 6c 64 20 6f 66 66 65 72 20 79 6f 75 20 6f'+
'6e 6c 79 20 6f 6e 65 20 74 69 70 20 66 6f 72 20'+
'74 68 65 20 66 75 74 75 72 65 2c 20 73 75 6e 73'+
'63 72 65 65 6e 20 77 6f 75 6c 64 20 62 65 20 69'+
'74 2e',
expected: '6e 2e 35 9a 25 68 f9 80 41 ba 07 28 dd 0d 69 81'+
'e9 7e 7a ec 1d 43 60 c2 0a 27 af cc fd 9f ae 0b'+
'f9 1b 65 c5 52 47 33 ab 8f 59 3d ab cd 62 b3 57'+
'16 39 d6 24 e6 51 52 ab 8f 53 0c 35 9f 08 61 d8'+
'07 ca 0d bf 50 0d 6a 61 56 a3 8e 08 8a 22 b6 5e'+
'52 bc 51 4d 16 cc f8 06 81 8c e9 1a b7 79 37 36'+
'5a f9 0b bf 74 a3 5b e6 b4 0b 8e ed f2 78 5e 42'+
'87 4d'
},
{
key: '1c 92 40 a5 eb 55 d3 8a f3 33 88 86 04 f6 b5 f0'+
'47 39 17 c1 40 2b 80 09 9d ca 5c bc 20 70 75 c0',
nonce: '00 00 00 00 00 00 00 00 00 00 00 02',
counter: 42,
plaintext: '27 54 77 61 73 20 62 72 69 6c 6c 69 67 2c 20 61'+
'6e 64 20 74 68 65 20 73 6c 69 74 68 79 20 74 6f'+
'76 65 73 0a 44 69 64 20 67 79 72 65 20 61 6e 64'+
'20 67 69 6d 62 6c 65 20 69 6e 20 74 68 65 20 77'+
'61 62 65 3a 0a 41 6c 6c 20 6d 69 6d 73 79 20 77'+
'65 72 65 20 74 68 65 20 62 6f 72 6f 67 6f 76 65'+
'73 2c 0a 41 6e 64 20 74 68 65 20 6d 6f 6d 65 20'+
'72 61 74 68 73 20 6f 75 74 67 72 61 62 65 2e',
expected: '62 e6 34 7f 95 ed 87 a4 5f fa e7 42 6f 27 a1 df'+
'5f b6 91 10 04 4c 0d 73 11 8e ff a9 5b 01 e5 cf'+
'16 6d 3d f2 d7 21 ca f9 b2 1e 5f b1 4c 61 68 71'+
'fd 84 c5 4f 9d 65 b2 83 19 6c 7f e4 f6 05 53 eb'+
'f3 9c 64 02 c4 22 34 e3 2a 35 6b 3e 76 43 12 a6'+
'1a 55 32 05 57 16 ea d6 96 25 68 f8 7d 3f 3f 77'+
'04 c6 a8 d1 bc d1 bf 4d 50 d6 15 4b 6d a7 31 b1'+
'87 b5 8d fd 72 8a fa 36 75 7a 79 7a c1 88 d1'
},
];
for (var i = 0; i < testVectors.length; i++) {
var key = fromHex(testVectors[i].key),
nonce = fromHex(testVectors[i].nonce),
counter = testVectors[i].counter,
plaintext = fromHex(testVectors[i].plaintext),
expected = fromHex(testVectors[i].expected),
len = plaintext.length,
buf = new Uint8Array(len),
output = new Uint8Array(len);
var ctx = new Chacha20(key, nonce, counter);
ctx.keystream(buf, len);
for (var j = 0; j < len; j++) {
output[j] = buf[j] ^ plaintext[j];
}
if (bytesEqual(output, expected) !== 1) {
console.log(i, 'ERROR');
} else {
console.log(i, 'OK');
}
}
}
chacha20_block_test();
chacha20_encryption_test();
});
});

11
unit02_symmetric/src/package-lock.json generated Normal file
View File

@@ -0,0 +1,11 @@
{
"requires": true,
"lockfileVersion": 1,
"dependencies": {
"chacha20": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/chacha20/-/chacha20-0.1.4.tgz",
"integrity": "sha1-CuFHSawjxESRL9xIKWhGFkn2nhg="
}
}
}

85
unit03_hashing/README.md Normal file
View File

@@ -0,0 +1,85 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
# Unit 3: Hashing and MAC
The key concepts are: MD2. MD4. MD5. SHA-1. Salting. Collisions. Murmur and FNV. Bloom Filter. LM Hash. SHA-3. Bcrypt. PBKDF2. Open SSL Hash passwords. One Time Passwords. Timed One Time Password (TOTP). Hashed One Time Password (HOTP). HMAC.
## What you should know at the end of unit?
* How the lengths of the hashes vary with the number of bits in the hash.
* How we can calculate the strengths on passwords.
* Understand how salt is applied to the hashing process.
* Define how collisions can occur within hashing.
* Implement hash cracking methods (John the Ripper and Hashcat).
* Defines the usage of signed hashes (eg HMAC).
* Outlines the usage of OTP and Timed Passwords.
## Presentations
* Week 3 Presentation (PDF) - Hashing: [here](https://github.com/billbuchanan/esecurity/blob/master/unit03_hashing/lecture/chapter03_hashing_authentication.pdf)
* Week 3 Presentation (video) - Hashing: [here](https://youtu.be/3D11YGD4vFQ)
* Week 3 Presentation (live lecture) - Hashing: [here](https://youtu.be/gh2CI5m2W6Y)
## Lab
* Unit 3 Lab (PDF): [here](https://github.com/billbuchanan/esecurity/blob/master/unit03_hashing/lab/new_lab03.pdf)
* Unit 3 Lab (video): [here](https://www.youtube.com/watch?v=rnTLr6iUbf0)
* Unit 3 Lab Part 2 (video): [here](https://www.youtube.com/watch?v=FKO6Pjsbp3g)
## Tests
* Test (Hash Encryption): [here](https://asecuritysite.com/tests/tests?sortBy=cryptobook03)
## Sample Exam Questions
The following are some sample questions for hashing:
* Outline the importance of storing the salt value with the hashed value when storing hashed passwords.
* Bob is using a password to generate a 128-bit encryption key. Explain why the key space is unlikely to be 2<sup>128</sup>, and why key entropy could be used to measure the equivalent key size.
* Where would I find this info? This is related to key enthropy [here](https://asecuritysite.com//encryption/en), and try and understand how key enthopy relates to the strengh of the encryption.
* Bob has just produced a key pair, in a Base-64 format, and now wants to send this to Alice. What advice would you give him on sending the key pair to Alice?
* Where would I find this info? Have a think about the certificate which is distributed. You can observe it here.
* Bob sends an encrypted message to Alice, and also sends his digital certificate to Alice to prove his identity. How does Alice prove that it is Bob who sent the message?
* Eve has captured a hashed password. How might she use the Cloud to be able to crack the hashed password, and what is a likely too for this?
* Where would I find this info? This [article](https://www.linkedin.com/pulse/quantum-v-supercomp-cloud-gpu-race-ultimate-cracking-william-buchanan) outlines a number of methods which might be used, included within Cloud cracking.
* Bob is an administrator for a network, and he tells his management team that user passwords are now salted, and they are thus completely secure against attacks. Is he correct? Explain your viewpoint.
* Where would I find this info? Have a read of the following [article](https://www.linkedin.com/pulse/salting-password-only-secure-when-you-keep-salt-secret-buchanan?forceNoSplash=true).
* Bob looks at the passwd file on his server, and wants to know the type of salting that is used. How would he do this?
* Where would I find this info? Have a quick look at the additional lab on [Software Hashes](https://asecuritysite.com/lab04_software_hash.pdf). If you can get the Python script to run in Section G, you'll see them all.
* Bob is looking for a new hashing method for storing passwords, and thinks that he will pick the fastest one. Is this a good approach? Explain your answer.
* Where would I find this info? Think about whether being fast for hashing is a good idea. Have a look at this [article](https://www.linkedin.com/pulse/when-slow-good-great-slowcoach-bcrypt-william-buchanan). But make up your own mind on the subject.
* What are the typical tools that are used to crack hashed password, and what are the methods they will use to crack them?
* Where would I find this info? Unit 3 and [Lab 2](https://asecuritysite.com/lab03_hashing_and_certs.pdf).
* Why would Eve have an aversion to salt?
* A password is defined as [a-z]. For a four character password, show that there are 456,976 different passwords.
* Where would I find this info? Have a look [here](https://asecuritysite.com/encryption/passes).
* A password is defined as [a-zA-Z]. For a four character password, show that there are 7,311,616 different passwords.
* Where would I find this info? Have a look [here](https://asecuritysite.com/encryption/passes).
* A password is defined as [a-zA-Z0-9]. For a four character password, show that there are 14,776,336 different passwords.
* Where would I find this info? Have a look [here](https://asecuritysite.com/encryption/passes).
* You are working with a security consultant, and he says that you don't need to check the hashing of passwords, as it should work without testing. You disagree with him, and decide to test your hashing method. Initially you must find test vectors for MD5, SHA-1 and SHA-256. Can you find three test vectors, and test them against an on-line calculator?
* At a security presentation a researcher gives a demonstration of Scrypt. In the presentation he shows a demonstration with a password of "password" and fixed salt of "NaCl". For each run he runs the hashing function, the hashed value changes, but, each time, the computation took longer. Which parameter is the researcher likely to be changing, and why does that parameter exist? Can the researcher select any value for the parameter? [Example](https://asecuritysite.com/encryption/scrypt).
* There has been a major data breach within your company, and you are to appear on Sky News to report it. Your company has used PBKDF2 to hash its passwords. How do you explain to your customers that their passwords are unlikely to be breached?
* It was stated in the recent Yahoo hack that:
"We have confirmed, based on a recent investigation, that a copy of certain user account information was stolen from our networks in late 2014 by what we believe is a state-sponsored actor," Lord wrote. "The account information may have included names, e-mail addresses, telephone numbers, dates of birth, hashed passwords (the vast majority with bcrypt), and, in some cases, encrypted or unencrypted security questions and answers."
Do you think the vast majority of the hashed passwords will be cracked? Do you think they had good practice in place for hashed passwords?
## Addendum
In the lecture, the slide at the end of Unit 2 (Symmetric Key) should be (for an eight character password and with [a-z]):
![](https://asecuritysite.com/public/unit02_update.png)
## Important points
* [BCrypt](https://asecuritysite.com/encryption/bcrypt), [PBKDF2](https://asecuritysite.com/encryption/PBKDF2_2) and [Scrypt](https://asecuritysite.com/encryption/Scrypt) are slow hashing methods, which also have salt, and are highly recommended for password storage.
* The strength of the encryption implementation is measured by key entropy. Anything less than 72 bits is likely to be weak.
## Interested in knowing more?
Hashcat with 8xGPUs in Cloud: [here](https://youtu.be/He_bbEkjF8o)

View File

@@ -0,0 +1,741 @@
# Lab 3: Hashing
Objective: The key objective of this lab is to understand the range of hashing methods used, analyse the strength of each of the methods, and in the usage of salting. Overall the most popular hashing methods are: MD5 (128-bit); SHA-1 (160-bit); SHA-256 (256-bit); SHA-3 (256-bit), bcrypt (192-bit) and PBKDF2 (256-bit). The methods of bcrypt, scrypt and PBKDF2 use a number of rounds, and which significantly reduce the hashing rate. This makes the hashing processes much slower, and thus makes the cracking of hashed passwords more difficult. We will also investigate the key hash cracking tools such as hashcat and John The Ripper.
Open up your Ubuntu instance within vsoc.napier.ac.uk and conduct this lab.
Demo: [here](https://youtu.be/rnTLr6iUbf0)
If required, you can check the hashing methods here: https://asecuritysite.com/encryption/js10
## A Hashing
In this section we will look at some fundamental hashing methods.
### A.1
Using (either on your Windows desktop or on Ubuntu):
Web link (Hashing): http://asecuritysite.com/encryption/md5
Match the hash signatures with their words (“Falkirk”, “Edinburgh”, “Glasgow” and “Stirling”).
<pre>
03CF54D8CE19777B12732B8C50B3B66F
D586293D554981ED611AB7B01316D2D5
48E935332AADEC763F2C82CDB4601A25
EE19033300A54DF2FA41DB9881B4B723
</pre>
03CF5: Is it [Falkirk][Edinburgh][Glasgow][Stirling]?
D5862: Is it [Falkirk][Edinburgh][Glasgow][Stirling]?
48E93: Is it [Falkirk][Edinburgh][Glasgow][Stirling]?
EE190: Is it [Falkirk][Edinburgh][Glasgow][Stirling]?
### A.2
Repeat Part 1, but now use openssl, such as:
<pre>
echo -n 'Falkirk' | openssl md5
</pre>
03CF5: Is it [Falkirk][Edinburgh][Glasgow][Stirling]?
D5862: Is it [Falkirk][Edinburgh][Glasgow][Stirling]?
48E93: Is it [Falkirk][Edinburgh][Glasgow][Stirling]?
EE190: Is it [Falkirk][Edinburgh][Glasgow][Stirling]?
### A.3
Using:
Web link (Hashing): http://asecuritysite.com/encryption/md5
Determine the number of hex characters in the following hash signatures.
MD5 hex chars:
SHA-1 hex chars:
SHA-256 hex chars:
SHA-384 hex chars:
SHA-512 hex chars:
How does the number of hex characters relate to the length of the hash signature:
### A.4
For the following /etc/shadow file, determine the matching password:
<pre>
bill:$apr1$waZS/8Tm$jDZmiZBct/c2hysERcZ3m1
mike:$apr1$mKfrJquI$Kx0CL9krmqhCu0SHKqp5Q0
fred:$apr1$Jbe/hCIb$/k3A4kjpJyC06BUUaPRKs0
ian:$apr1$0GyPhsLi$jTTzW0HNS4Cl5ZEoyFLjB.
jane: $1$rqOIRBBN$R2pOQH9egTTVN1Nlst2U7.
</pre>
[Hint: openssl passwd -apr1 -salt ZaZS/8TF napier]
The passwords are password, napier, inkwell and Ankle123.
Bills password:
Mikes password:
Freds password:
Ians password:
Janes password:
### A.5
From Ubuntu, download the following:
Web link (Files): http://asecuritysite.com/files02.zip
and the files should have the following MD5 signatures:
<pre>
MD5(1.txt)= 5d41402abc4b2a76b9719d911017c592
MD5(2.txt)= 69faab6268350295550de7d587bc323d
MD5(3.txt)= fea0f1f6fede90bd0a925b4194deac11
MD5(4.txt)= d89b56f81cd7b82856231e662429bcf2
</pre>
Which file(s) have been modified?
### A.6
From Ubuntu, download the following ZIP file:
Web link (PS Files): http://asecuritysite.com/letters.zip
On your Ubuntu instance, you should be able to view the files by double clicking on them in the file explorer (as you should have a PostScript viewer installed).
Do the files have different contents?
Now determine the MD5 signature for them. What can you observe from the result?
## B Hash Cracking (Hashcat)
### B.1
Run the hashcat benchmark (eg hashcat b -m 0), and complete the following:
Hash rate for MD5:
Hash rate for SHA-1:
Hash rate for SHA-256:
Hash rate for APR1:
### B.2
On Ubuntu, next create a word file (words) with the words of “napier”, “password” “Ankle123” and “inkwell”
Using hashcat crack the following MD5 signatures (hash1):
<pre>
232DD5D7274E0D662F36C575A3BD634C
5F4DCC3B5AA765D61D8327DEB882CF99
6D5875265D1979BDAD1C8A8F383C5FF5
04013F78ACCFEC9B673005FC6F20698D
</pre?
Command used:
<pre>
hashcat m 0 hash1 words
</pre>
232DD...634C Is it [napier][password][Ankle123][inkwell]?
5F4DC...CF99 Is it [napier][password][Ankle123][inkwell]?
6D587...5FF5 Is it [napier][password][Ankle123][inkwell]?
04013...698D Is it [napier][password][Ankle123][inkwell]?
### B.3
Using the method used in the first part of this tutorial, find crack the following for names of fruits (the fruits are all in lowercase):
<pre>
FE01D67A002DFA0F3AC084298142ECCD
1F3870BE274F6C49B3E31A0C6728957F
72B302BF297A228A75730123EFEF7C41
8893DC16B1B2534BAB7B03727145A2BB
889560D93572D538078CE1578567B91A
</pre>
FE01D:
1F387:
72B30:
8893D:
88956:
### B.4
We have hashed a SHA-256 value of the following and put it into a file named
file.txt:
<pre>
106a5842fc5fce6f663176285ed1516dbb1e3d15c05abab12fdca46d60b539b7
</pre>
By adding a word of “help” in a word file of words.txt, prove that the following cracks the hash (where file.txt contains the hashed value):
hashcat -m 1400 file.txt words.txt
### B.5
The following is an NTLM hash, for “help”:
<pre>
0333c27eb4b9401d91fef02a9f74840e
</pre>
Prove that the following can crack the hash (where file.txt contains the hashed value):
<pre>
hashcat -m 1000 file.txt words.txt
</pre>
### B.6
Now crack the following Scottish football teams (all are single words):
<pre>
635450503029fc2484f1d7eb80da8e25bdc1770e1dd14710c592c8929ba37ee9
b3cb6d04f9ccbf6dfe08f40c11648360ca421f0c531e69f326a72dc7e80a0912
bc5fb9abe8d5e72eb49cf00b3dbd173cbf914835281fadd674d5a2b680e47d50
6ac16a68ac94ca8298c9c2329593a4a4130b6fed2472a98424b7b4019ef1d968
</pre>
Football teams:
### B.7
Rather than use a dictionary, we can use a brute force a hashed password using a lowercase character set:
<pre>
hashcat -a 3 -m 1400 file.txt ?l?l?l?l?l?l?l?l --increment
</pre>
Using this style of command (look at the hash type and perhaps this is a SHA-256 hash), crack the following words:
<pre>
4dc2159bba05da394c3b94c6f54354db1f1f43b321ac4bbdfc2f658237858c70
0282d9b79f42c74c1550b20ff2dd16aafc3fe5d8ae9a00b2f66996d0ae882775
47c215b5f70eb9c9b4bcb2c027007d6cf38a899f40d1d1da6922e49308b15b69
</pre>
Words:
Number of tests for each sequence tried:
What happens when you take the “--increment” flag away?
## B.8
We can focus on given letters, such as where we add a letter or a digit at the end:
<pre>
hashcat -a 3 -m 1000 file.txt password?l
hashcat -a 3 -m 1000 file.txt password?u
hashcat -a 3 -m 1000 file.txt password?d
</pre>
Using these commands, crack the following:
<pre>
7a6c8de8ad7f89b922cc29c9505f58c3
db0edd04aaac4506f7edab03ac855d56
</pre>
Note: Remember to try both MD5 (0) and NTLM hash (1000).
Words:
Number of tests for each:
## C Hashing Cracking (John The Ripper)
All of the passwords in this section are in lowercase.
### C.1
On Ubuntu, and using John the Ripper, and using a word list with the names of fruits, crack the following pwdump passwords:
<pre>
fred:500:E79E56A8E5C6F8FEAAD3B435B51404EE:5EBE7DFA074DA8EE8AEF1FAA2BBDE876:::
bert:501:10EAF413723CBB15AAD3B435B51404EE:CA8E025E9893E8CE3D2CBF847FC56814:::
</pre>
Fred:
Bert:
### C.2
On Ubuntu, and using John the Ripper, the following pwdump passwords (they are names of major Scottish cities/towns):
<pre>
Admin:500:629E2BA1C0338CE0AAD3B435B51404EE:9408CB400B20ABA3DFEC054D2B6EE5A1:::
fred:501:33E58ABB4D723E5EE72C57EF50F76A05:4DFC4E7AA65D71FD4E06D061871C05F2:::
bert:502:BC2B6A869601E4D9AAD3B435B51404EE:2D8947D98F0B09A88DC9FCD6E546A711:::
</pre>
Admin:
Fred:
Bert:
### C.3
On Ubuntu, and using John the Ripper, crack the following pwdump passwords (they are the names of animals):
<pre>
fred:500:5A8BB08EFF0D416AAAD3B435B51404EE:85A2ED1CA59D0479B1E3406972AB1928:::
bert:501:C6E4266FEBEBD6A8AAD3B435B51404EE:0B9957E8BED733E0350C703AC1CDA822:::
admin:502:333CB006680FAF0A417EAF50CFAC29C3:D2EDBC29463C40E76297119421D2A707:::
</pre>
Fred:
Bert:
Admin:
## D LM Hash
The LM Hash is used in Microsoft Windows. For example, for LM Hash:
hashme gives: FA-91-C4-FD-28-A2-D2-57-AA-D3-B4-35-B5-14-04-EE
network gives: D7-5A-34-5D-5D-20-7A-00-AA-D3-B4-35-B5-14-04-EE
napier gives: 12-B9-C5-4F-6F-E0-EC-80-AA-D3-B4-35-B5-14-04-EE
Notice that the right-most element of the hash are always the same, if the password is less than eight characters. With more than eight characters we get:
networksims gives: D7-5A-34-5D-5D-20-7A-00-38-32-A0-DB-BA-51-68-07
napier123 gives: 67-82-2A-34-ED-C7-48-92-B7-5E-0C-8D-76-95-4A-50
For “hello” we get:
<pre>
LM: FD-A9-5F-BE-CA-28-8D-44-AA-D3-B4-35-B5-14-04-EE
NTLM: 06-6D-DF-D4-EF-0E-9C-D7-C2-56-FE-77-19-1E-F4-3C
</pre>
We can check these with a Python script:
```python
import passlib.hash;
string="hello"
print "LM Hash:"+passlib.hash.lmhash.encrypt(string)
print "NT Hash:"+passlib.hash.nthash.encrypt(string)
```
which gives:
LM Hash:fda95fbeca288d44aad3b435b51404ee
NT Hash:066ddfd4ef0e9cd7c256fe77191ef43c
Web link (LM Hash): http://asecuritysite.com/encryption/lmhash
### D.1
Create a Python script to determine the LM hash and NTLM hash of the following words:
“Napier”
“Foxtrot”
## E APR1
The Apache-defined APR1 format addresses the problems of brute forcing an MD5 hash, and basically iterates over the hash value 1,000 times. This considerably slows an intruder as they try to crack the hashed value. The resulting hashed string contains “$apr1$” to identify it and uses a 32-bit salt value. We can use both htpassword and Openssl to compute the hashed string (where “bill” is the user and “hello” is the password):
<pre>
# htpasswd -nbm bill hello
bill:$apr1$PkWj6gM4$XGWpADBVPyypjL/cL0XMc1
# openssl passwd -apr1 -salt PkWj6gM4 hello
$apr1$PkWj6gM4$XGWpADBVPyypjL/cL0XMc1
</pre>
We can also create a simple Python program with the passlib library, and add the same salt as the example above:
```python
import passlib.hash;
salt="PkWj6gM4"
string="hello"
print "APR1:"+passlib.hash.apr_md5_crypt.encrypt(string, salt=salt)
```
We can created a simple Python program with the passlib library, and add the same salt as the example above:
<pre>
APR1:$apr1$PkWj6gM4$XGWpADBVPyypjL/cL0XMc1
</pre>
Refer to: http://asecuritysite.com/encryption/apr1
### E.1
Create a Python script to create the APR1 hash for the following:
Prove them against on-line APR1 generator (or from the page given above).
“changeme”:
“123456”:
“password”
## F SHA
While APR1 has a salted value, the SHA-1 hash does not have a salted value. It produces a 160-bit signature, thus can contain a larger set of hashed value than MD5, but because there is no salt it can be cracked to rainbow tables, and also brute force. The format for the storage of the hashed password on Linux systems is:
<pre>
# htpasswd -nbs bill hello
bill:{SHA}qvTGHdzF6KLavt4PO0gs2a6pQ00=
</pre>
We can also generate salted passwords with crypt, and can use the Python script of:
```python
import passlib.hash;
salt="8sFt66rZ"
string="hello"
print "SHA1:"+passlib.hash.sha1_crypt.encrypt(string, salt=salt)
print "SHA256:"+passlib.hash.sha256_crypt.encrypt(string, salt=salt)
print "SHA512:"+passlib.hash.sha512_crypt.encrypt(string, salt=salt)
```
SHA-512 salts start with $6$ and are up to 16 chars long.
SHA-256 salts start with $5$ and are up to 16 chars long.
Which produces:
<pre>
SHA1:$sha1$480000$8sFt66rZ$klAZf7IPWRN1ACGNZIMxxuVaIKRj
SHA256:$5$rounds=535000$8sFt66rZ$.YYuHL27JtcOX8WpjwKf2VM876kLTGZHsHwCBbq9xTD
SHA512:$6$rounds=656000$8sFt66rZ$aMTKQHl60VXFjiDAsyNFxn4gRezZOZarxHaK.TcpVYLpMw6MnX0lyPQU06SSVmSdmF/VNbvPkkMpOEONvSd5Q1
</pre>
### F.1 Create a Python script to create the SHA hash for the following:
Prove them against on-line SHA generator (or from the page given above).
“changeme”:
“123456”:
“password”
## G PBKDF2
PBKDF2 (Password-Based Key Derivation Function 2) is defined in RFC 2898 and generates a salted hash. Often this is used to create an encryption key from a defined password, and where it is not possible to reverse the password from the hashed value. It is used in TrueCrypt to generate the key required to read the header information of the encrypted drive, and which stores the encryption keys.
PBKDF2 is used in WPA-2 and TrueCrypt. Its main focus is to produced a hashed version of a password and includes a salt value to reduce the opportunity for a rainbow table attack. It generally uses over 1,000 iterations in order to slow down the creation of the hash, so that it can overcome brute force attacks. The generalise format for PBKDF2 is:
<pre>
DK = PBKDF2(Password, Salt, MInterations, dkLen)
</pre>
where Password is the pass phrase, Salt is the salt, MInterations is the number of iterations, and dklen is the length of the derived hash.In WPA-2, the IEEE 802.11i standard defines that the pre-shared key is defined by:
<pre>
PSK = PBKDF2(PassPhrase, ssid, ssidLength, 4096, 256)
</pre>
In TrueCrypt we use PBKDF2 to generate the key (with salt) and which will decrypt the header, and reveal the keys which have been used to encrypt the disk (using AES, 3DES or Twofish). We use:
```python
byte[] result = passwordDerive.GenerateDerivedKey(16,
ASCIIEncoding.UTF8.GetBytes(message), salt, 1000);
```
which has a key length of 16 bytes (128 bits - dklen), uses a salt byte array, and 1000 iterations of the hash (Minterations). The resulting hash value will have 32 hexadecimal characters (16 bytes).
Web link (PBKDF2): http://www.asecuritysite.com/encryption/PBKDF2
```python
import hashlib;
import passlib.hash;
import sys;
salt="ZDzPE45C"
string="password"
if (len(sys.argv)>1):
string=sys.argv[1]
if (len(sys.argv)>2):
salt=sys.argv[2]
print "PBKDF2 (SHA1):"+passlib.hash.pbkdf2_sha1.encrypt(string, salt=salt)
print "PBKDF2 (SHA256):"+passlib.hash.pbkdf2_sha256.encrypt(string, salt=salt)
```
### G.1
Create a Python script to create the PBKDF2 hash for the following (uses a salt value of “ZDzPE45C”). You just need to list the first six hex characters of the hashed value.
“changeme”:
“123456”:
“password”
## H Bcrypt
MD5 and SHA-1 produce a hash signature, but this can be attacked by rainbow tables. Bcrypt (Blowfish Crypt) is a more powerful hash generator for passwords and uses salt to create a non-recurrent hash. It was designed by Niels Provos and David Mazières, and is based on the Blowfish cipher. It is used as the default password hashing method for BSD and other systems.
Overall it uses a 128-bit salt value, which requires 22 Base-64 characters. It can use a number of iterations, which will slow down any brute-force cracking of the hashed value. For example, “Hello” with a salt value of “$2a$06$NkYh0RCM8pNWPaYvRLgN9.” gives:
<pre>
$2a$06$NkYh0RCM8pNWPaYvRLgN9.LbJw4gcnWCOQYIom0P08UEZRQQjbfpy
</pre>
As illustrated in Figure 1, the first part is "$2a$" (or "$2b$"), and then followed by the number of rounds used. In this case is it 6 rounds which is 2<sup>6</sup> iterations (where each additional round doubles the hash time). The 128-bit (22 character) salt values comes after this, and then finally there is a 184-bit hash code (which is 31 characters).
The slowness of bcrypt is highlighted with an AWS EC2 server benchmark using hashcat:
* Hash type: MD5 Speed/sec: 380.02M words
* Hash type: SHA1 Speed/sec: 218.86M words
* Hash type: SHA256 Speed/sec: 110.37M words
* Hash type: bcrypt, Blowfish(OpenBSD) Speed/sec: 25.86k words
* Hash type: NTLM. Speed/sec: 370.22M words
You can see that Bcrypt is almost 15,000 times slower than MD5 (380,000,000 words/sec down to only 25,860 words/sec). With John The Ripper:
* md5crypt [MD5 32/64 X2] 318237 c/s real, 8881 c/s virtual
* bcrypt ("$2a$05", 32 iterations) 25488 c/s real, 708 c/s virtual
* LM [DES 128/128 SSE2-16] 88090K c/s real, 2462K c/s virtual
where you can see that BCrypt over 3,000 times slower than LM hashes. So, although the main hashing methods are fast and efficient, this speed has a down side, in that they can be cracked easier. With Bcrypt the speed of cracking is considerably slowed down, with each iteration doubling the amount of time it takes to crack the hash with brute force. If we add one onto the number of rounds, we double the time taken for the hashing process. So, to go from 6 to 16 increase by over 1,000 (210) and from 6 to 26 increases by over 1 million (220).
The following defines a Python script which calculates a whole range of hashes:
```python
import hashlib;
import passlib.hash;
salt="ZDzPE45C"
string="password"
salt2="1111111111111111111111"
print "General Hashes"
print "MD5:"+hashlib.md5(string).hexdigest()
print "SHA1:"+hashlib.sha1(string).hexdigest()
print "SHA256:"+hashlib.sha256(string).hexdigest()
print "SHA512:"+hashlib.sha512(string).hexdigest()
print "UNIX hashes (with salt)"
print "DES:"+passlib.hash.des_crypt.encrypt(string, salt=salt[:2])
print "MD5:"+passlib.hash.md5_crypt.encrypt(string, salt=salt)
print "Sun MD5:"+passlib.hash.sun_md5_crypt.encrypt(string, salt=salt)
print "SHA1:"+passlib.hash.sha1_crypt.encrypt(string, salt=salt)
print "SHA256:"+passlib.hash.sha256_crypt.encrypt(string, salt=salt)
print "SHA512:"+passlib.hash.sha512_crypt.encrypt(string, salt=salt)
print "Bcrypt:"+passlib.hash.bcrypt.encrypt(string, salt=salt2[:22])
```
Figure 1Bcrypt
### H.1
Create the hash for the word “hello” for the different methods (you only have to give the first six hex characters for the hash):
Also note the number hex characters that the hashed value uses:
MD5:
SHA1:
SHA256:
SHA512:
DES:
MD5:
Sun MD5:
SHA-1:
SHA-256:
SHA-512:
## I HMAC
Write a Python or Node.js program which will prove the following:
<pre>
Type: HMAC-MD5
Message: Hello
Password: qwerty123
Hex: c3a2fa8f20dee654a32c30e666cec48e
Base64: 7376b67daf1fdb475e7bae786b7d9cdf47baeba71e738f1e
</pre>
If you get this to work, can you expand to include other MAC methods. You can test against this page:
https://asecuritysite.com/encryption/js10
## J Reflective statements
1. Why might increasing the number of iterations be a better method of protecting a hashed password than using a salted version?
2. Why might the methods bcrypt, Phpass and PBFDK2 be preferred for storing passwords than MD5, SHA?
## K What I should have learnt from this lab?
The key things learnt:
* The differing methods used to hash data.
* How hashcat and John The Ripper are used to crack hashed values.
* How salt is added to the hashing process.
* The core difference between the fast hashing methods (such as MD5 and SHA-1) and the slow ones (bcrypt and PBKDF2).
## L Additional
The following provides a hash most of the widely used hashing method. For this enter the code of:
```python
import hashlib;
import passlib.hash;
import sys;
salt="ZDzPE45C"
string="password"
salt2="1111111111111111111111"
if (len(sys.argv)>1):
string=sys.argv[1]
if (len(sys.argv)>2):
salt=sys.argv[2]
print "General Hashes"
print "MD5:"+hashlib.md5(string).hexdigest()
print "SHA1:"+hashlib.sha1(string).hexdigest()
print "SHA256:"+hashlib.sha256(string).hexdigest()
print "SHA512:"+hashlib.sha512(string).hexdigest()
print "UNIX hashes (with salt)"
print "DES:"+passlib.hash.des_crypt.encrypt(string, salt=salt[:2])
print "MD5:"+passlib.hash.md5_crypt.encrypt(string, salt=salt)
print "Sun MD5:"+passlib.hash.sun_md5_crypt.encrypt(string, salt=salt)
print "SHA1:"+passlib.hash.sha1_crypt.encrypt(string, salt=salt)
print "SHA256:"+passlib.hash.sha256_crypt.encrypt(string, salt=salt)
print "SHA512:"+passlib.hash.sha512_crypt.encrypt(string, salt=salt)
print "APR1:"+passlib.hash.apr_md5_crypt.encrypt(string, salt=salt)
print "PHPASS:"+passlib.hash.phpass.encrypt(string, salt=salt)
print "PBKDF2 (SHA1):"+passlib.hash.pbkdf2_sha1.encrypt(string, salt=salt)
print "PBKDF2 (SHA256):"+passlib.hash.pbkdf2_sha256.encrypt(string, salt=salt)
#print "PBKDF2 (SHA512):"+passlib.hash.pbkdf2_sha512.encrypt(string, salt=salt)
#print "CTA PBKDF2:"+passlib.hash.cta_pbkdf2_sha1.encrypt(string, salt=salt)
#print "DLITZ PBKDF2:"+passlib.hash.dlitz_pbkdf2_sha1.encrypt(string, salt=salt)
print "MS Windows Hashes"
print "LM Hash:"+passlib.hash.lmhash.encrypt(string)
print "NT Hash:"+passlib.hash.nthash.encrypt(string)
print "MS DCC:"+passlib.hash.msdcc.encrypt(string, salt)
print "MS DCC2:"+passlib.hash.msdcc2.encrypt(string, salt)
#print "LDAP Hashes"
#print "LDAP (MD5):"+passlib.hash.ldap_md5.encrypt(string)
#print "LDAP (MD5 Salted):"+passlib.hash.ldap_salted_md5.encrypt(string, salt=salt)
#print "LDAP (SHA):"+passlib.hash.ldap_sha1.encrypt(string)
#print "LDAP (SHA1 Salted):"+passlib.hash.ldap_salted_sha1.encrypt(string, salt=salt)
#print "LDAP (DES Crypt):"+passlib.hash.ldap_des_crypt.encrypt(string)
#print "LDAP (BSDI Crypt):"+passlib.hash.ldap_bsdi_crypt.encrypt(string)
#print "LDAP (MD5 Crypt):"+passlib.hash.ldap_md5_crypt.encrypt(string)
#print "LDAP (Bcrypt):"+passlib.hash.ldap_bcrypt.encrypt(string)
#print "LDAP (SHA1):"+passlib.hash.ldap_sha1_crypt.encrypt(string)
#print "LDAP (SHA256):"+passlib.hash.ldap_sha256_crypt.encrypt(string)
#print "LDAP (SHA512):"+passlib.hash.ldap_sha512_crypt.encrypt(string)
print "LDAP (Hex MD5):"+passlib.hash.ldap_hex_md5.encrypt(string)
print "LDAP (Hex SHA1):"+passlib.hash.ldap_hex_sha1.encrypt(string)
print "LDAP (At Lass):"+passlib.hash.atlassian_pbkdf2_sha1.encrypt(string)
print "LDAP (FSHP):"+passlib.hash.fshp.encrypt(string)
print "Database Hashes"
print "MS SQL 2000:"+passlib.hash.mssql2000.encrypt(string)
print "MS SQL 2000:"+passlib.hash.mssql2005.encrypt(string)
print "MS SQL 2000:"+passlib.hash.mysql323.encrypt(string)
print "MySQL:"+passlib.hash.mysql41.encrypt(string)
print "Postgres (MD5):"+passlib.hash.postgres_md5.encrypt(string, user=salt)
print "Oracle 10:"+passlib.hash.oracle10.encrypt(string, user=salt)
print "Oracle 11:"+passlib.hash.oracle11.encrypt(string)
print "Other Known Hashes"
print "Cisco PIX:"+passlib.hash.cisco_pix.encrypt(string, user=salt)
print "Cisco Type 7:"+passlib.hash.cisco_type7.encrypt(string)
print "Dyango DES:"+passlib.hash.django_des_crypt.encrypt(string, salt=salt)
print "Dyango MD5:"+passlib.hash.django_salted_md5.encrypt(string, salt=salt[:2])
print "Dyango SHA1:"+passlib.hash.django_salted_sha1.encrypt(string, salt=salt)
print "Dyango Bcrypt:"+passlib.hash.django_bcrypt.encrypt(string, salt=salt2[:22])
print "Dyango PBKDF2 SHA1:"+passlib.hash.django_pbkdf2_sha1.encrypt(string, salt=salt)
print "Dyango PBKDF2 SHA1:"+passlib.hash.django_pbkdf2_sha256.encrypt(string, salt=salt)
print "Bcrypt:"+passlib.hash.bcrypt.encrypt(string, salt=salt2[:22])
```
## L.1
In the code, what does the modifier of “[:22]” do?
In running the methods, which of them take the longest time to compute?
Of the methods used, outline how you would identify some of the methods. For APR1 has an identifier of $apr1$.
For the following identify the hash methods used:
* 5f4dcc3b5aa765d61d8327deb882cf99
* 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8
* $apr1$ZDzPE45C$y372GZYCbB1WYtOkbm4/u.
* $P$HZDzPE45Ch4tvOeT9mhtu3i2G/JybR1
* b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86
* $1$ZDzPE45C$EEQHJaCXI6yInV3FnskmF1
* $2a$12$111111111111111111111uAQxS9vJNRtBb6zeFDV6k7tyB0DZJF0a
## L.2
It is known that a user has used a password of “passXord”, where X is an unknown character or number. Can crack the following hashes based on a filter:
<pre>
5fa8051ada600a097bd0922d7a085b94734684c4e070b24a02cf43d24d6eedbe
a6f63a5fb10b3bba180a79f2fc565b1db2101040ce71ea80692d671857fe2117
</pre>
Passwords used:
Number of tests:
## L.3
Download the bfield.hash password hash, and using the rockyou.txt list, determine the first 10 passwords in the hashed file. An example command might be:
<pre>
hashcat -m 0 bfield.hash /usr/share/wordlists/rockyou.txt
</pre>
First 10 passwords from bfield.hash:

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,41 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
# 3. Hashing and MAC
The key concepts are: MD2. MD4. MD5. SHA-1. Salting. Collisions. Murmur and FNV. Bloom Filter. LM Hash. SHA-3. Bcrypt. PBKDF2. Open SSL Hash passwords. One Time Passwords. Timed One Time Password (TOTP). Hashed One Time Password (HOTP). HMAC.
## What you should know at the end of unit?
* How the lengths of the hashes vary with the number of bits in the hash.
* How we can calculate the strengths on passwords.
* Understand how salt is applied to the hashing process.
* Define how collisions can occur within hashing.
* Implement hash cracking methods (John the Ripper and Hashcat).
* Defines the usage of signed hashes (eg HMAC).
* Outlines the usage of OTP and Timed Passwords.
## What you should know at the end of unit?
* How the lengths of the hashes vary with the number of bits in the hash.
* How we can calculate the strengths on passwords.
* Understand how salt is applied to the hashing process.
* Define how collisions can occur within hashing.
* Implement hash cracking methods (John the Ripper and Hashcat).
* Defines the usage of signed hashes (eg HMAC).
* Outlines the usage of One-time Passwords (OTP) and Timed Passwords.
## Presentations
* Week 3 Presentation (PDF) - Hashing: [here](https://github.com/billbuchanan/esecurity/blob/master/unit03_hashing/lecture/chapter03_hashing_authentication.pdf)
* Week 3 Presentation (video) - Hashing: [here](https://youtu.be/3D11YGD4vFQ)
* Week 3 Presentation (live lecture) - Hashing: [here](https://youtu.be/gh2CI5m2W6Y)
## Videos
The voice over lecture is here:
[![](http://img.youtube.com/vi/3D11YGD4vFQ/0.jpg)](https://www.youtube.com/watch?v=3D11YGD4vFQ "")
And the classroom lecture from 2020 is here:
[![](http://img.youtube.com/vi/gh2CI5m2W6Y/0.jpg)](https://www.youtube.com/watch?v=gh2CI5m2W6Y "")

View File

@@ -0,0 +1,4 @@
03CF54D8CE19777B12732B8C50B3B66F
D586293D554981ED611AB7B01316D2D5
48E935332AADEC763F2C82CDB4601A25
EE19033300A54DF2FA41DB9881B4B723

View File

@@ -0,0 +1 @@
echo -n 'Falkirk' | openssl md5

View File

@@ -0,0 +1,5 @@
bill:$apr1$waZS/8Tm$jDZmiZBct/c2hysERcZ3m1
mike:$apr1$mKfrJquI$Kx0CL9krmqhCu0SHKqp5Q0
fred:$apr1$Jbe/hCIb$/k3A4kjpJyC06BUUaPRKs0
ian:$apr1$0GyPhsLi$jTTzW0HNS4Cl5ZEoyFLjB.
jane: $1$rqOIRBBN$R2pOQH9egTTVN1Nlst2U7.

View File

@@ -0,0 +1,4 @@
MD5(1.txt)= 5d41402abc4b2a76b9719d911017c592
MD5(2.txt)= 69faab6268350295550de7d587bc323d
MD5(3.txt)= fea0f1f6fede90bd0a925b4194deac11
MD5(4.txt)= d89b56f81cd7b82856231e662429bcf2

View File

@@ -0,0 +1 @@
hashcat <20>b -m 0

View File

@@ -0,0 +1,4 @@
232DD5D7274E0D662F36C575A3BD634C
5F4DCC3B5AA765D61D8327DEB882CF99
6D5875265D1979BDAD1C8A8F383C5FF5
04013F78ACCFEC9B673005FC6F20698D

View File

@@ -0,0 +1,5 @@
FE01D67A002DFA0F3AC084298142ECCD
1F3870BE274F6C49B3E31A0C6728957F
72B302BF297A228A75730123EFEF7C41
8893DC16B1B2534BAB7B03727145A2BB
889560D93572D538078CE1578567B91A

View File

@@ -0,0 +1 @@
106a5842fc5fce6f663176285ed1516dbb1e3d15c05abab12fdca46d60b539b7

View File

@@ -0,0 +1 @@
0333c27eb4b9401d91fef02a9f74840e

View File

@@ -0,0 +1,4 @@
635450503029fc2484f1d7eb80da8e25bdc1770e1dd14710c592c8929ba37ee9
b3cb6d04f9ccbf6dfe08f40c11648360ca421f0c531e69f326a72dc7e80a0912
bc5fb9abe8d5e72eb49cf00b3dbd173cbf914835281fadd674d5a2b680e47d50
6ac16a68ac94ca8298c9c2329593a4a4130b6fed2472a98424b7b4019ef1d968

View File

@@ -0,0 +1,3 @@
4dc2159bba05da394c3b94c6f54354db1f1f43b321ac4bbdfc2f658237858c70
0282d9b79f42c74c1550b20ff2dd16aafc3fe5d8ae9a00b2f66996d0ae882775
47c215b5f70eb9c9b4bcb2c027007d6cf38a899f40d1d1da6922e49308b15b69

View File

@@ -0,0 +1,2 @@
7a6c8de8ad7f89b922cc29c9505f58c3
db0edd04aaac4506f7edab03ac855d56

View File

@@ -0,0 +1,2 @@
fred:500:E79E56A8E5C6F8FEAAD3B435B51404EE:5EBE7DFA074DA8EE8AEF1FAA2BBDE876:::
bert:501:10EAF413723CBB15AAD3B435B51404EE:CA8E025E9893E8CE3D2CBF847FC56814:::

View File

@@ -0,0 +1,3 @@
Admin:500:629E2BA1C0338CE0AAD3B435B51404EE:9408CB400B20ABA3DFEC054D2B6EE5A1:::
fred:501:33E58ABB4D723E5EE72C57EF50F76A05:4DFC4E7AA65D71FD4E06D061871C05F2:::
bert:502:BC2B6A869601E4D9AAD3B435B51404EE:2D8947D98F0B09A88DC9FCD6E546A711:::

View File

@@ -0,0 +1,3 @@
fred:500:5A8BB08EFF0D416AAAD3B435B51404EE:85A2ED1CA59D0479B1E3406972AB1928:::
bert:501:C6E4266FEBEBD6A8AAD3B435B51404EE:0B9957E8BED733E0350C703AC1CDA822:::
admin:502::333CB006680FAF0A417EAF50CFAC29C3:D2EDBC29463C40E76297119421D2A707:::

View File

@@ -0,0 +1,5 @@
import passlib.hash;
string="hello"
print ("LM Hash:"+passlib.hash.lmhash.encrypt(string))
print ("NT Hash:"+passlib.hash.nthash.encrypt(string))

View File

@@ -0,0 +1,7 @@
import passlib.hash;
salt="PkWj6gM4"
string="hello"
print ("APR1:"+passlib.hash.apr_md5_crypt.encrypt(string, salt=salt))

View File

@@ -0,0 +1,7 @@
import passlib.hash;
salt="8sFt66rZ"
string="hello"
print ("SHA1:"+passlib.hash.sha1_crypt.encrypt(string, salt=salt))
print ("SHA256:"+passlib.hash.sha256_crypt.encrypt(string, salt=salt))
print ("SHA512:"+passlib.hash.sha512_crypt.encrypt(string, salt=salt))

View File

@@ -0,0 +1,18 @@
import hashlib;
import passlib.hash;
import sys;
salt="ZDzPE45C"
string="password"
if (len(sys.argv)>1):
string=sys.argv[1]
if (len(sys.argv)>2):
salt=sys.argv[2]
print ("PBKDF2 (SHA1):"+passlib.hash.pbkdf2_sha1.encrypt(string, salt=salt.encode()))
print ("PBKDF2 (SHA256):"+passlib.hash.pbkdf2_sha256.encrypt(string, salt=salt.encode()))

View File

@@ -0,0 +1,12 @@
Try:
htpasswd -nbs bill test
bill:{SHA}qUqP5cyxm6YcTAhz05Hph5gvu9M=
https://asecuritysite.com/encryption/md5_2?word=test
import hashlib
import base64
string="test"
print "SHA1:"+base64.b64encode(hashlib.sha1(string).digest())

View File

@@ -0,0 +1,22 @@
import hashlib;
import passlib.hash;
salt="ZDzPE45C"
string="password"
salt2="1111111111111111111111"
print "General Hashes"
print "MD5:"+hashlib.md5(string).hexdigest()
print "SHA1:"+hashlib.sha1(string).hexdigest()
print "SHA256:"+hashlib.sha256(string).hexdigest()
print "SHA512:"+hashlib.sha512(string).hexdigest()
print "UNIX hashes (with salt)"
print "DES:"+passlib.hash.des_crypt.encrypt(string, salt=salt[:2])
print "MD5:"+passlib.hash.md5_crypt.encrypt(string, salt=salt)
print "Sun MD5:"+passlib.hash.sun_md5_crypt.encrypt(string, salt=salt)
print "SHA1:"+passlib.hash.sha1_crypt.encrypt(string, salt=salt)
print "SHA256:"+passlib.hash.sha256_crypt.encrypt(string, salt=salt)
print "SHA512:"+passlib.hash.sha512_crypt.encrypt(string, salt=salt)
print "Bcrypt:"+passlib.hash.bcrypt.encrypt(string, salt=salt2[:22])

View File

@@ -0,0 +1,82 @@
import hashlib;
import passlib.hash;
import sys;
salt="ZDzPE45C"
string="password"
salt2="1111111111111111111111"
if (len(sys.argv)>1):
string=sys.argv[1]
if (len(sys.argv)>2):
salt=sys.argv[2]
print "General Hashes"
print "MD5:"+hashlib.md5(string).hexdigest()
print "SHA1:"+hashlib.sha1(string).hexdigest()
print "SHA256:"+hashlib.sha256(string).hexdigest()
print "SHA512:"+hashlib.sha512(string).hexdigest()
print "UNIX hashes (with salt)"
print "DES:"+passlib.hash.des_crypt.encrypt(string, salt=salt[:2])
print "MD5:"+passlib.hash.md5_crypt.encrypt(string, salt=salt)
print "Sun MD5:"+passlib.hash.sun_md5_crypt.encrypt(string, salt=salt)
print "SHA1:"+passlib.hash.sha1_crypt.encrypt(string, salt=salt)
print "SHA256:"+passlib.hash.sha256_crypt.encrypt(string, salt=salt)
print "SHA512:"+passlib.hash.sha512_crypt.encrypt(string, salt=salt)
print "APR1:"+passlib.hash.apr_md5_crypt.encrypt(string, salt=salt)
print "PHPASS:"+passlib.hash.phpass.encrypt(string, salt=salt)
print "PBKDF2 (SHA1):"+passlib.hash.pbkdf2_sha1.encrypt(string, salt=salt)
print "PBKDF2 (SHA256):"+passlib.hash.pbkdf2_sha256.encrypt(string, salt=salt)
#print "PBKDF2 (SHA512):"+passlib.hash.pbkdf2_sha512.encrypt(string, salt=salt)
#print "CTA PBKDF2:"+passlib.hash.cta_pbkdf2_sha1.encrypt(string, salt=salt)
#print "DLITZ PBKDF2:"+passlib.hash.dlitz_pbkdf2_sha1.encrypt(string, salt=salt)
print "MS Windows Hashes"
print "LM Hash:"+passlib.hash.lmhash.encrypt(string)
print "NT Hash:"+passlib.hash.nthash.encrypt(string)
print "MS DCC:"+passlib.hash.msdcc.encrypt(string, salt)
print "MS DCC2:"+passlib.hash.msdcc2.encrypt(string, salt)
#print "LDAP Hashes"
#print "LDAP (MD5):"+passlib.hash.ldap_md5.encrypt(string)
#print "LDAP (MD5 Salted):"+passlib.hash.ldap_salted_md5.encrypt(string, salt=salt)
#print "LDAP (SHA):"+passlib.hash.ldap_sha1.encrypt(string)
#print "LDAP (SHA1 Salted):"+passlib.hash.ldap_salted_sha1.encrypt(string, salt=salt)
#print "LDAP (DES Crypt):"+passlib.hash.ldap_des_crypt.encrypt(string)
#print "LDAP (BSDI Crypt):"+passlib.hash.ldap_bsdi_crypt.encrypt(string)
#print "LDAP (MD5 Crypt):"+passlib.hash.ldap_md5_crypt.encrypt(string)
#print "LDAP (Bcrypt):"+passlib.hash.ldap_bcrypt.encrypt(string)
#print "LDAP (SHA1):"+passlib.hash.ldap_sha1_crypt.encrypt(string)
#print "LDAP (SHA256):"+passlib.hash.ldap_sha256_crypt.encrypt(string)
#print "LDAP (SHA512):"+passlib.hash.ldap_sha512_crypt.encrypt(string)
print "LDAP (Hex MD5):"+passlib.hash.ldap_hex_md5.encrypt(string)
print "LDAP (Hex SHA1):"+passlib.hash.ldap_hex_sha1.encrypt(string)
print "LDAP (At Lass):"+passlib.hash.atlassian_pbkdf2_sha1.encrypt(string)
print "LDAP (FSHP):"+passlib.hash.fshp.encrypt(string)
print "Database Hashes"
print "MS SQL 2000:"+passlib.hash.mssql2000.encrypt(string)
print "MS SQL 2000:"+passlib.hash.mssql2005.encrypt(string)
print "MS SQL 2000:"+passlib.hash.mysql323.encrypt(string)
print "MySQL:"+passlib.hash.mysql41.encrypt(string)
print "Postgres (MD5):"+passlib.hash.postgres_md5.encrypt(string, user=salt)
print "Oracle 10:"+passlib.hash.oracle10.encrypt(string, user=salt)
print "Oracle 11:"+passlib.hash.oracle11.encrypt(string)
print "Other Known Hashes"
print "Cisco PIX:"+passlib.hash.cisco_pix.encrypt(string, user=salt)
print "Cisco Type 7:"+passlib.hash.cisco_type7.encrypt(string)
print "Dyango DES:"+passlib.hash.django_des_crypt.encrypt(string, salt=salt)
print "Dyango MD5:"+passlib.hash.django_salted_md5.encrypt(string, salt=salt[:2])
print "Dyango SHA1:"+passlib.hash.django_salted_sha1.encrypt(string, salt=salt)
print "Dyango Bcrypt:"+passlib.hash.django_bcrypt.encrypt(string, salt=salt2[:22])
print "Dyango PBKDF2 SHA1:"+passlib.hash.django_pbkdf2_sha1.encrypt(string, salt=salt)
print "Dyango PBKDF2 SHA1:"+passlib.hash.django_pbkdf2_sha256.encrypt(string, salt=salt)
print "Bcrypt:"+passlib.hash.bcrypt.encrypt(string, salt=salt2[:22])

107
unit04_public_key/README.md Normal file
View File

@@ -0,0 +1,107 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
# e-Security Unit 4: Public Key
The key concepts are: Basics, RSA, Elliptic Curve and ElGamal.
## What you should know at the end of unit?
* Explain how public key provides both privacy and identity verification.
* Where would I find this info? This unit explains public key.
* Understand how the RSA process works, with a simple example.
* Understand how elliptic curve cryptography works, with a simple example.
* Explain the operation of PGP.
* Understands how the private key is used to check the identity of the sender, and how public key is used to preserve the privacy of the message.
* Explain how the e and d values are determined within the RSA method.
* Where would I find this info? There are some examples [here](https://asecuritysite.com/log/rsa_examples.pdf).
## Presentations
* Week 4 Presentation (PDF) - Public Key Encryption: [here](https://github.com/billbuchanan/esecurity/blob/master/unit04_public_key/lecture/chapter04_public_msc.pdf).
* Week 4 Presentation (video) - Public Key Encryption: [here](https://youtu.be/QEYqkxuzoTg).
* Week 4 Presentation (lecture video - 8 Feb 2020) - Public Key Encryption: [here](https://www.youtube.com/watch?v=PEdCHWdE3zk).
## Lab
* Week 4 Lab (PDF): [here](https://github.com/billbuchanan/esecurity/blob/master/unit04_public_key/lab/new_lab04.pdf)
* Week 4 Lab (Demo): [here](https://youtu.be/6T9bFA2nl3c)
## Public key challenge
1. Bob has the following keys:
<pre>
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDoIhiWs15X/6xiLAVcBzpgvnuvMzHBJk58wOWrdfyEAcTY10oG
+6auNFGqQHYHbfKaZlEi4prAoe01S/R6jpx8ZqJUN0WKNn5G9nmjJha9Pag28ftD
rsT+4LktaQrxdNdrusP+qI0NiYbNBH6qvCrK0aGiucextehnuoqgDcqmRwIDAQAB
AoGAZCaJu0MJ2ieJxRU+/rRzoFeuXylUNwQC6toCfNY7quxkdDV2T8r038Xc0fpb
sdrix3CLYuSnZaK3B76MbO/oXQVBjDQZ7jVQ5K41nVCEZOtRDBeX5Ue6CBs4iNmC
+QyWx+u4OZPURq61YG7D+F1aWRvczdEZgKHPXl/+s5pIvAkCQQDw4V6px/+DJuZV
5Eg20OZe0m9Lvaq+G9UX2xTA2AUuH8Z79e+SCus6fMVl+Sf/W3y3uXp8B662bXhz
yheH67aDAkEA9rQrvmFj65n/D6eH4JAT4OP/+icQNgLYDW+u1Y+MdmD6A0YjehW3
suT9JH0rvEBET959kP0xCx+iFEjl81tl7QJBAMcp4GZK2eXrxOjhnh/Mq51dKu6Z
/NHBG3jlCIzGT8oqNaeK2jGLW6D5RxGgZ8TINR+HeVGR3JAzhTNftgMJDtcCQQC3
IqReXVmZaeXnrwu07f9zsI0zG5BzJ8VOpBt7OWah8fdmOsjXNgv55vbsAWdYBbUw
PQ+lc+7WPRNKT5sz/iM5AkEAi9Is+fgNy4q68nxPl1rBQUV3Bg3S7k7oCJ4+ju4W
NXCCvRjQhpNVhlor7y4FC2p3thje9xox6QiwNr/5siyccw==
-----END RSA PRIVATE KEY-----
-----BEGIN RSA PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDoIhiWs15X/6xiLAVcBzpgvnuv
MzHBJk58wOWrdfyEAcTY10oG+6auNFGqQHYHbfKaZlEi4prAoe01S/R6jpx8ZqJU
N0WKNn5G9nmjJha9Pag28ftDrsT+4LktaQrxdNdrusP+qI0NiYbNBH6qvCrK0aGi
ucextehnuoqgDcqmRwIDAQAB
-----END RSA PUBLIC KEY-----
</pre>
Alice sends him the following ciphered message:
<pre>
uW6FQth0pKaWc3haoqxbjIA7q2rF+G0Kx3z9ZDPZGU3NmBfzpD9ByU1ZBtbgKC8ATVZzwj15AeteOnbjO3EHQC4A5Nu0xKTWpqpngYRGGmzMGtblW3wBlNQYovDsRUGt+cJK7RD0PKn6PMNqK5EQKCD6394K/gasQ9zA6fKn3f0=
</pre>
What is the message? You might find some interesting code [here](https://asecuritysite.com/encryption/rsa_example).
2. Bob uses the following parameters for his public key:
<pre>
RSA Encryption parameters. Public key: [e,N].
e: 65537
N: 498702132445864856509611776937010471
Cipher: 96708304500902540927682601709667939
</pre>
Can you crack the cipher and find the value, if you know we are using using 60 bit primes [example](https://medium.com/asecuritysite-when-bob-met-alice/cracking-rsa-a-challenge-generator-2b64c4edb3e7)?
## A bit of fun
* A Python program to implement RSA in just 12 lines [here](https://asecuritysite.com/encryption/rsa12).
* A Python program to crack RSA in just 12 lines [here](https://asecuritysite.com/encryption/rsa12_2).
* Elliptic Curve methods are used in key handshaking (ECDH). If you want to see the curves that are used click [here](https://asecurity.site/encryption/ecdh3).
## Sample Exam Questions
The following are sample questions for public key:
* Bob selects a p value of 7 and a q value of 9, but he cannot get his RSA encryption to work. What is the problem?
* Bob has selected a p value of 11 and a q value of 7. Which of the following are possible encryption keys: (5,77), (3,77), (9,77), (11,77), and (24,77).
* Bob and Alice decide to use RSA encryption to send secure email, where Bob uses Alice's public key to encrypt, and she uses her private key to decrypt. What is the main problem caused with this, as apposed to using symmetric encryption?
* Bob tells Alice that she should send her private key in order that he should encrypt something for her. Outline the main problem caused by this.
* Security professionals say that RSA keys of over 1,024 bits are secure. What is the core protection against the RSA method being cracked for keys of 1,024 bits and more.
* Bob says he has had a look at a few RSA public keys and he says that the ones he looked at where all the same. Is he right? If so, what makes public keys different?
* Research: Netscape had to comply with an export [embargo](https://en.wikipedia.org/wiki/Export_of_cryptography_from_the_United_States) on the size of the keys which can be used for RSA. Which major vulnerabilities have resulted?
* Bob and Alice get into a debate about the size of the d and e values in the RSA encryption key. Bob says that, in real-life keys, the length of the e value in (e,n) is normally about the same size as the d value (d,n). Alice disagrees. Who is correct?
* Where would I find this info? Have a look at some practical examples: [Here](https://asecuritysite.com/encryption/rsa2)
## Examples
RSA Examples: [here](https://asecuritysite.com/public/rsa_examples.pdf).
RSA Keygen: [here](https://asecuritysite.com/encryption/rsa_keygen).
ECC Keygen: [here](https://asecuritysite.com/encryption/ecc_keygen).
## Quick demos
* Introduction to RSA: [here](https://www.youtube.com/watch?v=pHES8eNor6k)
* Introduction to Elliptic Curve: [here](https://youtu.be/_CwIWk6XDmg)
* Picking the Generator Value (G): [here](https://www.youtube.com/watch?v=-TjSuch3VGU)

View File

@@ -0,0 +1,782 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
# Lab 4: Asymmetric (Public) Key
Objective: The key objective of this lab is to provide a practical introduction to public key encryption, and with a focus on RSA and Elliptic Curve methods. This includes the creation of key pairs and in the signing process.
Video demo: https://youtu.be/6T9bFA2nl3c
Note: If you are using Python 3, instead of "pip install pycrypto" you can install pycryptodome with "pip3 install pycryptodome".
## A RSA Encryption
### A.1
The following defines a public key that is used with PGP email encryption:
<pre>
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v2
mQENBFTzi1ABCADIEWchOyqRQmU4AyQAMj2Pn68Sqo9lTPdPcItwo9LbTdv1YCFz
w3qLlp2RORMP+Kpdi92CIhdUYHDmZfHZ3IWTBgo9+y/Np9UJ6tNGocrgsq4xWz15
4vX4jJRddC7QySSh9UxDpRWf9sgqEv1pah136r95ZuyjC1EXnoNxdLJtx8PliCXc
hV/v4+KfOyzYh+HDJ4xP2bt1S07dkasYZ6cA7BHYi9k4xgEwxVvYtNjSPjTsQY5R
cTayXveGafuxmhSauZKiB/2TFErjEt49Y+p07tPTLX7bhMBVbUvojtt/JeUKV6vK
R82dmOd8seUvhwOHYB0JL+3S7PgFFsLo1NV5ABEBAAG0LkJpbGwgQnVjaGFuYW4g
KE5vbmUpIDx3LmJ1Y2hhbmFuQG5hcGllci5hYy51az6JATkEEwECACMFAlTzi1AC
GwMHCwkIBwMCAQYVCAIJCgsEFgIDAQ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NnSBVgtY1rzwaYi05XfuxG0WHVHPTtRyJ5pF4HSqiuvk6Z/4z3bw==
=ZrP+
-----END PGP PUBLIC KEY BLOCK-----
</pre>
Using the following Web page, determine the owner of the key, and the ID on the key:
https://asecuritysite.com/encryption/pgp1
By searching on-line, can you find the public key of three famous people, and view their key details, and can you discover some of the details of their keys (eg User ID, key encryption method, key size, etc)?
By searching on-line, what is an ASCII Armored Message?
### A.2
Bob has a private RSA key of:
<pre>
MIICXAIBAAKBgQCwgjkeoyCXm9v6VBnUi5ihQ2knkdxGDL3GXLIUU43/froeqk7q9mtxT4AnPAaDX3f2r4STZYYiqXGsHCUBZcI90dvZf6YiEM5OY2jgsmqBjf2Xkp/8HgN/XDw/wD2+zebYGLLYtd2u3GXx9edqJ8kQcU9LaMH+ficFQyfq9UwTjQIDAQABAoGAD7L1a6Ess+9b6G70gTANWkKJpshVZDGb63mxKRepaJEX8sRJEqLqOYDNsC+pkKO8IsfHreh4vrp9bsZuECrB1OHSjwDB0S/fm3KEWbsaaXDUAu0dQg/JBMXAKzeATreoIYJItYgwzrJ++fuquKabAZumvOnWJyBIs2z103kDz2ECQQDnn3JpHirmgVdf81yBbAJaXBXNIPzOcCth1zwFAs4EvrE35n2HvUQuRhy3ahUKXsKX/bGvWzmC2O6kbLTFEygVAkEAwxXZnPkaAY2vuoUCN5NbLZgegrAtmU+U2woa5A0fx6uXmShqxo1iDxEC71FbNIgHBg5srsUyDj3OsloLmDVjmQJAIy7qLyOA+sCc6BtMavBgLx+bxCwFmsoZHOSX3l79smTRAJ/HY64RREIsLIQ1q/yW7IWBzxQ5WTHgliNZFjKBvQJBAL3t/vCJwRz0Ebs5FaB/8UwhhsrbtXlGdnkOjIGsmV0vHSf6poHqUiay/DV88pvhN11ZG8zHpeUhnaQccJ9ekzkCQDHHG9LYCOqTgsyYms//cW4sv2nuOE1UezTjUFeqOlsgO+WN96b/M5gnv45/Z3xZxzJ4HOCJ/NRwxNOtEUkw+zY=
</pre>
And receives a ciphertext message of:
Pob7AQZZSml618nMwTpx3V74N45x/rTimUQeTl0yHq8F0dsekZgOT385Jls1HUzWCx6ZRFPFMJ1RNYR2Yh7AkQtFLVx9lYDfb/Q+SkinBIBX59ER3/fDhrVKxIN4S6h2QmMSRblh4KdVhyY6cOxu+g48Jh7TkQ2Ig93/nCpAnYQ=
Using the following code:
```python
from Crypto.PublicKey import RSA
from Crypto.Util import asn1
from base64 import b64decode
msg="Pob7AQZZSml618nMwTpx3V74N45x/rTimUQeTl0yHq8F0dsekZgOT385Jls1HUzWCx6ZRFPFMJ1RNYR2Yh7AkQtFLVx9lYDfb/Q+SkinBIBX59ER3/fDhrVKxIN4S6h2QmMSRblh4KdVhyY6cOxu+g48Jh7TkQ2Ig93/nCpAnYQ="
privatekey = 'MIICXAIBAAKBgQCwgjkeoyCXm9v6VBnUi5ihQ2knkdxGDL3GXLIUU43/froeqk7q9mtxT4AnPAaDX3f2r4STZYYiqXGsHCUBZcI90dvZf6YiEM5OY2jgsmqBjf2Xkp/8HgN/XDw/wD2+zebYGLLYtd2u3GXx9edqJ8kQcU9LaMH+ficFQyfq9UwTjQIDAQABAoGAD7L1a6Ess+9b6G70gTANWkKJpshVZDGb63mxKRepaJEX8sRJEqLqOYDNsC+pkKO8IsfHreh4vrp9bsZuECrB1OHSjwDB0S/fm3KEWbsaaXDUAu0dQg/JBMXAKzeATreoIYJItYgwzrJ++fuquKabAZumvOnWJyBIs2z103kDz2ECQQDnn3JpHirmgVdf81yBbAJaXBXNIPzOcCth1zwFAs4EvrE35n2HvUQuRhy3ahUKXsKX/bGvWzmC2O6kbLTFEygVAkEAwxXZnPkaAY2vuoUCN5NbLZgegrAtmU+U2woa5A0fx6uXmShqxo1iDxEC71FbNIgHBg5srsUyDj3OsloLmDVjmQJAIy7qLyOA+sCc6BtMavBgLx+bxCwFmsoZHOSX3l79smTRAJ/HY64RREIsLIQ1q/yW7IWBzxQ5WTHgliNZFjKBvQJBAL3t/vCJwRz0Ebs5FaB/8UwhhsrbtXlGdnkOjIGsmV0vHSf6poHqUiay/DV88pvhN11ZG8zHpeUhnaQccJ9ekzkCQDHHG9LYCOqTgsyYms//cW4sv2nuOE1UezTjUFeqOlsgO+WN96b/M5gnv45/Z3xZxzJ4HOCJ/NRwxNOtEUkw+zY='
keyDER = b64decode(privatekey)
keys = RSA.importKey(keyDER)
dmsg = keys.decrypt(b64decode(msg))
print dmsg
```
What is the plaintext message that Bob has been sent?
## B OpenSSL (RSA)
We will use OpenSSL to perform the following:
### B.1
First we need to generate a key pair with:
<pre>
openssl genrsa -out private.pem 1024
</pre>
This file contains both the public and the private key.
What is the type of public key method used:
How long is the default key:
How long did it take to generate a 1,024 bit key?
Use the following command to view the keys:
<pre>
cat private.pem
</pre>
### B.2
Use following command to view the output file:
<pre>
cat private.pem
</pre>
What can be observed at the start and end of the file:
### B.3
Next we view the RSA key pair:
<pre>
openssl rsa -in private.pem -text
</pre>
Which are the attributes of the key shown:
Which number format is used to display the information on the attributes:
### B.4
Lets now secure the encrypted key with 3-DES:
<pre>
openssl rsa -in private.pem -des3 -out key3des.pem
</pre>
Why should you have a password on the usage of your private key?
### B.5
Next we will export the public key:
<pre>
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
</pre>
View the output key. What does the header and footer of the file identify?
### B.6
Now create a file named “myfile.txt” and put a message into it. Next encrypt it with your public key:
<pre>
openssl rsautl -encrypt -inkey public.pem -pubin -in myfile.txt -out file.bin
</pre>
### B.7
And then decrypt with your private key:
openssl rsautl -decrypt -inkey private.pem -in file.bin -out decrypted.txt What are the contents of decrypted.txt
On your VM, go into the ~/.ssh folder. Now generate your SSH keys:
<pre>
ssh-keygen -t rsa -C "your email address"
</pre>
The public key should look like this:
<pre>
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLrriuNYTyWuC1IW7H6yea3hMV+rm029m2f6IddtlImHrOXjNwYyt4Elkkc7AzOy899C3gpx0kJK45k/CLbPnrHvkLvtQ0AbzWEQpOKxI+tW06PcqJNmTB8ITRLqIFQ++ZanjHWMw2Odew/514y1dQ8dccCOuzeGhL2Lq9dtfhSxx+1cBLcyoSh/lQcs1HpXtpwU8JMxWJl409RQOVn3gOusp/P/0R8mz/RWkmsFsyDRLgQK+xtQxbpbodpnz5lIOPWn5LnT0si7eHmL3WikTyg+QLZ3D3m44NCeNb+bOJbfaQ2ZB+lv8C3OxylxSp2sxzPZMbrZWqGSLPjgDiFIBL w.buchanan@napier.ac.uk
</pre>
View the private key. Outline its format?
On your Ubuntu instance setup your new keys for ssh:
<pre>
ssh-add ~/.ssh/id_git
</pre>
Now create a Github account and upload your public key to Github (select Settings-> New SSH key or Add SSH key). Create a new repository on your GitHub site, and add a new file to it. Next go to your Ubuntu instance and see if you can clone of a new directory:
<pre>
git clone ssh://git@github.com/**user/repository name**.git
</pre>
If this doesnt work, try the https connection that is defined on GitHub.
## C OpenSSL (ECC)
Elliptic Curve Cryptography (ECC) is now used extensively within public key encryption, including with Bitcoin, Ethereum, Tor, and many IoT applications. In this part of the lab we will use OpenSSL to create a key pair. For this we generate a random 256-bit private key (priv), and then generate a public key point (priv multiplied by G), using a generator (G), and which is a generator point on the selected elliptic curve.
### C.1
First we need to generate a private key with:
<pre>
openssl ecparam -name secp256k1 -genkey -out priv.pem
</pre>
The file will only contain the private key (and should have 256 bits).
Now use “cat priv.pem” to view your key.
Can you view your key?
### C.2
We can view the details of the ECC parameters used with:
<pre>
openssl ecparam -in priv.pem -text -param_enc explicit -noout
</pre>
Outline these values:
Prime (last two bytes):
A:
B:
Generator (last two bytes):
Order (last two bytes):
### C.3
Now generate your public key based on your private key with:
<pre>
openssl ec -in priv.pem -text -noout
</pre>
How many bits and bytes does your private key have:
How many bit and bytes does your public key have (Note the 04 is not part of the elliptic curve point):
What is the ECC method that you have used?
If you want to see an example of ECC, try here: https://asecuritysite.com/encryption/ecc
## D Elliptic Curve Encryption
### D.1
In the following Bob and Alice create elliptic curve key pairs. Bob can encrypt a message for Alice with her public key, and she can decrypt with her private key. Copy and paste the program from here:
https://asecuritysite.com/encryption/elc
Code used:
```python
import OpenSSL
import pyelliptic
secretkey="password"
test="Test123"
alice = pyelliptic.ECC()
bob = pyelliptic.ECC()
print "++++Keys++++"
print "Bob's private key: "+bob.get_privkey().encode('hex')
print "Bob's public key: "+bob.get_pubkey().encode('hex')
print
print "Alice's private key: "+alice.get_privkey().encode('hex')
print "Alice's public key: "+alice.get_pubkey().encode('hex')
ciphertext = alice.encrypt(test, bob.get_pubkey())
print "\n++++Encryption++++"
print "Cipher: "+ciphertext.encode('hex')
print "Decrypt: "+bob.decrypt(ciphertext)
signature = bob.sign("Alice")
print
print "Bob verified: "+ str(pyelliptic.ECC(pubkey=bob.get_pubkey()).verify
(signature, "Alice"))
```
For a message of “Hello. Alice”, what is the ciphertext sent (just include the first four characters):
How is the signature used in this example?
### D.2
Lets say we create an elliptic curve with y<sup>2</sup> = x<sup>3</sup> + 7, and with a prime number of 89, generate the first five (x,y) points for the finite field elliptic curve. You can use the Python code at the following to generate them:
https://asecuritysite.com/encryption/ecc_points
First five points:
### D.3
Elliptic curve methods are often used to sign messages, and where Bob will sign a message with his private key, and where Alice can prove that he has signed it by using his public key. With ECC, we can use ECDSA, and which was used in the first version of Bitcoin. Enter the following code:
```python
from ecdsa import SigningKey,NIST192p,NIST224p,NIST256p,NIST384p,NIST521p,SECP256k1
import base64
import sys
msg="Hello"
type = 1
cur=NIST192p
sk = SigningKey.generate(curve=cur)
vk = sk.get_verifying_key()
signature = sk.sign(msg)
print "Message:\t",msg
print "Type:\t\t",cur.name
print "========================="
print "Signature:\t",base64.b64encode(signature)
print "========================="
print "Signatures match:\t",vk.verify(signature, msg)
```
What are the signatures (you only need to note the first four characters) for a message of “Bob”, for the curves of NIST192p, NIST521p and SECP256k1:
NIST192p:
NIST521p:
SECP256k1:
By searching on the Internet, can you find in which application areas that SECP256k1 is used?
What do you observe from the different hash signatures from the elliptic curve methods?
## E RSA
### E.1 We will follow a basic RSA process. If you are struggling here, have a look at the following page:
https://asecuritysite.com/encryption/rsa
First, pick two prime numbers:
p=
q=
Now calculate N (p.q) and PHI [(p-1).(q-1)]:
N=
PHI =
Now pick a value of e which does not share a factor with PHI [gcd(PHI,e)=1]:
e=
Now select a value of d, so that (e.d) (mod PHI) = 1:
[Note: You can use this page to find d: https://asecuritysite.com/encryption/inversemod]
d=
Now for a message of M=5, calculate the cipher as:
C = M<sup>e</sup> (mod N) =
Now decrypt your ciphertext with:
M = C<sup>d</sup> (mod N) =
Did you get the value of your message back (M=5)? If not, you have made a mistake, so go back and check.
Now run the following code and prove that the decrypted cipher is the same as the message:
```python
p=11
q=3
N=p*q
PHI=(p-1)*(q-1)
e=3
for d in range(1,N):
if ((e*d % PHI)==1): break
print e,N
print d,N
M=4
cipher = M**e % N
print cipher
message = cipher**d % N
print message
```
Select three more examples with different values of p and q, and then select e in order to make sure that the cipher will work:
### E.2
In the RSA method, we have a value of e, and then determine d from (d.e) (mod PHI)=1. But how do we use code to determine d? Well we can use the Euclidean algorithm. The code for this is given at:
https://asecuritysite.com/encryption/inversemod
Using the code, can you determine the following:
<pre>
Inverse of 53 (mod 120) =
Inverse of 65537 (mod 1034776851837418226012406113933120080) =
</pre>
Using this code, can you now create an RSA program where the user enters the values of p, q, and e, and the program determines (e,N) and (d,N)?
### E.3
Run the following code and observe the output of the keys. If you now change the key generation key from PEM to DER, how does the output change:
```python
from Crypto.PublicKey import RSA
key = RSA.generate(2048)
binPrivKey = key.exportKey('PEM')
binPubKey = key.publickey().exportKey('PEM')
print binPrivKey
print binPubKey
```
### E.4
A simple RSA program to encrypt and decrypt with RSA is given next. Prove its operation:
```python
import rsa
(bob_pub, bob_priv) = rsa.newkeys(512)
ciphertext = rsa.encrypt('Here is my message', bob_pub)
message = rsa.decrypt(ciphertext, bob_priv)
print(message.decode('utf8'))
```
## F PGP
### F.1
The following is a PGP key pair. Using https://asecuritysite.com/encryption/pgp, can you determine the owner of the keys:
<pre>
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: OpenPGP.js v4.4.5
Comment: https://openpgpjs.org
xk0EXEOYvQECAIpLP8wfLxzgcolMpwgzcUzTlH0icggOIyuQKsHM4XNPugzU
X0NeaawrJhfi+f8hDRojJ5Fv8jBI0m/KwFMNTT8AEQEAAc0UYmlsbCA8Ymls
bEBob21lLmNvbT7CdQQQAQgAHwUCXEOYvQYLCQcIAwIEFQgKAgMWAgECGQEC
GwMCHgEACgkQoNsXEDYt2ZjkTAH/b6+pDfQLi6zg/Y0tHS5PPRv1323cwoay
vMcPjnWq+VfiNyXzY+UJKR1PXskzDvHMLOyVpUcjle5ChyT5LOw/ZM5NBFxD
mL0BAgDYlTsT06vVQxu3jmfLzKMAr4kLqqIuFFRCapRuHYLOjw1gJZS9p0bF
S0qS8zMEGpN9QZxkG8YEcH3gHxlrvALtABEBAAHCXwQYAQgACQUCXEOYvQIb
DAAKCRCg2xcQNi3ZmMAGAf9w/XazfELDG1W35l2zw12rKwM7rK97aFrtxz5W
XwA/5gqoVP0iQxklb9qpX7RVd6rLKu7zoX7F+sQod1sCWrMw
=cXT5
-----END PGP PUBLIC KEY BLOCK-----
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: OpenPGP.js v4.4.5
Comment: https://openpgpjs.org
xcBmBFxDmL0BAgCKSz/MHy8c4HKJTKcIM3FM05R9InIIDiMrkCrBzOFzT7oM
1F9DXmmsKyYX4vn/IQ0aIyeRb/IwSNJvysBTDU0/ABEBAAH+CQMIBNTT/OPv
TJzgvF+fLOsLsNYP64QfNHav5O744y0MLV/EZT3gsBwO9v4XF2SsZj6+EHbk
O9gWi31BAIDgSaDsJYf7xPOhp8iEWWwrUkC+jlGpdTsGDJpeYMIsVVv8Ycam
0g7MSRsL+dYQauIgtVb3dloLMPtuL59nVAYuIgD8HXyaH2vsEgSZSQn0kfvF
+dWeqJxwFM/uX5PVKcuYsroJFBEO1zas4ERfxbbwnsQgNHpjdIpueHx6/4EO
b1kmhOd6UT7BamubY7bcma1PBSv8PH31Jt8SzRRiaWxsIDxiaWxsQGhvbWUu
Y29tPsJ1BBABCAAfBQJcQ5i9BgsJBwgDAgQVCAoCAxYCAQIZAQIbAwIeAQAK
CRCg2xcQNi3ZmORMAf9vr6kN9AuLrOD9jS0dLk89G/XfbdzChrK8xw+Odar5
V+I3JfNj5QkpHU9eyTMO8cws7JWlRyOV7kKHJPks7D9kx8BmBFxDmL0BAgDY
lTsT06vVQxu3jmfLzKMAr4kLqqIuFFRCapRuHYLOjw1gJZS9p0bFS0qS8zME
GpN9QZxkG8YEcH3gHxlrvALtABEBAAH+CQMI2Gyk+BqVOgzgZX3C80JRLBRM
T4sLCHOUGlwaspe+qatOVjeEuxA5DuSs0bVMrw7mJYQZLtjNkFAT92lSwfxY
gavS/bILlw3QGA0CT5mqijKr0nurKkekKBDSGjkjVbIoPLMYHfepPOju1322
Nw4V3JQO4LBh/sdgGbRnwW3LhHEK4Qe70cuiert8C+S5xfG+T5RWADi5HR8u
UTyH8x1h0ZrOF7K0Wq4UcNvrUm6c35H6lClC4Zaar4JSN8fZPqVKLlHTVcL9
lpDzXxqxKjS05KXXZBh5wl8EGAEIAAkFAlxDmL0CGwwACgkQoNsXEDYt2ZjA
BgH/cP12s3xCwxtVt+Zds8NdqysDO6yve2ha7cc+Vl8AP+YKqFT9IkMZJW/a
qV+0VXeqyyru86F+xfrEKHdbAlqzMA==
=5NaF
-----END PGP PRIVATE KEY BLOCK-----
</pre>
### F.2
Using the code at the following link, generate a key:
https://asecuritysite.com/encryption/openpgp
### F.3
An important element in data loss prevention is encrypted emails. In this part of the lab we will use an open source standard: PGP.
1 Create a key pair with (RSA and 2,048-bit keys):
<pre>
gpg --gen-key
</pre>
Now export your public key using the form of:
<pre>
gpg --export -a "Your name" > mypub.key
</pre>
Now export your private key using the form of:
<pre>
gpg --export-secret-key -a "Your name" > mypriv.key
</pre>
How is the randomness generated?
Outline the contents of your key file:
### 2
Now send your lab partner your public key in the contents of an email, and ask them to import it onto their key ring (if you are doing this on your own, create another set of keys to simulate another user, or use Bills public key which is defined at http://asecuritysite.com/public.txt and send the email to him):
<pre>
gpg --import theirpublickey.key
</pre>
Now list your keys with:
<pre>
gpg --list-keys
</pre>
Which keys are stored on your key ring and what details do they have:
### 3
Create a text file, and save it. Next encrypt the file with their public key:
<pre>
gpg -e -a -u "Your Name" -r "Your Lab Partner Name" hello.txt
</pre>
What does the a option do:
What does the r option do:
What does the u option do:
Which file does it produce and outline the format of its contents:
### 4
Send your encrypted file in an email to your lab partner, and get one back from them.
Now create a file (such as myfile.asc) and decrypt the email using the public key received from them with:
<pre>
gpg d myfile.asc > myfile.txt
</pre>
Can you decrypt the message:
### 5
Next using this public key file, send Bill (w.buchanan@napier.ac.uk) a question (http://asecuritysite.com/public.txt):
<pre>
-----BEGIN PGP PUBLIC KEY BLOCK-----
mQENBF48dkABCACnQz3dsgokvcZTOiiRrteBSMI2CGRDYlPzyvG52XrQ8A0YQcgY
JmaHFxNGiyXEYqlrNTey9e8i+abiQKuPBRZ4tLjq7hlcDs+lne4gXgQiX7nwO0Jg
ydp0tncKvnB9nCCgmh99YRC9N3/X0ObWtqUsFH7BOfsI18QalntqOA59W34ph4OB
+MyCxgXVcnI14w9oNvxEkAPCyQ4aSZiDEWpO4ITDl6+EyLZZYiMK4jcYNPdt2D+a
X7C+xh7m0egi6p8r61siTGi3iCtHj6rxVgJuh7E4Q1gR9blVGNwrrl+OxfgQwPg1
zBlpgk6Wmijn8kFd0Yo6jAwE6BzMOWZsDgg9ABEBAAG0LkJpbGwgQnVjaGFuYW4g
KFRlc3QpIDx3LmJ1Y2hhbmFuQG5hcGllci5hYy51az6JAVQEEwEIAD4WIQQDIH7a
zNq1SlIPpXf++x/U2051FAUCXjx2QAIbAwUJB4YfgAULCQgHAgYVCgkICwIEFgID
AQIeAQIXgAAKCRD++x/U2051FDmgB/9erztIZoQFXsL+ZO83+td8IkjMjhN1meBE
voq6nM9ihaa44rwU/bwdcOl+emcEyxbHTDYs9j0vFBUSzK8zJIwcCIIT7b4HXA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Y BLOCK-----
</pre>
Did you receive a reply:
### 6
Next send your public key to Bill (w.buchanan@napier.ac.uk), and ask for an encrypted message from him.
## G TrueCrypt
No Description Result
1 Go to your Kali instance (User: root, Password: toor). Now Create a new volume and use an encrypted file container (use tc_yourname) with a Standard TrueCrypt volume.
When you get to the Encryption Options, run the benchmark tests and outline the results:
CPU (Mean)
AES:
AES-Twofish:
AES-Two-Seperent
Serpent -AES
Serpent:
Serpent-Twofish-AES
Twofish:
Twofish-Serpent:
Which is the fastest:
Which is the slowest:
2 Select AES and RIPMD-160 and create a 100MB file. Finally select your password and use FAT for the file system.
What does the random pool generation do, and what does it use to generate the random key?
3 Now mount the file as a drive.
Can you view the drive on the file viewer and from the console? [Yes][No]
4 Create some files your TrueCrypt drive and save them.
Without giving them the password, can they read the file?
With the password, can they read the files?
The following files have the passwords of “Ankle123”, “foxtrot”, “napier123”, “password” or “napier”. Determine the properties of the files defined in the table:
File
Size Encryption type Key size Files/folders on disk Hidden partition (y/n) Hash method
http://asecuritysite.com/tctest01.zip
http://asecuritysite.com/tctest02.zip
http://asecuritysite.com/tctest03.zip
Now with truecrack see if you can determine the password on the volumes. Which TrueCrypt volumes can truecrack?
H Reflective statements
1. In ECC, we use a 256-bit private key. This is used to generate the key for signing Bitcoin transactions. Do you think that a 256-bit key is largest enough? If we use a cracker what performs 1 Tera keys per second, will someone be able to determine our private key?
## I What I should have learnt from this lab?
The key things learnt:
* The basics of the RSA method.
* The process of generating RSA and Elliptic Curve key pairs.
* To illustrate how the private key is used to sign data, and then using the public key to verify the signature.
## Additional
The following is code which performs RSA key generation, and the encryption and decryption of a message (https://asecuritysite.com/encryption/rsa_example):
```python
from Crypto.PublicKey import RSA
from Crypto.Util import asn1
from base64 import b64decode
from base64 import b64encode
from Crypto.Cipher import PKCS1_OAEP
import sys
msg = "hello..."
if (len(sys.argv)>1):
msg=str(sys.argv[1])
key = RSA.generate(1024)
binPrivKey = key.exportKey('PEM')
binPubKey = key.publickey().exportKey('PEM')
print
print "====Private key==="
print binPrivKey
print
print "====Public key==="
print binPubKey
privKeyObj = RSA.importKey(binPrivKey)
pubKeyObj = RSA.importKey(binPubKey)
cipher = PKCS1_OAEP.new(pubKeyObj)
ciphertext = cipher.encrypt(msg)
print
print "====Ciphertext==="
print b64encode(ciphertext)
cipher = PKCS1_OAEP.new(privKeyObj)
message = cipher.decrypt(ciphertext)
print
print "====Decrypted==="
print "Message:",message
```
Can you decrypt this:
<pre>
FipV/rvWDyUareWl4g9pneIbkvMaeulqSJk55M1VkiEsCRrDLq2fee8g2oGrwxx2j6KH+VafnLfn+QFByIKDQKy+GoJQ3B5bD8QSzPpoumJhdSILcOdHNSzTseuMAM1CSBawbddL2KmpW2zmeiNTrYeA+T6xE9JdgOFrZ0UrtKw=
</pre>
The private key is:
<pre>
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQCqRucTX4+UBgKxGUV5TB3A1hZnUwazkLlsUdBbM4hXoO+n3O7v
jk1UfhItDrVgkl3Mla7CMpyIadlOhSzn8jcvGdNY/Xc+rV7BLfR8FeatOIXGqV+G
d3vDXQtsxCDRnjXGNHfWZCypHn1vqVDulB2q/xTyWcKgC61Vj8mMiHXcAQIDAQAB
AoGAA7ZYA1jqAG6N6hG3xtU2ynJG1F0MoFpfY7hegOtQTAv6+mXoSUC8K6nNkgq0
2Zrw5vm8cNXTPWyEi4Z+9bxjusU8B3P2s8w+3t7NN0vDM18hiQL2loS0s7HLlGzb
IgkBclJS6b+B8qF2YtOoLaPrWke2uV0TPZGRVLBGAkCw4YECQQDFhZNqWWTFgpzn
/qrVYvw6dtn92CmUBT+8pxgaEUEBF41jAOyR4y97pvM85zeJ1Kcj7VhW0cNyBzEN
ItCNme1dAkEA3LBoaCjJnEXwhAJ8OJ0S52RT7T+3LI+rdPKNomZW0vZZ+F/SvY7A
+vOIGQaUenvK1PRhbefJraBvVN+d009a9QJBAJWwLxGPgYD1BPgD1W81PrUH0RhA
svHMMItFjkxi+wJa2PlIf//nTdr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KBgfT7s6dG07wV/6KALWc+D3fTutkxxA/kQtAHzxo9tBeuMNwn3FHDhrgn81
3PIGdMJUVds2K+O0fTKXhQifbTLIoitC6OwSbFzhJ91SbvNXLc8IuQENBF48dkAB
CADoJivwlYuMOeUVSQi7VIFr06j4jG2J2yp3t6tMEPoimnuj/5sjwDLM1q9vu1wA
0Fx0S3/e9dapLy7M1R8+qWEvFtBKUPxZyF+LwXaETl0on1PR64h4VShbYf1AnzrO
D2jkpsIKPorFSdd7UBJ7t/rQmUHtTZfgfsZwoA9Cho4LoXjkTR42AOsWYUqtAATx
6XCpFEukkIHzNWmaZpd7sDnJV9Ov9k2vcVxRAE8J2ZZkXO0qmGL+cCVIQyxlD7XH
fzPbRMDpFxN5npbJTMy2fK4z3Ijj8riISpr9ssZbY+MRvrV4isxt+fbPkjuGtJoY
fCA7RHAggtAOJ9sjTbJYlI95ABEBAAGJATwEGAEIACYWIQQDIH7azNq1SlIPpXf+
+x/U2051FAUCXjx2QAIbDAUJB4YfgAAKCRD++x/U2051FExICACDnSUpfYpLOcT3
jVzPmyAW+KqJWza8S1suUVThEMqyXfogqpdD/SLVLtpJZpFu6lbtSQZ7R6M/uVkH
0BfHiM2cKQU3ovSOo9yNbSmT45D72eVA/Uggu9lnPpma7MY864nqcjtaEQbTGdgL
GYWPoyAU4Ko34xJ5Cltp16CDZLk+eTcRUD6l3qbvR/P9/eajWP7q9fBW1rz1R3xn
jvXEsxT6cvQQlRGvCuuE25OX75OdUAiRg8rVwtWTgrOvIfY+G9HECZdw9e5/VfkA
RtuyTKiKVNSPCbPqYXCnZjBy/0NQiSz8h1OPYtwJ74l16Hz0XWzBy5YeFisl0wU3
kJ6Zg7/d
=oYa9
-----END PGP PUBLIC KEY BLOCK-----

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,735 @@
Try not to look at these answers, unless you really have too ..
# Introduction
## A.1
<pre>
pub 2048R/1AD74F42 2015-03-01 Bill Buchanan (None) <w.buchanan@napier.ac.uk>
sub 2048R/6F6AA48C 2015-03-01
</pre>
## A.2
The code used is:
```python
from Crypto.PublicKey import RSA
from Crypto.Util import asn1
from base64 import b64decode
msg="Pob7AQZZSml618nMwTpx3V74N45x/rTimUQeTl0yHq8F0dsekZgOT385Jls1HUzWCx6ZRFPFMJ1RNYR2Yh7AkQtFLVx9lYDfb/Q+SkinBIBX59ER3/fDhrVKxIN4S6h2QmMSRblh4KdVhyY6cOxu+g48Jh7TkQ2Ig93/nCpAnYQ="
privatekey = 'MIICXAIBAAKBgQCwgjkeoyCXm9v6VBnUi5ihQ2knkdxGDL3GXLIUU43/froeqk7q9mtxT4AnPAaDX3f2r4STZYYiqXGsHCUBZcI90dvZf6YiEM5OY2jgsmqBjf2Xkp/8HgN/XDw/wD2+zebYGLLYtd2u3GXx9edqJ8kQcU9LaMH+ficFQyfq9UwTjQIDAQABAoGAD7L1a6Ess+9b6G70gTANWkKJpshVZDGb63mxKRepaJEX8sRJEqLqOYDNsC+pkKO8IsfHreh4vrp9bsZuECrB1OHSjwDB0S/fm3KEWbsaaXDUAu0dQg/JBMXAKzeATreoIYJItYgwzrJ++fuquKabAZumvOnWJyBIs2z103kDz2ECQQDnn3JpHirmgVdf81yBbAJaXBXNIPzOcCth1zwFAs4EvrE35n2HvUQuRhy3ahUKXsKX/bGvWzmC2O6kbLTFEygVAkEAwxXZnPkaAY2vuoUCN5NbLZgegrAtmU+U2woa5A0fx6uXmShqxo1iDxEC71FbNIgHBg5srsUyDj3OsloLmDVjmQJAIy7qLyOA+sCc6BtMavBgLx+bxCwFmsoZHOSX3l79smTRAJ/HY64RREIsLIQ1q/yW7IWBzxQ5WTHgliNZFjKBvQJBAL3t/vCJwRz0Ebs5FaB/8UwhhsrbtXlGdnkOjIGsmV0vHSf6poHqUiay/DV88pvhN11ZG8zHpeUhnaQccJ9ekzkCQDHHG9LYCOqTgsyYms//cW4sv2nuOE1UezTjUFeqOlsgO+WN96b/M5gnv45/Z3xZxzJ4HOCJ/NRwxNOtEUkw+zY='
keyDER = b64decode(privatekey)
keys = RSA.importKey(keyDER)
dmsg = keys.decrypt(b64decode(msg))
print dmsg
```
The output is:
<pre>
Congrats! The flag is nothing_is_impossible
</pre>
## A.3
<pre>
napieraccount@ubuntu:~/.ssh$ cd ~/.ssh
napieraccount@ubuntu:~/.ssh$ ssh-keygen -t rsa -C "w.buchanan@napier.ac.uk"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/napaccount/.ssh/id_rsa):
/home/napaccount/.ssh/id_rsa already exists.
Overwrite (y/n)?
napieraccount@ubuntu:~/.ssh$ cat id_rsa
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,231906D9476629A1F38BF98A15E72E03
cWII6N99LmTwoD43g4eNQHt2cK5SDUjkbbkZccK/4lcSEpUB7lcxBr7irgZavrre
Mnydi+uTqzP4s+0vt5N/DxwmUT8kShgdfS5s5mx1obSXp9byHKcNSqY5rKggTsNQ
P6O17nPW+dOoZ0A1luNYsqjk5dh33M84rbRP8UydEZgJdvXOw+4C1fNHIs1/e7tN
tnEg4xT9uY1KRQmTeshdwlnjLDpcFz6bxRB7ppxg9GNKhaax9ZkQwH+kKo9IdeV3
J+YKG51n9gWhe/5PLyxrejHsO1DAWB0W+tKAiuSKF+H3v1H2DMhO8lm7qWryeuMg
IhiV29qkzJfgB6fH+aTQhmubxsuZ1Lgzb3/gc/TNRDR2vFE8yXvATZBvS82zNYgT
4K9Z3Okewl5UMAiKlbv0+2l/vBzk7zCKflCRY+7K9osuY6LdIgJCq5woPvrVi4QE
YJpVGcqjT2FDLXWIIz6TJH0fO8LRqkAf/oPezM4JSbTWgUnIyU5Oxs97avrnK1fU
Vc9rN7aI8u3XNxMGs3kFJ5VrOdJS5ZoXqMB6tkT0ASXLlP365mKV1hx78ypgOSQJ
1BelOnfnSoPHErsBqAJ6ddt2ZqTkES8V9HomjtB4uVJvKSgnw3nzdBGCge5PU425
mhNOrhTagQhf5wfiuuSu0rW6YKC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GLFS1J/KIeme2LpEryC5FaG8/gziM7RsqjrAcQ/ipeIb+fNYT6POX5z/KVM6x7VcdkV0vr/k+Zkb9qeVcsIlBUAQIAfz24wOQCYZ6UnB9va88JWnjVSgwxeL5KmqgHDelFt50LgXrN/KOw== w.buchanan@napier.ac.uk
</pre>
For the RSA private key, protecting it with 128-bit AES, CBC, and the salt used is "231906D9476629A1F38BF98A15E72E03":
<pre>
AES-128-CBC,231906D9476629A1F38BF98A15E72E03
</pre>
# OpenSSL RSA
## B.1
What is the type of public key method used? RSA
How long is the default key: 1024
A sample key:
<pre>
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQC3qXK4kCxn3BNk87vJUMwIznU8pTjr10Kma9+Jkj4zEy/fiZtY
xvdmn1rKNq/8fEUDCcRVC8hQBpevqxFiJ3dbA7ZM6VjUAmztOfRfxSezgvkjswVS
F1/cgBM32AB4nx1dkCV/Wgedn3KFIFU+b8LH1ZLoyRMyLnwWmAkT/mBC/QIDAQAB
AoGAE8Yao+Rh44y+SdA0F6irTwdrd+wSBNJYSrKyjo1ARR97uAWIxDYnzNS7Yaoh
qH14sKsMiFuMZZFQI4m3hWnaX7OFjhJvxKjP6+BdXKsnwWxpwec7RS6n9ptA7qlE
aIFfVARyiWjG+q+8Bg8CTaHjGgtYPnfLzJM0Vef6gKg5vgECQQDZSKGxtdbpXwXw
VAC78SyfOOYmWKL1HiZs0nyTOnZmhMSkE4+S38zhDTjITh0cuKTksTFeUku/sRij
4T4Y9iz5AkEA2GMpeeRT3IQntmzQgTc7Rgez73Y/UWFynuErg++9gzI758TO3AoV
lFs4NOUAqhZ5fdwizs6sa0bjYm+BC1mbJQJBAMQVts4QItVSSqK6vDrfh/xctd4v
KUh5oAWe4otfPBCCio7jlDLgwxzp+K9TRxRvUWeMvNe4/uEMKgdiss6GAskCQQCf
MpVZMDriifgNppDgABqDszcWfhCnduI1McQqFT+APn0ETy9Bg8nMlDAN+k061b4c
ctDJBhSj+EtiKFbwWsRhAkAnEPn+6m3djTwJMw82DxK1q2fcIjTR0ng8pyrF2iIR
P7oBP8I4hGix/FOrV8M8virK6iCsslEcZBo39FkEqc0N
-----END RSA PRIVATE KEY-----
</pre>
## B.2
Start and end are:
<pre>
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
</pre>
## B.3
We get **modulus** (N), **publicExponent** (e), **privateExponent** (d), **prime1** (p), **prime2** (q). The other parameters are stored to speed up the RSA process, such as **exponent1** (d mod p-1), **exponent2** (d mod q-1) and **coefficient** (inv q mod p).
<pre>
Private-Key: (1024 bit)
modulus:
00:b7:a9:72:b8:90:2c:67:dc:13:64:f3:bb:c9:50:
cc:08:ce:75:3c:a5:38:eb:d7:42:a6:6b:df:89:92:
3e:33:13:2f:df:89:9b:58:c6:f7:66:9f:5a:ca:36:
af:fc:7c:45:03:09:c4:55:0b:c8:50:06:97:af:ab:
11:62:27:77:5b:03:b6:4c:e9:58:d4:02:6c:ed:39:
f4:5f:c5:27:b3:82:f9:23:b3:05:52:17:5f:dc:80:
13:37:d8:00:78:9f:1d:5d:90:25:7f:5a:07:9d:9f:
72:85:20:55:3e:6f:c2:c7:d5:92:e8:c9:13:32:2e:
7c:16:98:09:13:fe:60:42:fd
publicExponent: 65537 (0x10001)
privateExponent:
13:c6:1a:a3:e4:61:e3:8c:be:49:d0:34:17:a8:ab:
4f:07:6b:77:ec:12:04:d2:58:4a:b2:b2:8e:8d:40:
45:1f:7b:b8:05:88:c4:36:27:cc:d4:bb:61:aa:21:
a8:7d:78:b0:ab:0c:88:5b:8c:65:91:50:23:89:b7:
85:69:da:5f:b3:85:8e:12:6f:c4:a8:cf:eb:e0:5d:
5c:ab:27:c1:6c:69:c1:e7:3b:45:2e:a7:f6:9b:40:
ee:a9:44:68:81:5f:54:04:72:89:68:c6:fa:af:bc:
06:0f:02:4d:a1:e3:1a:0b:58:3e:77:cb:cc:93:34:
55:e7:fa:80:a8:39:be:01
prime1:
00:d9:48:a1:b1:b5:d6:e9:5f:05:f0:54:00:bb:f1:
2c:9f:38:e6:26:58:a2:f5:1e:26:6c:d2:7c:93:3a:
76:66:84:c4:a4:13:8f:92:df:cc:e1:0d:38:c8:4e:
1d:1c:b8:a4:e4:b1:31:5e:52:4b:bf:b1:18:a3:e1:
3e:18:f6:2c:f9
prime2:
00:d8:63:29:79:e4:53:dc:84:27:b6:6c:d0:81:37:
3b:46:07:b3:ef:76:3f:51:61:72:9e:e1:2b:83:ef:
bd:83:32:3b:e7:c4:ce:dc:0a:15:94:5b:38:34:e5:
00:aa:16:79:7d:dc:22:ce:ce:ac:6b:46:e3:62:6f:
81:0b:59:9b:25
exponent1:
00:c4:15:b6:ce:10:22:d5:52:4a:a2:ba:bc:3a:df:
87:fc:5c:b5:de:2f:29:48:79:a0:05:9e:e2:8b:5f:
3c:10:82:8a:8e:e3:94:32:e0:c3:1c:e9:f8:af:53:
47:14:6f:51:67:8c:bc:d7:b8:fe:e1:0c:2a:07:62:
b2:ce:86:02:c9
exponent2:
00:9f:32:95:59:30:3a:e2:89:f8:0d:a6:90:e0:00:
1a:83:b3:37:16:7e:10:a7:76:e2:35:31:c4:2a:15:
3f:80:3e:7d:04:4f:2f:41:83:c9:cc:94:30:0d:fa:
4d:3a:d5:be:1c:72:d0:c9:06:14:a3:f8:4b:62:28:
56:f0:5a:c4:61
coefficient:
27:10:f9:fe:ea:6d:dd:8d:3c:09:33:0f:36:0f:12:
b5:ab:67:dc:22:34:d1:d2:78:3c:a7:2a:c5:da:22:
11:3f:ba:01:3f:c2:38:84:68:b1:fc:53:ab:57:c3:
3c:be:2a:ca:ea:20:ac:b2:51:1c:64:1a:37:f4:59:
04:a9:cd:0d
writing RSA key
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQC3qXK4kCxn3BNk87vJUMwIznU8pTjr10Kma9+Jkj4zEy/fiZtY
xvdmn1rKNq/8fEUDCcRVC8hQBpevqxFiJ3dbA7ZM6VjUAmztOfRfxSezgvkjswVS
F1/cgBM32AB4nx1dkCV/Wgedn3KFIFU+b8LH1ZLoyRMyLnwWmAkT/mBC/QIDAQAB
AoGAE8Yao+Rh44y+SdA0F6irTwdrd+wSBNJYSrKyjo1ARR97uAWIxDYnzNS7Yaoh
qH14sKsMiFuMZZFQI4m3hWnaX7OFjhJvxKjP6+BdXKsnwWxpwec7RS6n9ptA7qlE
aIFfVARyiWjG+q+8Bg8CTaHjGgtYPnfLzJM0Vef6gKg5vgECQQDZSKGxtdbpXwXw
VAC78SyfOOYmWKL1HiZs0nyTOnZmhMSkE4+S38zhDTjITh0cuKTksTFeUku/sRij
4T4Y9iz5AkEA2GMpeeRT3IQntmzQgTc7Rgez73Y/UWFynuErg++9gzI758TO3AoV
lFs4NOUAqhZ5fdwizs6sa0bjYm+BC1mbJQJBAMQVts4QItVSSqK6vDrfh/xctd4v
KUh5oAWe4otfPBCCio7jlDLgwxzp+K9TRxRvUWeMvNe4/uEMKgdiss6GAskCQQCf
MpVZMDriifgNppDgABqDszcWfhCnduI1McQqFT+APn0ETy9Bg8nMlDAN+k061b4c
ctDJBhSj+EtiKFbwWsRhAkAnEPn+6m3djTwJMw82DxK1q2fcIjTR0ng8pyrF2iIR
P7oBP8I4hGix/FOrV8M8virK6iCsslEcZBo39FkEqc0N
-----END RSA PRIVATE KEY-----
</pre>
## B.4
If someone gets your private key they could decrypt things sent to you with your public key, or sign things on your behalf.
## B.5
We see a PUBLIC KEY string:
<pre>
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3qXK4kCxn3BNk87vJUMwIznU8
pTjr10Kma9+Jkj4zEy/fiZtYxvdmn1rKNq/8fEUDCcRVC8hQBpevqxFiJ3dbA7ZM
6VjUAmztOfRfxSezgvkjswVSF1/cgBM32AB4nx1dkCV/Wgedn3KFIFU+b8LH1ZLo
yRMyLnwWmAkT/mBC/QIDAQAB
-----END PUBLIC KEY-----
</pre>
## B.7
<pre>
napieraccount@ubuntu:~/test$ openssl rsautl -decrypt -inkey private.pem -in file.bin -out decrypted.txt
napieraccount@ubuntu:~/test$ cat decrypted.txt
Hello
</pre>
## B.8
We have a hex format for the -hexdump output:
<pre>
napieraccount@ubuntu:~/test$ openssl rsautl -encrypt -inkey public.pem -pubin -in myfile.txt -out file.bin -hexdump
napieraccount@ubuntu:~/test$ cat file.bin
0000 - 88 a7 53 b6 da 09 6d 9f-c6 80 95 3b 23 2a bd 20 ..S...m....;#*.
0010 - 46 fb 4b f0 51 ee 64 66-79 96 3a b4 5c 32 c4 2b F.K.Q.dfy.:.\2.+
0020 - 62 b6 5b 1c da 99 1d 5f-1f 81 06 2e 2e 53 eb 7e b.[...._.....S.~
0030 - c9 c4 4e 6c d4 60 86 e0-9f 52 8c aa d2 8f 65 c2 ..Nl.`...R....e.
0040 - 7c 08 83 13 d3 c0 3e ce-fc b6 be 01 75 ad ee bb |.....>.....u...
0050 - 9a b6 56 b4 e5 22 7b ea-a5 85 2d 16 fa 7f 50 6f ..V.."{...-...Po
0060 - d7 67 ff bd 97 c2 26 04-1f 8d 4d c7 52 ea 40 6e .g....&...M.R.@n
0070 - 9a d9 03 10 67 52 a3 05-8f 0c fd 83 7b 1b 89 1b ....gR......{...
napieraccount@ubuntu:~/test$ openssl rsautl -encrypt -inkey public.pem -pub
</pre>
We get a binary format with:
<pre>
napieraccount@ubuntu:~/test$ openssl rsautl -encrypt -inkey public.pem -pubin -in myfile.txt -out file.bin
napieraccount@ubuntu:~/test$ cat file.bin
:<3A>H<EFBFBD>n<EFBFBD>D.Y<><59>?rѐ<72><D190>XRfZ'<27><><EFBFBD><EFBFBD>Rs<52><04>5|o<><6F>{<7B>W<EFBFBD><57>I<EFBFBD>f<EFBFBD><66>^9<06><>LP.<2E>z<EFBFBD><7A><EFBFBD>bunn_<02>RX<1B>N<EFBFBD><06>%<25>9<EFBFBD><39><EFBFBD>w_<77><5F><<3C>x<EFBFBD><78>ɯ<EFBFBD><C9AF>G1<>={|"<22>p<EFBFBD><1E>F<EFBFBD><46>94.P[_
</pre>
# ECC
## C.1
<pre>
napieraccount@ubuntu:~/test$ openssl ecparam -name secp256k1 -genkey -out priv.pem
napieraccount@ubuntu:~/test$ cat priv.pem
-----BEGIN EC PARAMETERS-----
BgUrgQQACg==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHQCAQEEIIjZk1BI+xwWQZ6XetT17JrQgGLdQzvDnTB6iqLEFsGCoAcGBSuBBAAK
oUQDQgAE4VZg4yjli491gWC+f7mNAtI8pdRyHYXhUVjVTFlVXKvflEd3BxRiMUWC
KJPzklyIgOZFAOMYzSv5YvMA/YovWQ==
-----END EC PRIVATE KEY-----
</pre>
## C.2
Values are A, B, Generator (G) and Prime (p), and where G is the generator point. The curve is:
y<sup>2</sup>=x<sup>3</sup>+a x + b (mod p)
<pre>
napieraccount@ubuntu:~/test$ openssl ecparam -in priv.pem -text -param_enc explicit -noout
Field Type: prime-field
Prime:
00:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:
ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:fe:ff:
ff:fc:2f
A: 0
B: 7 (0x7)
Generator (uncompressed):
04:79:be:66:7e:f9:dc:bb:ac:55:a0:62:95:ce:87:
0b:07:02:9b:fc:db:2d:ce:28:d9:59:f2:81:5b:16:
f8:17:98:48:3a:da:77:26:a3:c4:65:5d:a4:fb:fc:
0e:11:08:a8:fd:17:b4:48:a6:85:54:19:9c:47:d0:
8f:fb:10:d4:b8
Order:
00:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:
ff:fe:ba:ae:dc:e6:af:48:a0:3b:bf:d2:5e:8c:d0:
36:41:41
Cofactor: 1 (0x1)
</pre>
## C.3
We generate the public key from the private key. If we have a private key (priv) and a generator point (G). The public key is priv G. In this case we are using a curve of secp256k1.
<pre>
napieraccount@ubuntu:~/test$ openssl ec -in priv.pem -text -noout
read EC key
Private-Key: (256 bit)
priv:
00:88:d9:93:50:48:fb:1c:16:41:9e:97:7a:d4:f5:
ec:9a:d0:80:62:dd:43:3b:c3:9d:30:7a:8a:a2:c4:
16:c1:82
pub:
04:e1:56:60:e3:28:e5:8b:8f:75:81:60:be:7f:b9:
8d:02:d2:3c:a5:d4:72:1d:85:e1:51:58:d5:4c:59:
55:5c:ab:df:94:47:77:07:14:62:31:45:82:28:93:
f3:92:5c:88:80:e6:45:00:e3:18:cd:2b:f9:62:f3:
00:fd:8a:2f:59
ASN1 OID: secp256k1
</pre>
How many bits and bytes does your private key have: **256 bits (32 bytes)**
How many bit and bytes does your public key have (Note the 04 is not part of the elliptic curve point): **512 bits (64 bytes)**
What is the ECC method that you have used? **secp256k1**
# ECC Encryption
## D.1
```python
import OpenSSL
import pyelliptic
secretkey="password"
test="Test123"
alice = pyelliptic.ECC()
bob = pyelliptic.ECC()
print "++++Keys++++"
print "Bob's private key: "+bob.get_privkey().encode('hex')
print "Bob's public key: "+bob.get_pubkey().encode('hex')
print
print "Alice's private key: "+alice.get_privkey().encode('hex')
print "Alice's public key: "+alice.get_pubkey().encode('hex')
ciphertext = alice.encrypt(test, bob.get_pubkey())
print "\n++++Encryption++++"
print "Cipher: "+ciphertext.encode('hex')
print "Decrypt: "+bob.decrypt(ciphertext)
signature = bob.sign("Alice")
print
print "Bob verified: "+ str(pyelliptic.ECC(pubkey=bob.get_pubkey()).verify
(signature, "Alice"))
```
<pre>
++++Keys++++
Bob's private key: 02f9f16a09b1e7dbb7b6697f94407616d9cd57965146f9fa93e6167c8d59239e09ec68da
Bob's public key: 040634cbbfe036049706a41449a8528bf0f72cb4ada794f57bcaffa7edf77106ac74ce86e605c488184302331d4586638a879b717e66d53ee65363330bfc9f0e780ffed18dab5ff6bf
Alice's private key: 037cfc7ee3bc58f54f213877003b0d3bf8e6d760cc4474ccf9d6fed2ae1b241c0bb9b733
Alice's public key: 04063eefc97bf6cf4b21f9cdad6899c77826f54c03db6c3b08b417bcaac605b53d9e1852f20369db917baa69e30b1a7eafaca8264028bee780701a957f81f8202c86c1f93515227a88
++++Encryption++++
Cipher: ad8e883133fcaf6d14bd7a8d66a610310406d6a7dfb1ea892d5a518ce9155abca28212ed103c4c194aef62462d62eb409e33e5203604291d73d25d0aa63228e1b91fca6339eb384c956b8df64bad1ec4b19883d6531c950ef9e53f4e4686cd8889bdef3edc6625263dd94360585bc3774273402f93d87211767ebd3bde961be86a121c52881873078a
Decrypt: Test123
Bob verified: True
</pre>
## D.2
y<sup>2</sup> = x<sup>3 + 7 (mod 89)
<pre>
A: 0
B: 7
Prime number: 89
Elliptic curve is: y^2=x^3+ 7
Finding the first 20 points
(14, 9) (15, 0) (16, 3) (17, 5) (22, 8) (24, 6) (40, 4) (60, 2) (70, 1) (71, 7)
</pre>
## D.3
<pre>
napier@napier-virtual-machine:~$ python ecc1.py
Message: Hello
Type: NIST192p
=========================
Signature: ntghRZKzExfLcoR2TJOw9J+ZJ+Pwq1+n/5UPUQqM5qoM9BKu/hUV/KMFvVIgDmU1
=========================
Signatures match: True
</pre>
# RSA
## E.1
```python
import rsa
(bob_pub, bob_priv) = rsa.newkeys(512)
print bob_pub
print bob_priv
ciphertext = rsa.encrypt('Here is my message', bob_pub)
message = rsa.decrypt(ciphertext, bob_priv)
print(message.decode('utf8'))
```
A sample run gives:
<pre>
PublicKey(7044152640361902500168576401792350494310726185372977704588682647070501920385795486653093710793158373161949147824992313215786223524754692116109993477603703,
65537)
PrivateKey(7044152640361902500168576401792350494310726185372977704588682647070501920385795486653093710793158373161949147824992313215786223524754692116109993477603703,
65537, 1031520101462581111343482730793310461173078401529280666355457029829494893917496934907266419334856470211959662572029962392609614789178286814805200163248601,
7009636621105341733056641551350073875772161289792261672243040042003271353299512989, 1004924081107519375914073833480034561474534624800691686376057520755477027)
Here is my message
</pre>
The keys are (e,N) for the public key, and (d,N) for the private key. In this case the value of N is:
<pre>
7044152640361902500168576401792350494310726185372977704588682647070501920385795486653093710793158373161949147824992313215786223524754692116109993477603703
</pre>
And e is:
<pre>
65537
</pre>
For the decryption key, N is the same value as the encryption key, and d is:
<pre>
1031520101462581111343482730793310461173078401529280666355457029829494893917496934907266419334856470211959662572029962392609614789178286814805200163248601
</pre>
The two prime numbers used (p and q) are then:
<pre>
7009636621105341733056641551350073875772161289792261672243040042003271353299512989 1004924081107519375914073833480034561474534624800691686376057520755477027
</pre>
Sample:
<pre>
>>> 7009636621105341733056641551350073875772161289792261672243040042003271353299512989*1004924081107519375914073833480034561474534624800691686376057520755477027
7044152640361902500168576401792350494310726185372977704588682647070501920385795486653093710793158373161949147824992313215786223524754692116109993477603703L
</pre>
# GPG
## F.1
<pre>
napieraccount@ubuntu:~/test$ gpg key01.key
pub 512R/362DD998 2019-01-19 bill <bill@home.com>
sub 512R/4AA5846A 2019-01-19
</pre>
## F.3
<pre>
napieraccount@ubuntu:~/test$ gpg --gen-key
gpg (GnuPG) 1.4.20; Copyright (C) 2015 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Please select what kind of key you want:
(1) RSA and RSA (default)
(2) DSA and Elgamal
(3) DSA (sign only)
(4) RSA (sign only)
Your selection? 1
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048)
Requested keysize is 2048 bits
Please specify how long the key should be valid.
0 = key does not expire
<n> = key expires in n days
<n>w = key expires in n weeks
<n>m = key expires in n months
<n>y = key expires in n years
Key is valid for? (0)
Key does not expire at all
Is this correct? (y/N) y
You need a user ID to identify your key; the software constructs the user ID
from the Real Name, Comment and Email Address in this form:
"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>"
Real name: Bill Buchanan
Email address: w.buchanan@napier.ac.uk
Comment: Test
You selected this USER-ID:
"Bill Buchanan (Test) <w.buchanan@napier.ac.uk>"
Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
You need a Passphrase to protect your secret key.
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
..+++++
......+++++
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
....+++++
+++++
gpg: key B3396725 marked as ultimately trusted
public and secret key created and signed.
gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0 valid: 3 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 3u
pub 2048R/B3396725 2020-02-05
Key fingerprint = C6AA 3C69 9BB9 B49F 1E19 55B7 4CA0 F614 B339 6725
uid Bill Buchanan (Test) <w.buchanan@napier.ac.uk>
sub 2048R/F06888D7 2020-02-05
</pre>
Next we export to the public key:
<pre>
napieraccount@ubuntu:~/test$ gpg --export -a "Bill Buchanan" > mypub.key
napieraccount@ubuntu:~/test$ cat mypub.key
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1
mI0EXjs2VQEEALlDB1D/z+7Ydqjus2JPcT53RrRjRSQtwlDlZ9omiisTlEvqw6rx
6OkXF9lqjM4q5mEN1BwKBaZfmYYwtsJUzV6GWz2p9lEtHWWtn8pv66ve8tGrBpGj
+Bbx3p5DnAq9rKuOKFXoNj35cda/xpYv4R7WyBeTgisRK4yEb9tbZeBpABEBAAG0
LkJpbGwgQnVjaGFuYW4gKFRlc3QpIDx3LmJ1Y2hhbmFuQG5hcGllci5hYy51az6I
uAQTAQIAIgUCXjs2VQIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQQGhL
ZyBWhFp+/AP/YiEtJTahVgmczHtVkfOTdGiQraJZLB9ZiRBOT+Qby6f5gNtPM1SB
DHARFORQ2d9pXDj4x8I7esx+7WfZyR7Yv6XQznpAGxaALLNy4fkCJV2vew/Err2Q
rVN8hLry67S5b9x7YpmygzBD0L6Y9hh1R7Jqc3M97XHc7sWk0eS9Xf+4jQReOzZV
AQQA5HIN6FoHZYNagQ45k/uFMtvE4h+QdCvdvNZthj/RmFwu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QIACQUCXjs3kgIbDAAKCRBMoPYUszlnJT2xCADMXKdKyGVNndzH8p7w
YJRIk3FlCNH4Bdc8WObJOoz3Q5PBeTW7H24uP2N8C0HxKLBulUulwRTP2sCOM2aI
ZGLVZ9wK+RkFy4W5EhbPpH7GgcAL8OyzPYPF7t75v8RUDd1b6YAVJRp3x4KCirmw
pOokmzaK9l5hlmL9UUS7CCpPxHXSJBW3fIDWcSp/RioAccpmjwxYwwdw5tB5pK4m
novRBvBxXrKPKI3WUbn0x+xS82p5ljnKrb67SyuJrdyYmuM9EWWssTEDM4rsqI6S
B8wk8IYFC750Z48Zs1GKWvkf4rBiaaLptCVRqTHmZzesOUdJg8lF+kY43aMrksrk
f4lt
=3RvZ
-----END PGP PUBLIC KEY BLOCK-----
</pre>
And the private key:
<pre>
napieraccount@ubuntu:~/test$ gpg --export-secret-key -a "Bill Buchanan" > mypriv.key
napieraccount@ubuntu:~/test$ cat mypriv.key
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v1
lQIGBF47NlUBBAC5QwdQ/8/u2Hao7rNiT3E+d0a0Y0UkLcJQ5WfaJoorE5RL6sOq
8ejpFxfZaozOKuZhDdQcCgWmX5mGMLbCVM1ehls9qfZRLR1lrZ/Kb+ur3vLRqwaR
o/gW8d6eQ5wKvayrjihV6DY9+XHWv8aWL+Ee1sgXk4IrESuMhG/bW2XgaQARAQAB
/gcDApolyggf99h6YNZz83Ov+sXT69rPdEQIMHdYauO3WkdABdGN0uFCMfEZGqBv
KBqCQhLxPEhmIfCrtnzNoZxajbCuZn5evD/oH5TH7Li3t/xgZq4GrdWydnwRmCRM
u0ttBAvzR4maPi1evFv7ztLsdrD6d/8RIYW5Wwo9n+kMI3axupb0EZtY1hO6TsUn
buKI54IDk9tP6+VJM0QIFsHYUcqG9/1du6gAZ7h+3Y+TDUSK0ihxXyz3v/kttlEg
dPLovHzLR9RSpCVsybk/LXR3FRbkXLetz1fYauSyzL9u9wwBCD/MSEYwu4sjyplW
C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YQoWDk5WRauftUkUBd989y9d78LjDTM8WASnqdsOaF
/l6P8bjRXUFsjAke0g/Bji2VZxwAqtcZ5HLbYXks2t6mAQXBF8OGhgl4z/gtAqPp
wGpP27G8ZiCr2L4Hog9FrXOKyCrrQf9zdtNj3KR+6armU+PWCg2JmAcntfA2TBmX
yO6SG5fCYookILTsK8yGyFMdJN1oQIb+TnJYC35FhPC0+foQ9H3xkeRlSzWMlJuw
qcSptWLItUc/bEFQ7G0kJEd0CxZdg5Exatl6iW6fTW+mzp3qRzONH/mEtFkfP4qM
3ZhQLz7MeOmoYvz7+WJXXoteYovla1IBKIW7iRODE+vD7zzgevw6ueKq2pNGhsZZ
HBM7VxP+iTmIyOAXEqIGKAv59Eb2dTmEu2EwcmCuRNd6oyIiVeIln8wuhRjKLbKP
3L1ujXvKpK4vZF6jY5hHjxk91fEJ0wSe/Wxl1cyQuBzvBFlFNkR/xdSVO6DmG7S0
86me8QHuw92oJLiwDVBrgSYcwG6QdhsRLhve9Ik/Szb3/ti6+c3WiQEfBBgBAgAJ
BQJeOzeSAhsMAAoJEEyg9hSzOWclPbEIAMxcp0rIZU2d3MfynvBglEiTcWUI0fgF
1zxY5sk6jPdDk8F5Nbsfbi4/Y3wLQfEosG6VS6XBFM/awI4zZohkYtVn3Ar5GQXL
hbkSFs+kfsaBwAvw7LM9g8Xu3vm/xFQN3VvpgBUlGnfHgoKKubCk6iSbNor2XmGW
Yv1RRLsIKk/EddIkFbd8gNZxKn9GKgBxymaPDFjDB3Dm0Hmkriaei9EG8HFeso8o
jdZRufTH7FLzanmWOcqtvrtLK4mt3Jia4z0RZayxMQMziuyojpIHzCTwhgULvnRn
jxmzUYpa+R/isGJpoum0JVGpMeZnN6w5R0mDyUX6RjjdoyuSyuR/iW0=
=Ul23
-----END PGP PRIVATE KEY BLOCK-----
</pre>
## H.1
Password: napier
![tc](https://github.com/billbuchanan/esecurity/blob/master/unit04_public_key/lab/tc.png)

Binary file not shown.

After

Width:  |  Height:  |  Size: 265 KiB

View File

@@ -0,0 +1,35 @@
![esecurity](https://raw.githubusercontent.com/billbuchanan/esecurity/master/z_associated/esecurity_graphics.jpg)
# e-Security Unit 4: Public Key
The key concepts are: Basics, RSA, Elliptic Curve and ElGamal.
## What you should know at the end of unit?
* Explain how public key provides both privacy and identity verification.
* Where would I find this info? This unit explains public key.
* Understand how the RSA process works, with a simple example.
* Understand how elliptic curve cryptography works, with a simple example.
* Explain the operation of PGP.
* Understands how the private key is used to check the identity of the sender, and how public key is used to preserve the privacy of the message.
* Explain how the e and d values are determined within the RSA method.
* Where would I find this info? There are some examples [here](https://asecuritysite.com/log/rsa_examples.pdf).
## Presentations
* Week 4 Presentation (PDF) - Public Key Encryption: [here](https://github.com/billbuchanan/esecurity/blob/master/unit04_public_key/lecture/chapter04_public_msc.pdf).
* Week 4 Presentation (video) - Public Key Encryption: [here](https://youtu.be/QEYqkxuzoTg).
* Week 4 Presentation (lecture video - 8 Feb 2020) - Public Key Encryption: [here](https://www.youtube.com/watch?v=PEdCHWdE3zk).
## Examples
RSA Examples: [here](https://asecuritysite.com/public/rsa_examples.pdf)
## Quick demos
* Introduction to RSA: [here](https://www.youtube.com/watch?v=pHES8eNor6k)
* Introduction to Elliptic Curve: [here](https://youtu.be/_CwIWk6XDmg)
* Picking the Generator Value (G): [here](https://www.youtube.com/watch?v=-TjSuch3VGU)

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,32 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v2
mQENBFTzi1ABCADIEWchOyqRQmU4AyQAMj2Pn68Sqo9lTPdPcItwo9LbTdv1YCFz
w3qLlp2RORMP+Kpdi92CIhdUYHDmZfHZ3IWTBgo9+y/Np9UJ6tNGocrgsq4xWz15
4vX4jJRddC7QySSh9UxDpRWf9sgqEv1pah136r95ZuyjC1EXnoNxdLJtx8PliCXc
hV/v4+KfOyzYh+HDJ4xP2bt1S07dkasYZ6cA7BHYi9k4xgEwxVvYtN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jfP+owEhs8/Ez0j1/fSKIqAdlz3mB
dbqWPjzPTY/m0It+wv3epOM75uWjD35PF0rKxxZmEf6SrjZD1sk0B9bRy2v9iWN9
9ZkuvcfH4vT++PognQLTUqNx0FGpD1agrG0lXSCtJWQXCXPfWdtbIdThBgzH4flZ
ssAIbCaBlQkzfbPvrMzdTIP+AXg6++K9SnO9N/FRPYzjUSEmpRp+ox31WymvczcU
RmyUquF+/zNnSBVgtY1rzwaYi05XfuxG0WHVHPTtRyJ5pF4HSqiuvk6Z/4z3bw==
=ZrP+
-----END PGP PUBLIC KEY BLOCK-----

Some files were not shown because too many files have changed in this diff Show More