SlideShare a Scribd company logo
Blockchain Cryptography for Devs
Elliptic Curves, ECC, ECDSA,
secp256k1, Hash Functions, Wallets,
AES, SCrypt, HMAC, BIP39, BIP44
Svetlin Nakov
Inspiration Manager
Software University
http://softuni.bg
2
 Software engineer, trainer, entrepreneur,
PhD, author of 10 books, blockchain expert
 3 successful tech educational initiatives:
About Svetlin Nakov
3
 Elliptic Curve Cryptography (ECC)
 ECC Concepts, Elliptic Curves, the secp256k1 Curve
 Private Key  Public Key  Blockchain Address
 Sign / Verify Transactions in Ethereum
 Cryptographic Hash Functions: SHA256, SHA3, RIPEMD160, …
 HMAC and Key Derivation: HMAC, PBKDF2, SCrypt
 Blockchain Cryptography and Wallets: JSON / UTC, BIP39, BIP44
 Wallet Encryption: AES + Padding + CBC/CTR, SCrypt, HMAC
Table of Contents
Elliptic Curve Cryptography (ECC)
Elliptic Curves, ECC and ECDSA, Sign, Verify
5
 Uses a pair of keys: public key + private key
 Encrypt / sign by private key
 Decrypt / verify by public key
Public Key Cryptography
6
 Well-known public-key crypto-systems
 RSA – based on discrete logarithms
 ECC – based on elliptic curves
 ECC cryptography is considered more secure
 3072-bit RSA key ≈≈ 256-bit ECC key
 Most blockchains (like Bitcoin and Ethereum) use ECC
 But be warned: ECC is not quantum-safe!
Public Key Crypto Systems
7
 Public / private key cryptography
based on the algebraic structure of
elliptic curves over finite fields
 Requires smaller key-size than RSA
for the same security strength
 Elliptic curves == set of points {x, y}
such that:
 y2 = x3 + ax + b
 Example – the Bitcoin elliptic curve:
 y2 = x3 + 7 (a = 0; b = 7)
Elliptic Curve Cryptography (ECC)
8
 Elliptic curves cryptography (ECC)
 Uses ecliptic curves over the finite
field Fp (p is prime, p > 3)
 A set of integer coordinates
{x, y}, such that 0 ≤ x, y < p
 Staying on the elliptic curve:
y2 ≡ x3 + ax + b (mod p)
 Example of elliptic curve over F17:
 y2 ≡ x3 + 7 (mod 17)
Elliptic Curves over a Finite Fields
y2 ≡ x3 + 7 (mod 17)
9
 A point G over the curve can be
multiplied by an integer k
 P = k * G
 The result is another point P
staying on the same curve
 k == private key (integer)
 P == public key (point {x, y})
 Very fast to calculate P = k * G
 Extremely slow (considered infeasible) to calculate k = P / G
Multiply a Point Over an Elliptic Curve
y2 ≡ x3 + 7 (mod 17)
G
P
10
Elliptic Curves Multiplication in Python
from pycoin.ecdsa import Point
from pycoin.ecdsa import CurveFp
curve = CurveFp(17, 0, 7)
print("Curve = " + str(curve))
G = Point(curve, 15, 13)
print("G = " + str(G))
for k in range(0, 6) :
print(str(k) + " * G = " + str(k * G))
pip install pycoin
11
 The elliptic curves over Fp
 Have at most 2 points per y
coordinate (odd x and even x)
 A public key P(x, y) can be
compressed as C(x, odd/even)
 At the curve y2 ≡ x3 + 7 (mod 17)
P(10, 15) == C(10, odd)
 mod_sqrt(x3 + 7, 17) == y || 17 - y
Compressing the Public Key
y2 ≡ x3 + 7 (mod 17)
12
 ECC operates with a set of EC domain parameters:
 T = (p, a, b, G, n, h)
 Prime field (prime p), elliptic equation (a, b), base point G(xG, yG),
order of G (prime n), cofactor (h)
 The secp256k1 standard (used in Bitcoin) defines 256-bit
elliptic-curves cryptosystem:
 Prime field (p) = 2256 - 232 - 977; Equation: y2 = x3 + 7 (a = 0, b = 7)
 G = 0x79BE667E …; n = 0xFFF…D0364141; h = 1
ECC Parameters and secp256k1
Learn more at: http://www.secg.org/sec2-v2.pdf, https://en.bitcoin.it/wiki/Secp256k1
13
 The private key in secp256k1 is 256-bit integer (32 bytes)
 Example of Ethereum private key (encoded as 64 hex digits)
 The respective public key is a EC point (2 * 256 bits == 64 bytes)
 Can be compressed to 257 bits (Ethereum uses prefix 02 or 03)
 Example of compressed public key (33 bytes / 66 hex digits):
Ethereum Addresses and secp256k1
97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a
027b83ad6afb1209f3c82ebeb08c0c5fa9bf6724548506f2fb4f991e2287a77090
7b83ad6afb1209f3c82ebeb08c0c5fa9bf6724548506f2fb4f991e2287a77090
177316ca82b0bdf70cd9dee145c3002c0da1d92626449875972a27807b73b42e
14
 The blockchain address in Ethereum is 20 bytes
 Calculated as: last20bytes(keccak256(publicKeyFull))
 Example of Ethereum address (encoded as 40 hex digits):
 Note: some letters are capital to incorporate a checksum (EIP55)
 Digital signatures in secp256k1 are 64 bytes (2 * 32 bytes)
 A pair of two 256-bit numbers: [r, s]
 Calculated by the well-known ECDSA formulas (see RFC6979)
