SlideShare a Scribd company logo
How does cryptography work?
2015-10-18
This page attempts to give a very basic conceptual introduction to cryptographic methods. Before we start the usual disclaimer:
I am not a cryptographer. This document is only for educational purposes. Crypto is hard, you should never trust your home-grown
implementation. Unless you’re a cryptographer you will probably overlook some crucial details. Developers should only use the high-
level functions that have been implemented by an actual cryptographer.
Now that we got this is out of the way, let’s start hacking :)
The XOR operator
The logical XOR operator outputs true only when both inputs differ (one is true , the other is false ). It is sometimes called an invertor
because the output of x gets inverted if and only if y is true:
# XOR two (8bit) bytes 'x' and 'y'
x <- as.raw(0x7a)
y <- as.raw(0xe4)
z <- base::xor(x, y)
dput(z)
as.raw(0x9e)
# Show the bits in each byte
cbind(x = rawToBits(x), y = rawToBits(y), z = rawToBits(z))
x y z
[1,] 00 00 00
[2,] 01 00 01
[3,] 00 01 01
[4,] 01 00 01
[5,] 01 00 01
[6,] 01 01 00
[7,] 01 01 00
[8,] 00 01 01
In cryptography we xor a message x with secret random data y . Because each bit in y is randomly true with probability 0.5, the xor
output is completely random and uncorrelated to x . This is called perfect secrecy. Only if we know y we can decipher the message x .
# Encrypt message using random one-time-pad
msg <- charToRaw("TTIP is evil")
one_time_pad <- random(length(msg))
ciphertext <- base::xor(msg, one_time_pad)
# It's really encrypted
rawToChar(ciphertext)
[1] "(8xd7ȉ%u035fx81xbb023xa2"
# Decrypt with same pad
rawToChar(base::xor(ciphertext, one_time_pad))
[1] "TTIP is evil"
This method is perfectly secure and forms the basis for most cryptograhpic methods. However the challenge is generating and communicating
unique pseudo-random y data every time we want to encrypt something. One-time-pads as in the example are not very practical for large
messages. Also we should never re-use a one-time-pad y for encrypting multiple messages, as this compromises the secrecy.
Stream ciphers
A stream cipher generates a unique stream of pseudo-random data based on a secret key and a unique nonce . For a given set of
parameters the stream cipher always generates the same stream of data. Sodium implements a few popular stream ciphers:
password <- "My secret passphrase"
key <- hash(charToRaw(password))
nonce <- random(8)
chacha20(size = 20, key, nonce)
converted by Web2PDFConvert.com
[1] 51 c6 c9 45 c6 13 6b 3d 6f 5c e3 ab 9f 16 f2 46 ce cb 19 f3
Each stream requires a key and a nonce . The key forms the shared secret and should only be known to trusted parties. The nonce is not
secret and is stored or sent along with the ciphertext. The purpose of the nonce is to make a random stream unique to protect gainst re-use
attacks. This way you can re-use a your key to encrypt multiple messages, as long as you never re-use the same nonce.
salsa20(size = 20, key, nonce)
[1] df 7d 13 ca ea 7c ff 93 e5 b6 fe b6 6b e2 91 14 ed ae 17 eb
Over the years cryptographers have come up with many more variants. Many stream ciphers are based on a block cipher such as AES: a keyed
permutation of fixed length amount of data. The block ciphers get chained in a particular mode of operation which repeatedly applies the cipher’s
single-block operation to securely transform amounts of data larger than a block.
We are not going to discuss implementation details, but you could probably come up with something yourself. For example you could use a hash
function such sha256 as the block cipher and append counter which is incremented for each block (this is called CTR mode).
# Illustrative example.
sha256_ctr <- function(size, key, nonce){
n <- ceiling(size/32)
output <- raw()
for(i in 1:n){
counter <- packBits(intToBits(i))
block <- sha256(c(key, nonce, counter))
output <- c(output, block)
}
return(output[1:size])
}
This allows us to generate an arbitrary length stream from a single secret key:
password <- "My secret passphrase"
key <- hash(charToRaw(password))
nonce <- random(8)
sha256_ctr(50, key, nonce)
[1] 07 01 96 02 7e c7 37 b4 8c b1 6a ec 4e 2d 56 34 7d 39 13 bc 72 e0 19
[24] ad b3 44 0e 9f 88 bb 3d 26 94 aa 66 01 2e bd 46 55 2c 04 99 1e af a9
[47] 91 cd 53 b4
In practice, you should never write your own ciphers. A lot of research goes into studying the properties of block ciphers under various modes of
operation. In the remainder we just use the standard Sodium ciphers: chacha20 , salsa20 , xsalsa20 or aes128 . See sodium
documentation for details.
Symmetric encryption
Symmetric encryption means that the same secret key is used for both encryption and decryption. All that is needed to implement symmetric
encryption is xor and a stream cipher. For example to encrypt an arbitrary length message using password :
# Encrypt 'message' using 'password'
myfile <- file.path(R.home(), "COPYING")
message <- readBin(myfile, raw(), file.info(myfile)$size)
passwd <- charToRaw("My secret passphrase")
A hash function converts the password to a key of suitable size for the stream cipher, which we use to generate a psuedo random stream of
equal length to the message:
# Basic secret key encryption
key <- hash(passwd)
nonce8 <- random(8)
stream <- chacha20(length(message), key, nonce8)
ciphertext <- base::xor(stream, message)
Now the ciphertext is an encrypted version of the message. Only those that know the key and the nonce can re-generate the same
keystream in order to xor the ciphertext back into the original message.
converted by Web2PDFConvert.com
# Decrypt with the same key
key <- hash(charToRaw("My secret passphrase"))
stream <- chacha20(length(ciphertext), key, nonce8)
out <- base::xor(ciphertext, stream)
# Print part of the message
cat(substring(rawToChar(out), 1, 120))
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
The Sodium functions data_encrypt and data_decrypt provide a more elaborate implementation of the above. This is what you should use
in practice for secret key encryption.
Symmetric encryption can be used for e.g. encrypting local data. However because the same secret is used for both encryption and decryption,
it is impractical for communication with other parties. For exchanging secure messages we need public key encryption.
Public-key encryption and Diffie-Hellman
Rather than using a single secret-key, assymetric (public key) encryption requires a keypair, consisting of a public key for encryption and a
private-key for decryption. Data that is encrypted using a given public key can only be decrypted using the corresponding private key.
The public key is not confidential and can be shared on e.g. a website or keyserver. This allows anyone to send somebody a secure message by
encrypting it with the receivers public key. The encrypted message will only be readable by the owner of the corresponding private key.
# Create keypair
key <- keygen()
pub <- pubkey(key)
# Encrypt message for receiver using his/her public key
msg <- serialize(iris, NULL)
ciphertext <- simple_encrypt(msg, pub)
# Receiver decrypts with his/her private key
out <- simple_decrypt(ciphertext, key)
identical(msg, out)
[1] TRUE
How does this work? Public key encryption makes use of Diffie-Hellman (D-H): a method which allows two parties that have no prior knowledge of
each other to jointly establish a shared secret key over an insecure channel. In the most simple case, both parties generate a temporary keypair
and exchange their public key over the insecure channel. Then both parties use the D-H function to calculcate the (same) shared secret key by
combining their own private key with the other person’s public key:
# Bob generates keypair
bob_key <- keygen()
bob_pubkey <- pubkey(bob_key)
# Alice generates keypair
alice_key <- keygen()
alice_pubkey <- pubkey(alice_key)
# After Bob and Alice exchange pubkey they can both derive the secret
alice_secret <- diffie_hellman(alice_key, bob_pubkey)
bob_secret <- diffie_hellman(bob_key, alice_pubkey)
identical(alice_secret, bob_secret)
[1] TRUE
Once the shared secret has been established, both parties can discard their temporary public/private key and use the shared secret to start
encrypting communications with symmetric encryption as discussed earlier. Because the shared secret cannot be calculated using only the
public keys, the process is safe from eavesdroppers.
The classical Diffie-Hellman method is based on the discrete logarithm problem with large prime numbers. Sodium uses curve25519, a state-of-
the-art D-H function by Daniel Bernsteinan designed for use with the elliptic curve Diffie–Hellman (ECDH) key agreement scheme.
converted by Web2PDFConvert.com