ECDSA, secp256k1 and Ethereum (2)
0xa44f70834a711F0DF388ab016465f2eEb255dEd0
15
Ethereum Key to Addresses – Example
pip install eth_keys
import eth_keys, binascii
privKey = eth_keys.keys.PrivateKey(binascii.unhexlify(
'97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a'))
print('Private key (64 hex digits):', privKey)
pubKey = privKey.public_key
print('Public key (plain, 128 hex digits):', pubKey)
pubKeyCompr = '0' + str(2 + int(pubKey) % 2) + str(pubKey)[2:66]
print('Public key (compressed, 66 hex digits):', pubKeyCompr)
address = pubKey.to_checksum_address()
print('Ethereum address:', address)
16
 Ethereum uses secp256k1-based ECDSA signatures
 ECDSA generates deterministically a random point R (see RFC6979)
 Ethereum signatures consists of 3 numbers: [v, r, s]
 v – the compressed Y coordinate of the point R (1 byte: 00 or 01)
 r – the X coordinate of the point R (256-bit integer, 32 bytes)
 s – 256-bit integer (32 bytes), calculated from the signer's private key +
message hash (Ethereum uses keccak256)
 Typically encoded as 130 hex digits (65 bytes), e.g. 0x…465c5cf4be401
 Given an Ethereum signature [v, r, s], the public key can be recovered
from [R, s, msgHash]  also the signer's Ethereum address
Verifying an Ethereum Signature
17
Sign Message in Ethereum – Example
import eth_keys, binascii
privKey = eth_keys.keys.PrivateKey(binascii.unhexlify(
'97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a'))
print('Private key (64 hex digits):', privKey)
signature = privKey.sign_msg(b'Message for signing')
print('Signature: [v = {0}, r = {1}, s = {2}]'.format(
hex(signature.v), hex(signature.r), hex(signature.s)))
print('Signature (130 hex digits):', signature)
18
Verify Message Signature in Etherscan
 Verify message signature at https://etherscan.io/verifySig by:
 signer address (40 hex digits)
 signature (130 hex digits)
 original message text
 The result is: valid / invalid