More Related Content

What's hot

Cryptography for Absolute Beginners (May 2019)
Cryptography for Absolute Beginners (May 2019)Cryptography for Absolute Beginners (May 2019)
Cryptography for Absolute Beginners (May 2019)
Svetlin Nakov
 
Clojure ♥ cassandra
Clojure ♥ cassandra Clojure ♥ cassandra
Clojure ♥ cassandra
Max Penet
 
Even the LastPass Will be Stolen Deal with It!
Even the LastPass Will be Stolen Deal with It!Even the LastPass Will be Stolen Deal with It!
Even the LastPass Will be Stolen Deal with It!
Martin Vigo
 
apidays LIVE New York - WT* is JWT? by Maciej Treder
apidays LIVE New York -  WT* is JWT? by Maciej Trederapidays LIVE New York -  WT* is JWT? by Maciej Treder
apidays LIVE New York - WT* is JWT? by Maciej Treder
apidays
 
Dodging WebCrypto API Landmines
Dodging WebCrypto API LandminesDodging WebCrypto API Landmines
Dodging WebCrypto API Landmines
Ernie Turner
 
MongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 Link
MongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 LinkMongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 Link
MongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 Link
MongoDB
 
Trust boundaries - Confidence 2015
Trust boundaries - Confidence 2015Trust boundaries - Confidence 2015
Trust boundaries - Confidence 2015
Logicaltrust pl
 