19
Verify Ethereum Signature – Example
import eth_keys, binascii
msg = b'Message for signing'
msgSigner = '0xa44f70834a711F0DF388ab016465f2eEb255dEd0'
signature = eth_keys.keys.Signature(binascii.unhexlify(
'6f0156091cbe912f2d5d1215cc3cd81c0963c8839b93af60e0921b61a1
9c54300c71006dd93f3508c432daca21db0095f4b16542782b7986f48a5
d0ae3c583d401'))
signerPubKey = signature.recover_public_key_from_msg(msg)
print('Signer public key (recovered):', signerPubKey)
signerAddress = signerPubKey.to_checksum_address()
print('Signer address:', signerAddress)
print('Signature valid?:', signerAddress == msgSigner)
Hashing and Hash Functions
Cryptographic Hash Functions
21
What is Cryptographic Hash Function?
Some text
Some text
Some text
Some text
Some text
Some text
Some text
20c9ad97c081d63397d
7b685a412227a40e23c
8bdc6688c6f37e97cfbc2
2d2b4d1db1510d8f61e
6a8866ad7f0e17c02b14
182d37ea7c3c8b9c2683
aeb6b733a1
Text Hashed text
Cryptographic
hash function
(almost no collisions)
22
Cryptographic Hash Function
 One-way hash function
 Infeasible to invert
 Extremely little chance
to find a collision
23
 Old hash algorithms: MD5, SHA-0, SHA-1
 Withdrawn due to cryptographic weaknesses (collisions found)
 SHA-2
 Family of functions: SHA-256 (256 bits hash), SHA-512 (512 bits), …
 SHA-3
 More secure, same hash length (256 bits), known as "Keccak"
 RIPEMD-160
 Secure hash function, widely used in cryptography, e.g. PGP, Bitcoin
 Less secure variations: RIPEMD-128, RIPEMD-256, RIPEMD-320
Secure Hash Functions
24
 BLAKE / BLAKE2 / BLAKE2s / BLAKE2b
 Fast, secure cryptographic hash function
 256-bit (BLAKE-256, BLAKE2s) and 512-bit (BLAKE-512, BLAKE2b)
 As of April 2018, no collisions are known for:
 SHA256, SHA3-256, Keccak-256, BLAKE2s, RIPEMD160
 Brute forcing to find a collision costs: 2128 for SHA256/SHA3-256
and 280 for RIPEMD160 (285 / 285 on quantum computer)
 512-bit hashes (SHA-512 / SHA3-512) are Quantum-resistant
Secure Hash Algorithms (2)
25
Calculating Hash Functions in Python
import hashlib, binascii
text = 'hello'
data = text.encode("utf8")
sha256hash = hashlib.sha256(data).digest()
print("SHA256: ", binascii.hexlify(sha256hash))
sha3_256 = hashlib.sha3_256(data).digest()
print("SHA3-256: ", binascii.hexlify(sha3_256))
ripemd160 = hashlib.new('ripemd160', data).digest()
print("RIPEMD-160:", binascii.hexlify(ripemd160))
HMAC and Key Derivation
MAC, HMAC, PBKDF2 and SCrypt
27
 HMAC = Hash-based Message Authentication Code
 HMAC(key, msg, hash_func)  hash
 Message hash mixed with a secret shared key
 Used for message integrity / authenticity / key derivation
 Key derivation function (KDF) == function(password)  key
 Use HKDF (HMAC-based key derivation), PBKDF2 or SCrypt
 PBKDF2, BCrypt and SCrypt are modern key-derivation functions
 Use a lot of iterations + a lot of memory  to make it slow
HMAC and Key Derivation
28
HMAC Calculation in Python – Example
import hashlib, hmac, binascii
def hmac_sha256(key, msg):
return hmac.new(key, msg, hashlib.sha256).digest()
key = binascii.unhexlify("fa63f2b4c85af6bed3")
msg = "some message".encode("utf8")
print(binascii.hexlify(hmac_sha256(key, msg)))
29
 SCrypt (RFC 7914) is a strong cryptographic key-derivation function
 Memory intensive, designed to prevent ASIC and FPGA attacks
 key = Scrypt(password, salt, N, r, p, derived-key-len)
 N – iterations count (affects memory and CPU usage), e.g. 16384
 r – block size (affects memory and CPU usage), e.g. 8
 p – parallelism factor (threads to run in parallel), usually 1
 Memory used = 128 * N * r * p bytes, e.g. 128 * 16384 * 8 = 16 MB
 Parameters for interactive login: N=16384, r=8, p=1 (RAM=16MB)
 Parameters for file encryption: N=1048576, r=8, p=1 (RAM=1GB)
Key Derivation Functions: Scrypt
30
SCrypt Key Derivation in Python – Example
import scrypt, os, binascii
passwd = "p@$$w0rD~3"
salt = os.urandom(32)
print("Salt: ", binascii.hexlify(salt))
key = scrypt.hash(passwd, salt, 16384, 8, 1, 32)
print("Derived key:", binascii.hexlify(key))
pip install scrypt
Blockchain Cryptography and Wallets
Keys, Addresses, Signatures, Wallets
32
Public / Private Keys, Wallets & Blockchain
private key public key address
transaction
sign by private key
signed
transaction
valid / invalid
verify by address
wallet master
key (seed)
signed
transaction
transaction data
public key: (x, y)
signature: (v, r, s)
33
 In blockchain wallets keep private keys, highly encrypted
 Simple wallet (keystore) keeps a single private key
 Example: https://gist.github.com/nakov/53f869e01c9b573844c48e5966e33a3f
 HD wallet (hierarchical wallet) keeps multiple private keys
 Hierarchically derived by a master key (seed) by derivation path
 The seed is encoded as mnemonic phrase (12 / 24 words)
 Example: https://iancoleman.io/bip39/
HD Wallets, BIP39, BIP32 / BIP44
hill brave science fox crime quit owner chapter myth vocal chat custom
34
 The BIP-32 standard defines how a crypto-wallet can generate
multiple keys + addresses
 The wallet is initialized by
a 512-bit master key (seed)
 HMAC + ECC math used to
generate multiple accounts
 Through a derivation path
 E.g. m/44'/60'/1'/12
 Each account holds private
key  public key  address
ECC and Wallets: BIP32
35
 Most modern crypto wallets start from a 512-bit securely
generated random seed (see the BIP-39 standard)
 The seed (root key) can be represented by 12 or 24 words, e.g.
 Each word comes from a wordlist of 2048 words
 See https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt
 1 word == 11 bits of entropy
 12 words == 132 bits == 128-bit entropy + checksum (in the last word)
 24 words == 264 bits == 256-bit entropy + checksum (in the last word)
Internal Seed in Crypto Wallets
hill brave science fox crime quit owner chapter myth vocal chat custom
BIP-39 Mnemonic
Seed Generator
Live Demo
https://iancoleman.io/bip39
Wallet Encryption and AES
AES, CBC/CTR, Padding, SCrypt, HMAC
38
 A single secret key to
encrypt / decrypt
 The secret key is usually
derived by a password
 Both the sender and the
recipient should know
the secret key
 Widely used symmetric
algorithms: AES-128,
AES-256, Twofish, IDEA
Symmetric Encryption
 Wallets are typically encrypted using
symmetric ciphers like AES
39
 AES is a "block cipher" – encrypts block by block (e.g. 128 bits)
 It has several modes of operation (CBC, ECB, CTR, …)
 Some modes of operation require initial vector (IV)
 Non-secret random salt  used to get different result each time
 Recommended modes: CBC (Cipher Block Chaining) or CTR (Counter)
 It may use a padding algorithm (typically PKCS7) to split the input
data into blocks of fixed block-size (e.g. 128 bits)
 It may use password to key derivation: key = SCrypt(pass, salt, …)
 It may use MAC to check the password validity: HMAC(text, key)
AES Cipher Settings
40
Example: AES Encrypt / Decrypt in Python
import pyaes, pbkdf2, binascii, os, secrets
plaintext = "Sample text for encryption"
password = "s0m3p@$$w0rd"
key = pbkdf2.PBKDF2(password, 'some salt').read(16)
print('AES encryption key:', binascii.hexlify(key))
iv = secrets.randbelow(2 << 128)
aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
ciphertext = aes.encrypt(plaintext)
print('encrypted:', binascii.hexlify(ciphertext))
aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
decrypted = aes.decrypt(ciphertext)
print('decrypted:', decrypted)
pip install pyaes
pip install pbkdf2
41
Ethereum UTC / JSON Wallet Encryption
{ "version": 3, "id": "…", "address": "b97e993872a9050c07f…ef195",
"Crypto": {
"ciphertext": "bc9215b2cd1571df…e3a1", // the encrypted private key
"cipher": "aes-128-ctr", // AES, 128-bit encryption, CTR mode
"cipherparams": { "iv": "2bac08cafc…8e" }, // random initial vector
"kdf": "scrypt", "kdfparams": {
"dklen": 32, // key length (256-bit key for AES encryption)
"salt": "7d48230c94b90c0301bf9f4…eba1", // random-generated salt
"n": 1024, // iterations count (CPU + memory cost factor)
"r": 8, // block size (affects CPU + memory)
"p": 1 // parallelization factor (threads count)
},
"mac": "e3cd7ea4e3ceb0e9a…0564" // msg integrity key (password check)
} } Learn more at: https://github.com/ethers-io/ethers.js/blob/master/wallet/secret-storage.js#L288
?
Blockchain Cryptography for Devs
License
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
43
Trainings @ Software University (SoftUni)
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg
 Software University Foundation
 http://softuni.foundation/
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg

More Related Content

PDF
Zero-Knowledge Proofs: Privacy-Preserving Digital Identity with Clare Nelson
PDF
Bitcoin Addresses
PPTX
BLOCKCHAIN
PDF
Introduction to Blockchain
PPTX
IoT and Blockchain Challenges and Risks
PPTX
Cryptography and network security Nit701
PPTX
Block chain technology
PDF
Basics of Blockchain Technology
Zero-Knowledge Proofs: Privacy-Preserving Digital Identity with Clare Nelson
Bitcoin Addresses
BLOCKCHAIN
Introduction to Blockchain
IoT and Blockchain Challenges and Risks
Cryptography and network security Nit701
Block chain technology
Basics of Blockchain Technology

What's hot (20)

PDF
Introduction to Blockchain
PPTX
Blockchain 101 by imran bashir
PDF
Overview of blockchain technology and architecture
 
PPTX
What's cryptocurrency ?
PDF
Keccak
PDF
An Introduction to Blockchain Technology
PPTX
blockchain and iot: Opportunities and Challanges
PPTX
Introduction to Blockchain and Smart Contracts
PPTX
Basic Cryptography unit 4 CSS
PDF
Public key Infrastructure (PKI)
PPTX
Blockchain ecosystem and evolution
PDF
Basics of Bitcoin & Mining
PPTX
Bitcoin Script
PDF
Bitcoin Keys, Addresses & Wallets
PPTX
Introduction to Bitcoin's Scripting Language
PDF
Hyperledger Fabric Technical Deep Dive 20190618
PDF
Blockchain & the IoT
PPTX
Blockchain and distributed ledgers
PPTX
Blockchain Technology
PDF
Layer 2 Scaling Solutions
Introduction to Blockchain
Blockchain 101 by imran bashir
Overview of blockchain technology and architecture
 
What's cryptocurrency ?
Keccak
An Introduction to Blockchain Technology
blockchain and iot: Opportunities and Challanges
Introduction to Blockchain and Smart Contracts
Basic Cryptography unit 4 CSS
Public key Infrastructure (PKI)
Blockchain ecosystem and evolution
Basics of Bitcoin & Mining
Bitcoin Script
Bitcoin Keys, Addresses & Wallets
Introduction to Bitcoin's Scripting Language
Hyperledger Fabric Technical Deep Dive 20190618
Blockchain & the IoT
Blockchain and distributed ledgers
Blockchain Technology
Layer 2 Scaling Solutions
Ad

Similar to Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018) (20)

PPTX
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)
PDF
Blockchain and Cryptography - A Primer
PPTX
Cryptography in a use case of Blockchain.pptx
PPT
Elliptic Curve Digital Signature Algorithm (ECDSA).ppt
PDF
Lec 4 Public Key Cryptography & Digital Identity 2022f.pdf
PPTX
Smart City Lecture 5 - Introduction to Encryption
PDF
A Survey on Elliptic Curve Cryptography
PPT
1524 elliptic curve cryptography
PDF
Blockchain 101 - Introduction for Developers
PPTX
Bitcoin MOOC Lecture 1.pptx
PDF
CNIT 141 12. Elliptic Curves
PPTX
ECC.pptx Ecc cryptography for secure encrypted message and decryption using ...
PDF
Topic 2 Blockchain Fundamentals - Cryptography BW.pdf
PPTX
J.burke HackMiami6
PDF
CNIT 141 12. Elliptic Curves
PPTX
Cryptography Key Management.pptx
PDF
12 Elliptic Curves
PDF
CNIT 141 12. Elliptic Curves
PDF
CNIT 141: 12. Elliptic Curves
PDF
Design Of Elliptic Curve Crypto Processor with Modified Karatsuba Multiplier ...
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)
Blockchain and Cryptography - A Primer
Cryptography in a use case of Blockchain.pptx
Elliptic Curve Digital Signature Algorithm (ECDSA).ppt
Lec 4 Public Key Cryptography & Digital Identity 2022f.pdf
Smart City Lecture 5 - Introduction to Encryption
A Survey on Elliptic Curve Cryptography
1524 elliptic curve cryptography
Blockchain 101 - Introduction for Developers
Bitcoin MOOC Lecture 1.pptx
CNIT 141 12. Elliptic Curves
ECC.pptx Ecc cryptography for secure encrypted message and decryption using ...
Topic 2 Blockchain Fundamentals - Cryptography BW.pdf
J.burke HackMiami6
CNIT 141 12. Elliptic Curves
Cryptography Key Management.pptx
12 Elliptic Curves
CNIT 141 12. Elliptic Curves
CNIT 141: 12. Elliptic Curves
Design Of Elliptic Curve Crypto Processor with Modified Karatsuba Multiplier ...
Ad