Reutov, yunusov, nagibin random numbers take ii
Reutov, yunusov, nagibin   random numbers take iiReutov, yunusov, nagibin   random numbers take ii
Reutov, yunusov, nagibin random numbers take iiDefconRussia
 
Cargo Cult Security at OpenWest
Cargo Cult Security at OpenWestCargo Cult Security at OpenWest
Cargo Cult Security at OpenWest
Derrick Isaacson
 
MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB
 
Cryptography for Smalltalkers 2 - ESUG 2006
Cryptography for Smalltalkers 2 - ESUG 2006Cryptography for Smalltalkers 2 - ESUG 2006
Cryptography for Smalltalkers 2 - ESUG 2006
Martin Kobetic
 
Cargo Cult Security UJUG Sep2015
Cargo Cult Security UJUG Sep2015Cargo Cult Security UJUG Sep2015
Cargo Cult Security UJUG Sep2015
Derrick Isaacson
 
Hacking (with) WebSockets
Hacking (with) WebSocketsHacking (with) WebSockets
Hacking (with) WebSockets
Sergey Shekyan
 
DASP Top10 for OWASP Thailand Chapter by s111s
DASP Top10 for OWASP Thailand Chapter by s111s DASP Top10 for OWASP Thailand Chapter by s111s
DASP Top10 for OWASP Thailand Chapter by s111s
s111s object
 