More from Svetlin Nakov (20)

PPTX
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
PPTX
AI за ежедневието - Наков @ Techniverse (Nov 2024)
PPTX
AI инструменти за бизнеса - Наков - Nov 2024
PPTX
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
PPTX
Software Engineers in the AI Era - Sept 2024
PPTX
Най-търсените направления в ИТ сферата за 2024
PPTX
BG-IT-Edu: отворено учебно съдържание за ИТ учители
PPTX
Programming World in 2024
PDF
AI Tools for Business and Startups
PPTX
AI Tools for Scientists - Nakov (Oct 2023)
PPTX
AI Tools for Entrepreneurs
PPTX
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
PPTX
AI Tools for Business and Personal Life
PDF
Дипломна работа: учебно съдържание по ООП - Светлин Наков
PPTX
Дипломна работа: учебно съдържание по ООП
PPTX
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
PPTX
AI and the Professions of the Future
PPTX
Programming Languages Trends for 2023
PPTX
IT Professions and How to Become a Developer
PPTX
GitHub Actions (Nakov at RuseConf, Sept 2022)
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
AI за ежедневието - Наков @ Techniverse (Nov 2024)
AI инструменти за бизнеса - Наков - Nov 2024
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
Software Engineers in the AI Era - Sept 2024
Най-търсените направления в ИТ сферата за 2024
BG-IT-Edu: отворено учебно съдържание за ИТ учители
Programming World in 2024
AI Tools for Business and Startups
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Entrepreneurs
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
AI Tools for Business and Personal Life
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
AI and the Professions of the Future
Programming Languages Trends for 2023
IT Professions and How to Become a Developer
GitHub Actions (Nakov at RuseConf, Sept 2022)