[Wroclaw #8] TLS all the things!
[Wroclaw #8] TLS all the things![Wroclaw #8] TLS all the things!
[Wroclaw #8] TLS all the things!
OWASP
 
MongoDB .local Munich 2019: New Encryption Capabilities in MongoDB 4.2: A Dee...
MongoDB .local Munich 2019: New Encryption Capabilities in MongoDB 4.2: A Dee...MongoDB .local Munich 2019: New Encryption Capabilities in MongoDB 4.2: A Dee...
MongoDB .local Munich 2019: New Encryption Capabilities in MongoDB 4.2: A Dee...
MongoDB
 
Collision vulnerability for hash data structures in web platforms
Collision vulnerability for hash data structures in web platformsCollision vulnerability for hash data structures in web platforms
Collision vulnerability for hash data structures in web platforms
Berescu Ionut
 

What's hot (17)

Cryptography for Absolute Beginners (May 2019)
Cryptography for Absolute Beginners (May 2019)Cryptography for Absolute Beginners (May 2019)
Cryptography for Absolute Beginners (May 2019)
 
Clojure ♥ cassandra
Clojure ♥ cassandra Clojure ♥ cassandra
Clojure ♥ cassandra
 
Even the LastPass Will be Stolen Deal with It!
Even the LastPass Will be Stolen Deal with It!Even the LastPass Will be Stolen Deal with It!
Even the LastPass Will be Stolen Deal with It!
 
apidays LIVE New York - WT* is JWT? by Maciej Treder
apidays LIVE New York -  WT* is JWT? by Maciej Trederapidays LIVE New York -  WT* is JWT? by Maciej Treder
apidays LIVE New York - WT* is JWT? by Maciej Treder
 
Dodging WebCrypto API Landmines
Dodging WebCrypto API LandminesDodging WebCrypto API Landmines
Dodging WebCrypto API Landmines
 
MongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 Link
MongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 LinkMongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 Link
MongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 Link
 
Trust boundaries - Confidence 2015
Trust boundaries - Confidence 2015Trust boundaries - Confidence 2015
Trust boundaries - Confidence 2015
 
Reutov, yunusov, nagibin random numbers take ii
Reutov, yunusov, nagibin   random numbers take iiReutov, yunusov, nagibin   random numbers take ii
Reutov, yunusov, nagibin random numbers take ii
 
Cargo Cult Security at OpenWest
Cargo Cult Security at OpenWestCargo Cult Security at OpenWest
Cargo Cult Security at OpenWest
 
MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Chicago 2019: Using Client Side Encryption in MongoDB 4.2
 
Cryptography for Smalltalkers 2 - ESUG 2006
Cryptography for Smalltalkers 2 - ESUG 2006Cryptography for Smalltalkers 2 - ESUG 2006
Cryptography for Smalltalkers 2 - ESUG 2006
 
Cargo Cult Security UJUG Sep2015
Cargo Cult Security UJUG Sep2015Cargo Cult Security UJUG Sep2015
Cargo Cult Security UJUG Sep2015
 
Hacking (with) WebSockets
Hacking (with) WebSocketsHacking (with) WebSockets
Hacking (with) WebSockets
 
DASP Top10 for OWASP Thailand Chapter by s111s
DASP Top10 for OWASP Thailand Chapter by s111s DASP Top10 for OWASP Thailand Chapter by s111s
DASP Top10 for OWASP Thailand Chapter by s111s
 
[Wroclaw #8] TLS all the things!
[Wroclaw #8] TLS all the things![Wroclaw #8] TLS all the things!
[Wroclaw #8] TLS all the things!
 
MongoDB .local Munich 2019: New Encryption Capabilities in MongoDB 4.2: A Dee...
MongoDB .local Munich 2019: New Encryption Capabilities in MongoDB 4.2: A Dee...MongoDB .local Munich 2019: New Encryption Capabilities in MongoDB 4.2: A Dee...
MongoDB .local Munich 2019: New Encryption Capabilities in MongoDB 4.2: A Dee...
 
Collision vulnerability for hash data structures in web platforms
Collision vulnerability for hash data structures in web platformsCollision vulnerability for hash data structures in web platforms
Collision vulnerability for hash data structures in web platforms
 

Similar to How does cryptography work? by Jeroen Ooms

Dnssec tutorial-crypto-defs
Dnssec tutorial-crypto-defsDnssec tutorial-crypto-defs
Dnssec tutorial-crypto-defs
AFRINIC
 
Crypto failures every developer should avoid
Crypto failures every developer should avoidCrypto failures every developer should avoid
Crypto failures every developer should avoid
OwaspCzech
 
Crypto failures every developer should avoid
Crypto failures every developer should avoidCrypto failures every developer should avoid
Crypto failures every developer should avoidFilip Šebesta
 
Cryptography
CryptographyCryptography
CryptographyRohan04
 
Cryptography Key Management.pptx
Cryptography Key Management.pptxCryptography Key Management.pptx
Cryptography Key Management.pptx
SurendraBasnet6
 
SSL/TLS Handshake
SSL/TLS HandshakeSSL/TLS Handshake
SSL/TLS Handshake
Arpit Agarwal
 
Encryption in php
Encryption in phpEncryption in php
Encryption in php
sana mateen
 
Digital signatures
Digital signaturesDigital signatures
Digital signatures
Kannan Ravindran
 
Digital signatures
Digital signaturesDigital signatures
Cryptography
CryptographyCryptography
Cryptography
Vishalya Dulam
 
Using Cryptography Properly in Applications
Using Cryptography Properly in ApplicationsUsing Cryptography Properly in Applications
Using Cryptography Properly in Applications
Great Wide Open
 
Web cryptography javascript
Web cryptography javascriptWeb cryptography javascript
Web cryptography javascript
Jose Manuel Ortega Candel
 
Survey of Hybrid Encryption Algorithm for Mobile Communication
Survey of Hybrid Encryption Algorithm for Mobile CommunicationSurvey of Hybrid Encryption Algorithm for Mobile Communication
Survey of Hybrid Encryption Algorithm for Mobile Communication
ijsrd.com
 
Password (in)security
Password (in)securityPassword (in)security
Password (in)security
Enrico Zimuel
 
Cryptography-Hash-Functions.pptx
Cryptography-Hash-Functions.pptxCryptography-Hash-Functions.pptx
Cryptography-Hash-Functions.pptx
AngeloChangcoco
 
Nachos3 - Theoretical Part
Nachos3 - Theoretical PartNachos3 - Theoretical Part
Nachos3 - Theoretical PartEduardo Triana
 
Secured algorithm for gsm encryption & decryption
Secured algorithm for gsm encryption & decryptionSecured algorithm for gsm encryption & decryption
Secured algorithm for gsm encryption & decryption
Tharindu Weerasinghe
 
(Crypto) DES And RSA Algorithms Overview
(Crypto) DES And RSA Algorithms Overview(Crypto) DES And RSA Algorithms Overview
(Crypto) DES And RSA Algorithms Overview
EL Bachir Nouni
 

Similar to How does cryptography work? by Jeroen Ooms (20)

Dnssec tutorial-crypto-defs
Dnssec tutorial-crypto-defsDnssec tutorial-crypto-defs
Dnssec tutorial-crypto-defs
 
Crypto failures every developer should avoid
Crypto failures every developer should avoidCrypto failures every developer should avoid
Crypto failures every developer should avoid
 
Crypto failures every developer should avoid
Crypto failures every developer should avoidCrypto failures every developer should avoid
Crypto failures every developer should avoid
 
Cryptography
CryptographyCryptography
Cryptography
 
Cryptography Key Management.pptx
Cryptography Key Management.pptxCryptography Key Management.pptx
Cryptography Key Management.pptx
 
Encryption
EncryptionEncryption
Encryption
 
SSL/TLS Handshake
SSL/TLS HandshakeSSL/TLS Handshake
SSL/TLS Handshake
 
Encryption in php
Encryption in phpEncryption in php
Encryption in php
 
Digital signatures
Digital signaturesDigital signatures
Digital signatures
 
Digital signatures
Digital signaturesDigital signatures
Digital signatures
 
Cryptography
CryptographyCryptography
Cryptography
 
Django cryptography
Django cryptographyDjango cryptography
Django cryptography
 
Using Cryptography Properly in Applications
Using Cryptography Properly in ApplicationsUsing Cryptography Properly in Applications
Using Cryptography Properly in Applications
 
Web cryptography javascript
Web cryptography javascriptWeb cryptography javascript
Web cryptography javascript
 
Survey of Hybrid Encryption Algorithm for Mobile Communication
Survey of Hybrid Encryption Algorithm for Mobile CommunicationSurvey of Hybrid Encryption Algorithm for Mobile Communication
Survey of Hybrid Encryption Algorithm for Mobile Communication
 
Password (in)security
Password (in)securityPassword (in)security
Password (in)security
 
Cryptography-Hash-Functions.pptx
Cryptography-Hash-Functions.pptxCryptography-Hash-Functions.pptx
Cryptography-Hash-Functions.pptx
 
Nachos3 - Theoretical Part
Nachos3 - Theoretical PartNachos3 - Theoretical Part
Nachos3 - Theoretical Part
 
Secured algorithm for gsm encryption & decryption
Secured algorithm for gsm encryption & decryptionSecured algorithm for gsm encryption & decryption
Secured algorithm for gsm encryption & decryption
 
(Crypto) DES And RSA Algorithms Overview
(Crypto) DES And RSA Algorithms Overview(Crypto) DES And RSA Algorithms Overview
(Crypto) DES And RSA Algorithms Overview
 

More from Ajay Ohri

Introduction to R ajay Ohri
Introduction to R ajay OhriIntroduction to R ajay Ohri
Introduction to R ajay Ohri
Ajay Ohri
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
Ajay Ohri
 
Social Media and Fake News in the 2016 Election
Social Media and Fake News in the 2016 ElectionSocial Media and Fake News in the 2016 Election
Social Media and Fake News in the 2016 Election
Ajay Ohri
 
Pyspark
PysparkPyspark
Pyspark
Ajay Ohri
 
Download Python for R Users pdf for free
Download Python for R Users pdf for freeDownload Python for R Users pdf for free
Download Python for R Users pdf for free
Ajay Ohri
 
Install spark on_windows10
Install spark on_windows10Install spark on_windows10
Install spark on_windows10
Ajay Ohri
 
Ajay ohri Resume
Ajay ohri ResumeAjay ohri Resume
Ajay ohri Resume
Ajay Ohri
 
Statistics for data scientists
Statistics for  data scientistsStatistics for  data scientists
Statistics for data scientists
Ajay Ohri
 
National seminar on emergence of internet of things (io t) trends and challe...
National seminar on emergence of internet of things (io t)  trends and challe...National seminar on emergence of internet of things (io t)  trends and challe...
National seminar on emergence of internet of things (io t) trends and challe...
Ajay Ohri
 
Tools and techniques for data science
Tools and techniques for data scienceTools and techniques for data science
Tools and techniques for data science
Ajay Ohri
 
How Big Data ,Cloud Computing ,Data Science can help business
How Big Data ,Cloud Computing ,Data Science can help businessHow Big Data ,Cloud Computing ,Data Science can help business
How Big Data ,Cloud Computing ,Data Science can help business
Ajay Ohri
 
Training in Analytics and Data Science
Training in Analytics and Data ScienceTraining in Analytics and Data Science
Training in Analytics and Data Science
Ajay Ohri
 
Tradecraft
Tradecraft   Tradecraft
Tradecraft
Ajay Ohri
 
Software Testing for Data Scientists
Software Testing for Data ScientistsSoftware Testing for Data Scientists
Software Testing for Data Scientists
Ajay Ohri
 
Craps
CrapsCraps
Craps
Ajay Ohri
 
A Data Science Tutorial in Python
A Data Science Tutorial in PythonA Data Science Tutorial in Python
A Data Science Tutorial in Python
Ajay Ohri
 
Using R for Social Media and Sports Analytics
Using R for Social Media and Sports AnalyticsUsing R for Social Media and Sports Analytics
Using R for Social Media and Sports Analytics
Ajay Ohri
 
Kush stats alpha
Kush stats alpha Kush stats alpha
Kush stats alpha
Ajay Ohri
 
Analyze this
Analyze thisAnalyze this
Analyze this
Ajay Ohri
 
Summer school python in spanish
Summer school python in spanishSummer school python in spanish
Summer school python in spanish
Ajay Ohri
 

More from Ajay Ohri (20)

Introduction to R ajay Ohri
Introduction to R ajay OhriIntroduction to R ajay Ohri
Introduction to R ajay Ohri
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
Social Media and Fake News in the 2016 Election
Social Media and Fake News in the 2016 ElectionSocial Media and Fake News in the 2016 Election
Social Media and Fake News in the 2016 Election
 
Pyspark
PysparkPyspark
Pyspark
 
Download Python for R Users pdf for free
Download Python for R Users pdf for freeDownload Python for R Users pdf for free
Download Python for R Users pdf for free
 
Install spark on_windows10
Install spark on_windows10Install spark on_windows10
Install spark on_windows10
 
Ajay ohri Resume
Ajay ohri ResumeAjay ohri Resume
Ajay ohri Resume
 
Statistics for data scientists
Statistics for  data scientistsStatistics for  data scientists
Statistics for data scientists
 
National seminar on emergence of internet of things (io t) trends and challe...
National seminar on emergence of internet of things (io t)  trends and challe...National seminar on emergence of internet of things (io t)  trends and challe...
National seminar on emergence of internet of things (io t) trends and challe...
 
Tools and techniques for data science
Tools and techniques for data scienceTools and techniques for data science
Tools and techniques for data science
 
How Big Data ,Cloud Computing ,Data Science can help business
How Big Data ,Cloud Computing ,Data Science can help businessHow Big Data ,Cloud Computing ,Data Science can help business
How Big Data ,Cloud Computing ,Data Science can help business
 
Training in Analytics and Data Science
Training in Analytics and Data ScienceTraining in Analytics and Data Science
Training in Analytics and Data Science
 
Tradecraft
Tradecraft   Tradecraft
Tradecraft
 
Software Testing for Data Scientists
Software Testing for Data ScientistsSoftware Testing for Data Scientists
Software Testing for Data Scientists
 
Craps
CrapsCraps
Craps
 
A Data Science Tutorial in Python
A Data Science Tutorial in PythonA Data Science Tutorial in Python
A Data Science Tutorial in Python
 
Using R for Social Media and Sports Analytics
Using R for Social Media and Sports AnalyticsUsing R for Social Media and Sports Analytics
Using R for Social Media and Sports Analytics
 
Kush stats alpha
Kush stats alpha Kush stats alpha
Kush stats alpha
 
Analyze this
Analyze thisAnalyze this
Analyze this
 
Summer school python in spanish
Summer school python in spanishSummer school python in spanish
Summer school python in spanish
 

Recently uploaded

1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
Tiktokethiodaily
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
yhkoc
 
Empowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptxEmpowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptx
benishzehra469
 
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
axoqas
 
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Subhajit Sahu
 
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
slg6lamcq
 
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Subhajit Sahu
 
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
ukgaet
 
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
ewymefz
 
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdfCh03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
haila53
 
一比一原版(UofS毕业证书)萨省大学毕业证如何办理
一比一原版(UofS毕业证书)萨省大学毕业证如何办理一比一原版(UofS毕业证书)萨省大学毕业证如何办理
一比一原版(UofS毕业证书)萨省大学毕业证如何办理
v3tuleee
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
nscud
 
社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .
NABLAS株式会社
 
SOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape ReportSOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape Report
SOCRadar
 
standardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghhstandardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghh
ArpitMalhotra16
 
Malana- Gimlet Market Analysis (Portfolio 2)
Malana- Gimlet Market Analysis (Portfolio 2)Malana- Gimlet Market Analysis (Portfolio 2)
Malana- Gimlet Market Analysis (Portfolio 2)
TravisMalana
 
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
ewymefz
 
Predicting Product Ad Campaign Performance: A Data Analysis Project Presentation
Predicting Product Ad Campaign Performance: A Data Analysis Project PresentationPredicting Product Ad Campaign Performance: A Data Analysis Project Presentation
Predicting Product Ad Campaign Performance: A Data Analysis Project Presentation
Boston Institute of Analytics
 
Adjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTESAdjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTES
Subhajit Sahu
 
一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单
enxupq
 

Recently uploaded (20)

1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
 
Empowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptxEmpowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptx
 
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
 
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
 
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
一比一原版(Adelaide毕业证书)阿德莱德大学毕业证如何办理
 
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
 
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
 
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
 
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdfCh03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
 
一比一原版(UofS毕业证书)萨省大学毕业证如何办理
一比一原版(UofS毕业证书)萨省大学毕业证如何办理一比一原版(UofS毕业证书)萨省大学毕业证如何办理
一比一原版(UofS毕业证书)萨省大学毕业证如何办理
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
 
社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .
 
SOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape ReportSOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape Report
 
standardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghhstandardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghh
 
Malana- Gimlet Market Analysis (Portfolio 2)
Malana- Gimlet Market Analysis (Portfolio 2)Malana- Gimlet Market Analysis (Portfolio 2)
Malana- Gimlet Market Analysis (Portfolio 2)
 
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
 
Predicting Product Ad Campaign Performance: A Data Analysis Project Presentation
Predicting Product Ad Campaign Performance: A Data Analysis Project PresentationPredicting Product Ad Campaign Performance: A Data Analysis Project Presentation
Predicting Product Ad Campaign Performance: A Data Analysis Project Presentation
 
Adjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTESAdjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTES
 
一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单
 

How does cryptography work? by Jeroen Ooms

  • 1. How does cryptography work? 2015-10-18 This page attempts to give a very basic conceptual introduction to cryptographic methods. Before we start the usual disclaimer: I am not a cryptographer. This document is only for educational purposes. Crypto is hard, you should never trust your home-grown implementation. Unless you’re a cryptographer you will probably overlook some crucial details. Developers should only use the high- level functions that have been implemented by an actual cryptographer. Now that we got this is out of the way, let’s start hacking :) The XOR operator The logical XOR operator outputs true only when both inputs differ (one is true , the other is false ). It is sometimes called an invertor because the output of x gets inverted if and only if y is true: # XOR two (8bit) bytes 'x' and 'y' x <- as.raw(0x7a) y <- as.raw(0xe4) z <- base::xor(x, y) dput(z) as.raw(0x9e) # Show the bits in each byte cbind(x = rawToBits(x), y = rawToBits(y), z = rawToBits(z)) x y z [1,] 00 00 00 [2,] 01 00 01 [3,] 00 01 01 [4,] 01 00 01 [5,] 01 00 01 [6,] 01 01 00 [7,] 01 01 00 [8,] 00 01 01 In cryptography we xor a message x with secret random data y . Because each bit in y is randomly true with probability 0.5, the xor output is completely random and uncorrelated to x . This is called perfect secrecy. Only if we know y we can decipher the message x . # Encrypt message using random one-time-pad msg <- charToRaw("TTIP is evil") one_time_pad <- random(length(msg)) ciphertext <- base::xor(msg, one_time_pad) # It's really encrypted rawToChar(ciphertext) [1] "(8xd7ȉ%u035fx81xbb023xa2" # Decrypt with same pad rawToChar(base::xor(ciphertext, one_time_pad)) [1] "TTIP is evil" This method is perfectly secure and forms the basis for most cryptograhpic methods. However the challenge is generating and communicating unique pseudo-random y data every time we want to encrypt something. One-time-pads as in the example are not very practical for large messages. Also we should never re-use a one-time-pad y for encrypting multiple messages, as this compromises the secrecy. Stream ciphers A stream cipher generates a unique stream of pseudo-random data based on a secret key and a unique nonce . For a given set of parameters the stream cipher always generates the same stream of data. Sodium implements a few popular stream ciphers: password <- "My secret passphrase" key <- hash(charToRaw(password)) nonce <- random(8) chacha20(size = 20, key, nonce) converted by Web2PDFConvert.com
  • 2. [1] 51 c6 c9 45 c6 13 6b 3d 6f 5c e3 ab 9f 16 f2 46 ce cb 19 f3 Each stream requires a key and a nonce . The key forms the shared secret and should only be known to trusted parties. The nonce is not secret and is stored or sent along with the ciphertext. The purpose of the nonce is to make a random stream unique to protect gainst re-use attacks. This way you can re-use a your key to encrypt multiple messages, as long as you never re-use the same nonce. salsa20(size = 20, key, nonce) [1] df 7d 13 ca ea 7c ff 93 e5 b6 fe b6 6b e2 91 14 ed ae 17 eb Over the years cryptographers have come up with many more variants. Many stream ciphers are based on a block cipher such as AES: a keyed permutation of fixed length amount of data. The block ciphers get chained in a particular mode of operation which repeatedly applies the cipher’s single-block operation to securely transform amounts of data larger than a block. We are not going to discuss implementation details, but you could probably come up with something yourself. For example you could use a hash function such sha256 as the block cipher and append counter which is incremented for each block (this is called CTR mode). # Illustrative example. sha256_ctr <- function(size, key, nonce){ n <- ceiling(size/32) output <- raw() for(i in 1:n){ counter <- packBits(intToBits(i)) block <- sha256(c(key, nonce, counter)) output <- c(output, block) } return(output[1:size]) } This allows us to generate an arbitrary length stream from a single secret key: password <- "My secret passphrase" key <- hash(charToRaw(password)) nonce <- random(8) sha256_ctr(50, key, nonce) [1] 07 01 96 02 7e c7 37 b4 8c b1 6a ec 4e 2d 56 34 7d 39 13 bc 72 e0 19 [24] ad b3 44 0e 9f 88 bb 3d 26 94 aa 66 01 2e bd 46 55 2c 04 99 1e af a9 [47] 91 cd 53 b4 In practice, you should never write your own ciphers. A lot of research goes into studying the properties of block ciphers under various modes of operation. In the remainder we just use the standard Sodium ciphers: chacha20 , salsa20 , xsalsa20 or aes128 . See sodium documentation for details. Symmetric encryption Symmetric encryption means that the same secret key is used for both encryption and decryption. All that is needed to implement symmetric encryption is xor and a stream cipher. For example to encrypt an arbitrary length message using password : # Encrypt 'message' using 'password' myfile <- file.path(R.home(), "COPYING") message <- readBin(myfile, raw(), file.info(myfile)$size) passwd <- charToRaw("My secret passphrase") A hash function converts the password to a key of suitable size for the stream cipher, which we use to generate a psuedo random stream of equal length to the message: # Basic secret key encryption key <- hash(passwd) nonce8 <- random(8) stream <- chacha20(length(message), key, nonce8) ciphertext <- base::xor(stream, message) Now the ciphertext is an encrypted version of the message. Only those that know the key and the nonce can re-generate the same keystream in order to xor the ciphertext back into the original message. converted by Web2PDFConvert.com
  • 3. # Decrypt with the same key key <- hash(charToRaw("My secret passphrase")) stream <- chacha20(length(ciphertext), key, nonce8) out <- base::xor(ciphertext, stream) # Print part of the message cat(substring(rawToChar(out), 1, 120)) GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. The Sodium functions data_encrypt and data_decrypt provide a more elaborate implementation of the above. This is what you should use in practice for secret key encryption. Symmetric encryption can be used for e.g. encrypting local data. However because the same secret is used for both encryption and decryption, it is impractical for communication with other parties. For exchanging secure messages we need public key encryption. Public-key encryption and Diffie-Hellman Rather than using a single secret-key, assymetric (public key) encryption requires a keypair, consisting of a public key for encryption and a private-key for decryption. Data that is encrypted using a given public key can only be decrypted using the corresponding private key. The public key is not confidential and can be shared on e.g. a website or keyserver. This allows anyone to send somebody a secure message by encrypting it with the receivers public key. The encrypted message will only be readable by the owner of the corresponding private key. # Create keypair key <- keygen() pub <- pubkey(key) # Encrypt message for receiver using his/her public key msg <- serialize(iris, NULL) ciphertext <- simple_encrypt(msg, pub) # Receiver decrypts with his/her private key out <- simple_decrypt(ciphertext, key) identical(msg, out) [1] TRUE How does this work? Public key encryption makes use of Diffie-Hellman (D-H): a method which allows two parties that have no prior knowledge of each other to jointly establish a shared secret key over an insecure channel. In the most simple case, both parties generate a temporary keypair and exchange their public key over the insecure channel. Then both parties use the D-H function to calculcate the (same) shared secret key by combining their own private key with the other person’s public key: # Bob generates keypair bob_key <- keygen() bob_pubkey <- pubkey(bob_key) # Alice generates keypair alice_key <- keygen() alice_pubkey <- pubkey(alice_key) # After Bob and Alice exchange pubkey they can both derive the secret alice_secret <- diffie_hellman(alice_key, bob_pubkey) bob_secret <- diffie_hellman(bob_key, alice_pubkey) identical(alice_secret, bob_secret) [1] TRUE Once the shared secret has been established, both parties can discard their temporary public/private key and use the shared secret to start encrypting communications with symmetric encryption as discussed earlier. Because the shared secret cannot be calculated using only the public keys, the process is safe from eavesdroppers. The classical Diffie-Hellman method is based on the discrete logarithm problem with large prime numbers. Sodium uses curve25519, a state-of- the-art D-H function by Daniel Bernsteinan designed for use with the elliptic curve Diffie–Hellman (ECDH) key agreement scheme. converted by Web2PDFConvert.com