Recently uploaded (20)

PDF
Understanding Forklifts - TECH EHS Solution
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
top salesforce developer skills in 2025.pdf
PDF
Nekopoi APK 2025 free lastest update
PPTX
Transform Your Business with a Software ERP System
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Digital Strategies for Manufacturing Companies
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
L1 - Introduction to python Backend.pptx
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Understanding Forklifts - TECH EHS Solution
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
top salesforce developer skills in 2025.pdf
Nekopoi APK 2025 free lastest update
Transform Your Business with a Software ERP System
2025 Textile ERP Trends: SAP, Odoo & Oracle
Wondershare Filmora 15 Crack With Activation Key [2025
Digital Strategies for Manufacturing Companies
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Upgrade and Innovation Strategies for SAP ERP Customers
Softaken Excel to vCard Converter Software.pdf
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
L1 - Introduction to python Backend.pptx
How to Migrate SBCGlobal Email to Yahoo Easily
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Which alternative to Crystal Reports is best for small or large businesses.pdf
Navsoft: AI-Powered Business Solutions & Custom Software Development
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf

Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)

  • 1. Blockchain Cryptography for Devs Elliptic Curves, ECC, ECDSA, secp256k1, Hash Functions, Wallets, AES, SCrypt, HMAC, BIP39, BIP44 Svetlin Nakov Inspiration Manager Software University http://softuni.bg
  • 2. 2  Software engineer, trainer, entrepreneur, PhD, author of 10 books, blockchain expert  3 successful tech educational initiatives: About Svetlin Nakov
  • 3. 3  Elliptic Curve Cryptography (ECC)  ECC Concepts, Elliptic Curves, the secp256k1 Curve  Private Key  Public Key  Blockchain Address  Sign / Verify Transactions in Ethereum  Cryptographic Hash Functions: SHA256, SHA3, RIPEMD160, …  HMAC and Key Derivation: HMAC, PBKDF2, SCrypt  Blockchain Cryptography and Wallets: JSON / UTC, BIP39, BIP44  Wallet Encryption: AES + Padding + CBC/CTR, SCrypt, HMAC Table of Contents
  • 4. Elliptic Curve Cryptography (ECC) Elliptic Curves, ECC and ECDSA, Sign, Verify
  • 5. 5  Uses a pair of keys: public key + private key  Encrypt / sign by private key  Decrypt / verify by public key Public Key Cryptography
  • 6. 6  Well-known public-key crypto-systems  RSA – based on discrete logarithms  ECC – based on elliptic curves  ECC cryptography is considered more secure  3072-bit RSA key ≈≈ 256-bit ECC key  Most blockchains (like Bitcoin and Ethereum) use ECC  But be warned: ECC is not quantum-safe! Public Key Crypto Systems
  • 7. 7  Public / private key cryptography based on the algebraic structure of elliptic curves over finite fields  Requires smaller key-size than RSA for the same security strength  Elliptic curves == set of points {x, y} such that:  y2 = x3 + ax + b  Example – the Bitcoin elliptic curve:  y2 = x3 + 7 (a = 0; b = 7) Elliptic Curve Cryptography (ECC)
  • 8. 8  Elliptic curves cryptography (ECC)  Uses ecliptic curves over the finite field Fp (p is prime, p > 3)  A set of integer coordinates {x, y}, such that 0 ≤ x, y < p  Staying on the elliptic curve: y2 ≡ x3 + ax + b (mod p)  Example of elliptic curve over F17:  y2 ≡ x3 + 7 (mod 17) Elliptic Curves over a Finite Fields y2 ≡ x3 + 7 (mod 17)
  • 9. 9  A point G over the curve can be multiplied by an integer k  P = k * G  The result is another point P staying on the same curve  k == private key (integer)  P == public key (point {x, y})  Very fast to calculate P = k * G  Extremely slow (considered infeasible) to calculate k = P / G Multiply a Point Over an Elliptic Curve y2 ≡ x3 + 7 (mod 17) G P
  • 10. 10 Elliptic Curves Multiplication in Python from pycoin.ecdsa import Point from pycoin.ecdsa import CurveFp curve = CurveFp(17, 0, 7) print("Curve = " + str(curve)) G = Point(curve, 15, 13) print("G = " + str(G)) for k in range(0, 6) : print(str(k) + " * G = " + str(k * G)) pip install pycoin
  • 11. 11  The elliptic curves over Fp  Have at most 2 points per y coordinate (odd x and even x)  A public key P(x, y) can be compressed as C(x, odd/even)  At the curve y2 ≡ x3 + 7 (mod 17) P(10, 15) == C(10, odd)  mod_sqrt(x3 + 7, 17) == y || 17 - y Compressing the Public Key y2 ≡ x3 + 7 (mod 17)
  • 12. 12  ECC operates with a set of EC domain parameters:  T = (p, a, b, G, n, h)  Prime field (prime p), elliptic equation (a, b), base point G(xG, yG), order of G (prime n), cofactor (h)  The secp256k1 standard (used in Bitcoin) defines 256-bit elliptic-curves cryptosystem:  Prime field (p) = 2256 - 232 - 977; Equation: y2 = x3 + 7 (a = 0, b = 7)  G = 0x79BE667E …; n = 0xFFF…D0364141; h = 1 ECC Parameters and secp256k1 Learn more at: http://www.secg.org/sec2-v2.pdf, https://en.bitcoin.it/wiki/Secp256k1
  • 13. 13  The private key in secp256k1 is 256-bit integer (32 bytes)  Example of Ethereum private key (encoded as 64 hex digits)  The respective public key is a EC point (2 * 256 bits == 64 bytes)  Can be compressed to 257 bits (Ethereum uses prefix 02 or 03)  Example of compressed public key (33 bytes / 66 hex digits): Ethereum Addresses and secp256k1 97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a 027b83ad6afb1209f3c82ebeb08c0c5fa9bf6724548506f2fb4f991e2287a77090 7b83ad6afb1209f3c82ebeb08c0c5fa9bf6724548506f2fb4f991e2287a77090 177316ca82b0bdf70cd9dee145c3002c0da1d92626449875972a27807b73b42e
  • 14. 14  The blockchain address in Ethereum is 20 bytes  Calculated as: last20bytes(keccak256(publicKeyFull))  Example of Ethereum address (encoded as 40 hex digits):  Note: some letters are capital to incorporate a checksum (EIP55)  Digital signatures in secp256k1 are 64 bytes (2 * 32 bytes)  A pair of two 256-bit numbers: [r, s]  Calculated by the well-known ECDSA formulas (see RFC6979) ECDSA, secp256k1 and Ethereum (2) 0xa44f70834a711F0DF388ab016465f2eEb255dEd0
  • 15. 15 Ethereum Key to Addresses – Example pip install eth_keys import eth_keys, binascii privKey = eth_keys.keys.PrivateKey(binascii.unhexlify( '97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a')) print('Private key (64 hex digits):', privKey) pubKey = privKey.public_key print('Public key (plain, 128 hex digits):', pubKey) pubKeyCompr = '0' + str(2 + int(pubKey) % 2) + str(pubKey)[2:66] print('Public key (compressed, 66 hex digits):', pubKeyCompr) address = pubKey.to_checksum_address() print('Ethereum address:', address)
  • 16. 16  Ethereum uses secp256k1-based ECDSA signatures  ECDSA generates deterministically a random point R (see RFC6979)  Ethereum signatures consists of 3 numbers: [v, r, s]  v – the compressed Y coordinate of the point R (1 byte: 00 or 01)  r – the X coordinate of the point R (256-bit integer, 32 bytes)  s – 256-bit integer (32 bytes), calculated from the signer's private key + message hash (Ethereum uses keccak256)  Typically encoded as 130 hex digits (65 bytes), e.g. 0x…465c5cf4be401  Given an Ethereum signature [v, r, s], the public key can be recovered from [R, s, msgHash]  also the signer's Ethereum address Verifying an Ethereum Signature
  • 17. 17 Sign Message in Ethereum – Example import eth_keys, binascii privKey = eth_keys.keys.PrivateKey(binascii.unhexlify( '97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a')) print('Private key (64 hex digits):', privKey) signature = privKey.sign_msg(b'Message for signing') print('Signature: [v = {0}, r = {1}, s = {2}]'.format( hex(signature.v), hex(signature.r), hex(signature.s))) print('Signature (130 hex digits):', signature)
  • 18. 18 Verify Message Signature in Etherscan  Verify message signature at https://etherscan.io/verifySig by:  signer address (40 hex digits)  signature (130 hex digits)  original message text  The result is: valid / invalid
  • 19. 19 Verify Ethereum Signature – Example import eth_keys, binascii msg = b'Message for signing' msgSigner = '0xa44f70834a711F0DF388ab016465f2eEb255dEd0' signature = eth_keys.keys.Signature(binascii.unhexlify( '6f0156091cbe912f2d5d1215cc3cd81c0963c8839b93af60e0921b61a1 9c54300c71006dd93f3508c432daca21db0095f4b16542782b7986f48a5 d0ae3c583d401')) signerPubKey = signature.recover_public_key_from_msg(msg) print('Signer public key (recovered):', signerPubKey) signerAddress = signerPubKey.to_checksum_address() print('Signer address:', signerAddress) print('Signature valid?:', signerAddress == msgSigner)
  • 20. Hashing and Hash Functions Cryptographic Hash Functions
  • 21. 21 What is Cryptographic Hash Function? Some text Some text Some text Some text Some text Some text Some text 20c9ad97c081d63397d 7b685a412227a40e23c 8bdc6688c6f37e97cfbc2 2d2b4d1db1510d8f61e 6a8866ad7f0e17c02b14 182d37ea7c3c8b9c2683 aeb6b733a1 Text Hashed text Cryptographic hash function (almost no collisions)
  • 22. 22 Cryptographic Hash Function  One-way hash function  Infeasible to invert  Extremely little chance to find a collision
  • 23. 23  Old hash algorithms: MD5, SHA-0, SHA-1  Withdrawn due to cryptographic weaknesses (collisions found)  SHA-2  Family of functions: SHA-256 (256 bits hash), SHA-512 (512 bits), …  SHA-3  More secure, same hash length (256 bits), known as "Keccak"  RIPEMD-160  Secure hash function, widely used in cryptography, e.g. PGP, Bitcoin  Less secure variations: RIPEMD-128, RIPEMD-256, RIPEMD-320 Secure Hash Functions
  • 24. 24  BLAKE / BLAKE2 / BLAKE2s / BLAKE2b  Fast, secure cryptographic hash function  256-bit (BLAKE-256, BLAKE2s) and 512-bit (BLAKE-512, BLAKE2b)  As of April 2018, no collisions are known for:  SHA256, SHA3-256, Keccak-256, BLAKE2s, RIPEMD160  Brute forcing to find a collision costs: 2128 for SHA256/SHA3-256 and 280 for RIPEMD160 (285 / 285 on quantum computer)  512-bit hashes (SHA-512 / SHA3-512) are Quantum-resistant Secure Hash Algorithms (2)
  • 25. 25 Calculating Hash Functions in Python import hashlib, binascii text = 'hello' data = text.encode("utf8") sha256hash = hashlib.sha256(data).digest() print("SHA256: ", binascii.hexlify(sha256hash)) sha3_256 = hashlib.sha3_256(data).digest() print("SHA3-256: ", binascii.hexlify(sha3_256)) ripemd160 = hashlib.new('ripemd160', data).digest() print("RIPEMD-160:", binascii.hexlify(ripemd160))
  • 26. HMAC and Key Derivation MAC, HMAC, PBKDF2 and SCrypt
  • 27. 27  HMAC = Hash-based Message Authentication Code  HMAC(key, msg, hash_func)  hash  Message hash mixed with a secret shared key  Used for message integrity / authenticity / key derivation  Key derivation function (KDF) == function(password)  key  Use HKDF (HMAC-based key derivation), PBKDF2 or SCrypt  PBKDF2, BCrypt and SCrypt are modern key-derivation functions  Use a lot of iterations + a lot of memory  to make it slow HMAC and Key Derivation
  • 28. 28 HMAC Calculation in Python – Example import hashlib, hmac, binascii def hmac_sha256(key, msg): return hmac.new(key, msg, hashlib.sha256).digest() key = binascii.unhexlify("fa63f2b4c85af6bed3") msg = "some message".encode("utf8") print(binascii.hexlify(hmac_sha256(key, msg)))
  • 29. 29  SCrypt (RFC 7914) is a strong cryptographic key-derivation function  Memory intensive, designed to prevent ASIC and FPGA attacks  key = Scrypt(password, salt, N, r, p, derived-key-len)  N – iterations count (affects memory and CPU usage), e.g. 16384  r – block size (affects memory and CPU usage), e.g. 8  p – parallelism factor (threads to run in parallel), usually 1  Memory used = 128 * N * r * p bytes, e.g. 128 * 16384 * 8 = 16 MB  Parameters for interactive login: N=16384, r=8, p=1 (RAM=16MB)  Parameters for file encryption: N=1048576, r=8, p=1 (RAM=1GB) Key Derivation Functions: Scrypt
  • 30. 30 SCrypt Key Derivation in Python – Example import scrypt, os, binascii passwd = "p@$$w0rD~3" salt = os.urandom(32) print("Salt: ", binascii.hexlify(salt)) key = scrypt.hash(passwd, salt, 16384, 8, 1, 32) print("Derived key:", binascii.hexlify(key)) pip install scrypt
  • 31. Blockchain Cryptography and Wallets Keys, Addresses, Signatures, Wallets
  • 32. 32 Public / Private Keys, Wallets & Blockchain private key public key address transaction sign by private key signed transaction valid / invalid verify by address wallet master key (seed) signed transaction transaction data public key: (x, y) signature: (v, r, s)
  • 33. 33  In blockchain wallets keep private keys, highly encrypted  Simple wallet (keystore) keeps a single private key  Example: https://gist.github.com/nakov/53f869e01c9b573844c48e5966e33a3f  HD wallet (hierarchical wallet) keeps multiple private keys  Hierarchically derived by a master key (seed) by derivation path  The seed is encoded as mnemonic phrase (12 / 24 words)  Example: https://iancoleman.io/bip39/ HD Wallets, BIP39, BIP32 / BIP44 hill brave science fox crime quit owner chapter myth vocal chat custom
  • 34. 34  The BIP-32 standard defines how a crypto-wallet can generate multiple keys + addresses  The wallet is initialized by a 512-bit master key (seed)  HMAC + ECC math used to generate multiple accounts  Through a derivation path  E.g. m/44'/60'/1'/12  Each account holds private key  public key  address ECC and Wallets: BIP32
  • 35. 35  Most modern crypto wallets start from a 512-bit securely generated random seed (see the BIP-39 standard)  The seed (root key) can be represented by 12 or 24 words, e.g.  Each word comes from a wordlist of 2048 words  See https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt  1 word == 11 bits of entropy  12 words == 132 bits == 128-bit entropy + checksum (in the last word)  24 words == 264 bits == 256-bit entropy + checksum (in the last word) Internal Seed in Crypto Wallets hill brave science fox crime quit owner chapter myth vocal chat custom
  • 36. BIP-39 Mnemonic Seed Generator Live Demo https://iancoleman.io/bip39
  • 37. Wallet Encryption and AES AES, CBC/CTR, Padding, SCrypt, HMAC
  • 38. 38  A single secret key to encrypt / decrypt  The secret key is usually derived by a password  Both the sender and the recipient should know the secret key  Widely used symmetric algorithms: AES-128, AES-256, Twofish, IDEA Symmetric Encryption  Wallets are typically encrypted using symmetric ciphers like AES
  • 39. 39  AES is a "block cipher" – encrypts block by block (e.g. 128 bits)  It has several modes of operation (CBC, ECB, CTR, …)  Some modes of operation require initial vector (IV)  Non-secret random salt  used to get different result each time  Recommended modes: CBC (Cipher Block Chaining) or CTR (Counter)  It may use a padding algorithm (typically PKCS7) to split the input data into blocks of fixed block-size (e.g. 128 bits)  It may use password to key derivation: key = SCrypt(pass, salt, …)  It may use MAC to check the password validity: HMAC(text, key) AES Cipher Settings
  • 40. 40 Example: AES Encrypt / Decrypt in Python import pyaes, pbkdf2, binascii, os, secrets plaintext = "Sample text for encryption" password = "s0m3p@$$w0rd" key = pbkdf2.PBKDF2(password, 'some salt').read(16) print('AES encryption key:', binascii.hexlify(key)) iv = secrets.randbelow(2 << 128) aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv)) ciphertext = aes.encrypt(plaintext) print('encrypted:', binascii.hexlify(ciphertext)) aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv)) decrypted = aes.decrypt(ciphertext) print('decrypted:', decrypted) pip install pyaes pip install pbkdf2
  • 41. 41 Ethereum UTC / JSON Wallet Encryption { "version": 3, "id": "…", "address": "b97e993872a9050c07f…ef195", "Crypto": { "ciphertext": "bc9215b2cd1571df…e3a1", // the encrypted private key "cipher": "aes-128-ctr", // AES, 128-bit encryption, CTR mode "cipherparams": { "iv": "2bac08cafc…8e" }, // random initial vector "kdf": "scrypt", "kdfparams": { "dklen": 32, // key length (256-bit key for AES encryption) "salt": "7d48230c94b90c0301bf9f4…eba1", // random-generated salt "n": 1024, // iterations count (CPU + memory cost factor) "r": 8, // block size (affects CPU + memory) "p": 1 // parallelization factor (threads count) }, "mac": "e3cd7ea4e3ceb0e9a…0564" // msg integrity key (password check) } } Learn more at: https://github.com/ethers-io/ethers.js/blob/master/wallet/secret-storage.js#L288
  • 43. License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license 43
  • 44. Trainings @ Software University (SoftUni)  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg  Software University Foundation  http://softuni.foundation/  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg