SlideShare a Scribd company logo
1 of 19
Aleksandar Radulovic
Introduction to
Cryptography in Java
Spiced up with Design Patterns and
some examples
What you shouldn’t expect?
❖ Why privacy does not exist on the Internet?
❖ How to prevent your girlfriend/boyfriend/spouse to read
your messages?
❖ Stories about Caesars cipher, Enigma, historical stuff
❖ Details about algorithms
What to expect?
❖ Get acquainted with cryptographic glossary
❖ What kinds of cryptographic algorithm exist and what is their purpose
❖ How to differentiate between secret (symmetric) and public (asymmetric) key cryptography?
❖ How to use them
❖ Why Base64 encoding/decoding has nothing to do with encryption
❖ Goals:
❖ How easy it is to use cryptography in Java, having algorithms encapsulated into high-level interfaces
❖ Improve awareness of presence of cryptography in our everyday life and work
❖ Sparkle curiosity
Language of patterns
❖ Strategy design pattern: Every class of algorithm is encapsulated into a dedicated interface: MessageDigest,
Cipher, Signature, Mac, …
❖ Factory design pattern: Every cryptographic object is created by using static method: getInstance(algorithm:
string)
❖ Slide patterns: for each class of cryptographic algorithms we will have:
❖ Purpose
❖ Features
❖ Best known algorithms
❖ Examination of the API interface (Strategy ^)
❖ Example/Usage
The Purpose of Cryptography
❖ Integrity: Message Digest
❖ Confidentiality/Secrecy: Cipher
❖ Authentication: Signatures and Message Authentication Codes
❖ Non-repudiation: Signatures (+ additional legislation)
❖ Bonus points:
❖ Word Cryptography comes from Greek kryptos, meaning “hidden” or “secret” and graphein,
meaning “to write”
❖ Word Code denotes a system of words, letters, figures, or other symbols substituted for
other words, letters, etc., especially for the purposes of secrecy.
Message Digest
❖ Synonyms: Cryptographic Hash Function,
Cryptographic Checksum, one-way function
❖ Purpose: Data Integrity / Has this data been
changed?
❖ Features:
❖ For arbitrary input data length, cryptographic
checksum length remains constant
❖ Small change in input data results in huge
change in the checksum
❖ Well-known algorithms: MD5, SHA1, SHA-2
(SHA224, 256, 364, 512), SHA-3
❖ Real life usage: software downloads, credit card
numbers, account numbers, …
Digest Engine
SHA-256
Byte Stream
Fixed Length
Cryptographic Checksum
java.security.MessageDigest
MessageDigest md = MessageDigest.getInstance(“SHA-256”);
md.reset();
md.update(byteArray);
var checksum = md.digest();
Resets digest object to the initial state.
Can be called multiple times.
Does the final computation and resets digest object.
Static factory method.
Strategy
Confidentiality: High-Level Overview
Algoritm = Transformation
Key = Parameter
Kerckhoff’s principle: Algorithms are public, keys are secret
* Algorithms are safe - it is not computationally feasible to transform cipher text into plain text
without knowing key
* Keys have sufficient lengths
* Key generation algorithm is not predictable
Algorithm
Plain text Cipher text
Secret vs Public Key Cryptography
❖ Secret (symmetric) key cryptography: encryption key =
decryption key
❖ Public (asymmetric) key cryptography
❖ Both Jovana and Matija have their own key pair: public key,
private key
❖ It is easy to calculate public key from private one, not vice
versa
❖ What is encrypted with public key, can be decrypted with
private key =>
❖ Everyone can encrypt content for Jovana using her public
key, but only she can decrypt cipher text using her private
key
❖ If Jovana encrypts something using her private key, anybody
can decrypt cipher text using her public key => digital
signature
Plain text Cipher text
Matija Jovana
Plain text
Cipher text
Jovana
Encryption
Decryption
Symmetric vs Asymmetric Ciphers
❖ Symmetric encryption algorithms:
❖ Faster than asymmetric
❖ Confidentiality
❖ Examples: AES (Advanced Encryption Standard), DES (Data Encryption Standard), Triple DES
(DESEDE), IDEA, Blowfish, RC2, RC4
❖ Asymmetric encryption algorithms:
❖ Confidentiality ~ key exchange (RSA)
❖ Digital Signatures (RSA, ECDSA)
❖ Authentication (RSA, ECDSA)
Block Ciphers
❖ Block vs Stream Ciphers
❖ Block cipher operating modes: Electronic
Code Book (ECB), Cipher Block Chaining
(CBC), Cipher Feedback, …
❖ Initialisation Vector (IV)
❖ Block ciphers in a streaming mode
❖ Padding (to the full block length) is applied
when needed: NoPadding, PKCS5Padding,
OAEPWithSHA-1AndMGF1Padding
Chaining of cipher blocks
javax.crypto.Cipher
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(192);
SecretKey secretKey = keyGenerator.generateKey();
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = cipher.doFinal(plainText);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedPlainText = cipher.doFinal(cipherText);
Auxiliary stuff to get a random/session key.
Algorithm / Mode / Padding
Initialisation of the Cipher object.
update() , doFinal(): do the work
Initialisation of the Cipher object: decrypt mode
Decrypt.
Signature
❖ Purpose: Message Authentication
❖ Integrity (Has this data been changed?)
❖ Origin (Is it really coming from the trusted
source?)
❖ Features: inherits message digest &
asymmetric cipher features
❖ Algorithms: SHA256withRSA, SHA1withRSA,
SHA256withDSA, SHA256withECDSA, etc.
❖ Note: DSA & ECDSA are used only for
signature, they don’t have Cipher capability of
RSA
❖ Example
Digest
(e.g.SHA-
256)
Input message
Signature
Cipher.encrypt
(e.g. RSA)
Private key
Signature
Cipher.decrypt
(e.g. RSA)
Public key
Message Digest
Digest
(e.g.SHA-
256)
Input message
Message Authentication Code
❖ Very similar to signatures: features, API, usage
❖ Different implementations:
❖ Message Digest + secret value (e.g. HmacSHA1, HmacSHA256)
❖ Chained usage of symmetric cryptographic encryption algorithm (Poly1305-
AES)
Miscellaneous: Base64 encoding
❖ What is Base64 encoding?
❖ It is not encryption :)
❖ It is just a way to encode/decode binary content (byte array) into textual
representation
❖ Compared to binaryHex string representation, it takes less space
Example: JWT
❖ JSON Web Tokens
❖ Similar to digital certificates
❖ Example
Example from the jwt.io
Miscellaneous: Cryptographic Providers
❖ Java Cryptographic Provider: provider of (cryptographic) algorithm
implementations => HashMap of cryptographic algorithm names and their
implementations
❖ MessageDigestSpi, SignatureSpi, CipherSpi… (SPI = Service Provider
Interface)
❖ Best known providers: BouncyCastle, IAIK, Sun PKCS#11, OpenSSL
❖ Security.getProviders()
Let us recap!
❖ Feedback time:
❖ How do you like the Strategy/Factory pattern used in Java Cryptography
Architecture?
❖ Do you find examples relevant for the topic?
❖ A few additional words:
❖ Trying to simplify the topic, Java KeyStore was excluded from the talk
❖ There is another nice application of Decorator design pattern:
DigestInput/OutputStream, Signature, Cipher IO Streams
Additional Resources
❖ Examples from this talk: https://github.com/alexradul/java-cryptography-playbook
❖ Cryptography for Java Developers: https://www.youtube.com/watch?v=1925zmDP_BY
❖ Real-World Cryptography book: https://www.manning.com/books/real-world-cryptography
❖ Understanding PKI book: https://www.oreilly.com/library/view/understanding-pki-
concepts/0672323915/
❖ Bouncy Castle: https://www.bouncycastle.org/
❖ Very rich and versatile Java cryptographic provider
❖ Library encapsulating different cryptographic formats & protocols:
org.bouncycastle/bcpkix-jdk15on

More Related Content

Similar to Introduction to Cryptography in Java with Design Patterns and Examples

BCS_PKI_part1.ppt
BCS_PKI_part1.pptBCS_PKI_part1.ppt
BCS_PKI_part1.pptUskuMusku1
 
Digital signature & eSign overview
Digital signature & eSign overviewDigital signature & eSign overview
Digital signature & eSign overviewRishi Pathak
 
Applied cryptanalysis - everything else
Applied cryptanalysis - everything elseApplied cryptanalysis - everything else
Applied cryptanalysis - everything elseVlad Garbuz
 
Basic Cryptography.pdf
Basic Cryptography.pdfBasic Cryptography.pdf
Basic Cryptography.pdfSetiya Nugroho
 
Breaking out of crypto authentication
Breaking out of crypto authenticationBreaking out of crypto authentication
Breaking out of crypto authenticationMohammed Adam
 
6. cryptography
6. cryptography6. cryptography
6. cryptography7wounders
 
Secure & authentication By Lai HIEU - eXo SEA
Secure & authentication By Lai HIEU - eXo SEASecure & authentication By Lai HIEU - eXo SEA
Secure & authentication By Lai HIEU - eXo SEAThuy_Dang
 
Strong cryptography in PHP
Strong cryptography in PHPStrong cryptography in PHP
Strong cryptography in PHPEnrico Zimuel
 
Data Security Essentials - JavaOne 2013
Data Security Essentials - JavaOne 2013Data Security Essentials - JavaOne 2013
Data Security Essentials - JavaOne 2013javagroup2006
 
Secure JAX-RS
Secure JAX-RSSecure JAX-RS
Secure JAX-RSPayara
 
Automatic tool for static analysis
Automatic tool for static analysisAutomatic tool for static analysis
Automatic tool for static analysisChong-Kuan Chen
 
Dnssec tutorial-crypto-defs
Dnssec tutorial-crypto-defsDnssec tutorial-crypto-defs
Dnssec tutorial-crypto-defsAFRINIC
 
[CONFidence 2016] Marco Ortisi - Recover a RSA private key from a TLS session...
[CONFidence 2016] Marco Ortisi - Recover a RSA private key from a TLS session...[CONFidence 2016] Marco Ortisi - Recover a RSA private key from a TLS session...
[CONFidence 2016] Marco Ortisi - Recover a RSA private key from a TLS session...PROIDEA
 

Similar to Introduction to Cryptography in Java with Design Patterns and Examples (20)

BCS_PKI_part1.ppt
BCS_PKI_part1.pptBCS_PKI_part1.ppt
BCS_PKI_part1.ppt
 
Digital signature & eSign overview
Digital signature & eSign overviewDigital signature & eSign overview
Digital signature & eSign overview
 
Applied cryptanalysis - everything else
Applied cryptanalysis - everything elseApplied cryptanalysis - everything else
Applied cryptanalysis - everything else
 
Ciphers
CiphersCiphers
Ciphers
 
Cryptography
CryptographyCryptography
Cryptography
 
Basic Cryptography.pdf
Basic Cryptography.pdfBasic Cryptography.pdf
Basic Cryptography.pdf
 
Overview of cryptography
Overview of cryptographyOverview of cryptography
Overview of cryptography
 
Breaking out of crypto authentication
Breaking out of crypto authenticationBreaking out of crypto authentication
Breaking out of crypto authentication
 
6. cryptography
6. cryptography6. cryptography
6. cryptography
 
Secure & authentication By Lai HIEU - eXo SEA
Secure & authentication By Lai HIEU - eXo SEASecure & authentication By Lai HIEU - eXo SEA
Secure & authentication By Lai HIEU - eXo SEA
 
Strong cryptography in PHP
Strong cryptography in PHPStrong cryptography in PHP
Strong cryptography in PHP
 
Pki by Steve Lamb
Pki by Steve LambPki by Steve Lamb
Pki by Steve Lamb
 
Moein
MoeinMoein
Moein
 
Data Security Essentials - JavaOne 2013
Data Security Essentials - JavaOne 2013Data Security Essentials - JavaOne 2013
Data Security Essentials - JavaOne 2013
 
Secure JAX-RS
Secure JAX-RSSecure JAX-RS
Secure JAX-RS
 
Encryption Primer por Cathy Nolan
Encryption Primer por Cathy NolanEncryption Primer por Cathy Nolan
Encryption Primer por Cathy Nolan
 
Java Crypto
Java CryptoJava Crypto
Java Crypto
 
Automatic tool for static analysis
Automatic tool for static analysisAutomatic tool for static analysis
Automatic tool for static analysis
 
Dnssec tutorial-crypto-defs
Dnssec tutorial-crypto-defsDnssec tutorial-crypto-defs
Dnssec tutorial-crypto-defs
 
[CONFidence 2016] Marco Ortisi - Recover a RSA private key from a TLS session...
[CONFidence 2016] Marco Ortisi - Recover a RSA private key from a TLS session...[CONFidence 2016] Marco Ortisi - Recover a RSA private key from a TLS session...
[CONFidence 2016] Marco Ortisi - Recover a RSA private key from a TLS session...
 

Recently uploaded

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 

Recently uploaded (20)

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 

Introduction to Cryptography in Java with Design Patterns and Examples

  • 1. Aleksandar Radulovic Introduction to Cryptography in Java Spiced up with Design Patterns and some examples
  • 2. What you shouldn’t expect? ❖ Why privacy does not exist on the Internet? ❖ How to prevent your girlfriend/boyfriend/spouse to read your messages? ❖ Stories about Caesars cipher, Enigma, historical stuff ❖ Details about algorithms
  • 3. What to expect? ❖ Get acquainted with cryptographic glossary ❖ What kinds of cryptographic algorithm exist and what is their purpose ❖ How to differentiate between secret (symmetric) and public (asymmetric) key cryptography? ❖ How to use them ❖ Why Base64 encoding/decoding has nothing to do with encryption ❖ Goals: ❖ How easy it is to use cryptography in Java, having algorithms encapsulated into high-level interfaces ❖ Improve awareness of presence of cryptography in our everyday life and work ❖ Sparkle curiosity
  • 4. Language of patterns ❖ Strategy design pattern: Every class of algorithm is encapsulated into a dedicated interface: MessageDigest, Cipher, Signature, Mac, … ❖ Factory design pattern: Every cryptographic object is created by using static method: getInstance(algorithm: string) ❖ Slide patterns: for each class of cryptographic algorithms we will have: ❖ Purpose ❖ Features ❖ Best known algorithms ❖ Examination of the API interface (Strategy ^) ❖ Example/Usage
  • 5. The Purpose of Cryptography ❖ Integrity: Message Digest ❖ Confidentiality/Secrecy: Cipher ❖ Authentication: Signatures and Message Authentication Codes ❖ Non-repudiation: Signatures (+ additional legislation) ❖ Bonus points: ❖ Word Cryptography comes from Greek kryptos, meaning “hidden” or “secret” and graphein, meaning “to write” ❖ Word Code denotes a system of words, letters, figures, or other symbols substituted for other words, letters, etc., especially for the purposes of secrecy.
  • 6. Message Digest ❖ Synonyms: Cryptographic Hash Function, Cryptographic Checksum, one-way function ❖ Purpose: Data Integrity / Has this data been changed? ❖ Features: ❖ For arbitrary input data length, cryptographic checksum length remains constant ❖ Small change in input data results in huge change in the checksum ❖ Well-known algorithms: MD5, SHA1, SHA-2 (SHA224, 256, 364, 512), SHA-3 ❖ Real life usage: software downloads, credit card numbers, account numbers, … Digest Engine SHA-256 Byte Stream Fixed Length Cryptographic Checksum
  • 7. java.security.MessageDigest MessageDigest md = MessageDigest.getInstance(“SHA-256”); md.reset(); md.update(byteArray); var checksum = md.digest(); Resets digest object to the initial state. Can be called multiple times. Does the final computation and resets digest object. Static factory method. Strategy
  • 8. Confidentiality: High-Level Overview Algoritm = Transformation Key = Parameter Kerckhoff’s principle: Algorithms are public, keys are secret * Algorithms are safe - it is not computationally feasible to transform cipher text into plain text without knowing key * Keys have sufficient lengths * Key generation algorithm is not predictable Algorithm Plain text Cipher text
  • 9. Secret vs Public Key Cryptography ❖ Secret (symmetric) key cryptography: encryption key = decryption key ❖ Public (asymmetric) key cryptography ❖ Both Jovana and Matija have their own key pair: public key, private key ❖ It is easy to calculate public key from private one, not vice versa ❖ What is encrypted with public key, can be decrypted with private key => ❖ Everyone can encrypt content for Jovana using her public key, but only she can decrypt cipher text using her private key ❖ If Jovana encrypts something using her private key, anybody can decrypt cipher text using her public key => digital signature Plain text Cipher text Matija Jovana Plain text Cipher text Jovana Encryption Decryption
  • 10. Symmetric vs Asymmetric Ciphers ❖ Symmetric encryption algorithms: ❖ Faster than asymmetric ❖ Confidentiality ❖ Examples: AES (Advanced Encryption Standard), DES (Data Encryption Standard), Triple DES (DESEDE), IDEA, Blowfish, RC2, RC4 ❖ Asymmetric encryption algorithms: ❖ Confidentiality ~ key exchange (RSA) ❖ Digital Signatures (RSA, ECDSA) ❖ Authentication (RSA, ECDSA)
  • 11. Block Ciphers ❖ Block vs Stream Ciphers ❖ Block cipher operating modes: Electronic Code Book (ECB), Cipher Block Chaining (CBC), Cipher Feedback, … ❖ Initialisation Vector (IV) ❖ Block ciphers in a streaming mode ❖ Padding (to the full block length) is applied when needed: NoPadding, PKCS5Padding, OAEPWithSHA-1AndMGF1Padding Chaining of cipher blocks
  • 12. javax.crypto.Cipher KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(192); SecretKey secretKey = keyGenerator.generateKey(); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] cipherText = cipher.doFinal(plainText); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedPlainText = cipher.doFinal(cipherText); Auxiliary stuff to get a random/session key. Algorithm / Mode / Padding Initialisation of the Cipher object. update() , doFinal(): do the work Initialisation of the Cipher object: decrypt mode Decrypt.
  • 13. Signature ❖ Purpose: Message Authentication ❖ Integrity (Has this data been changed?) ❖ Origin (Is it really coming from the trusted source?) ❖ Features: inherits message digest & asymmetric cipher features ❖ Algorithms: SHA256withRSA, SHA1withRSA, SHA256withDSA, SHA256withECDSA, etc. ❖ Note: DSA & ECDSA are used only for signature, they don’t have Cipher capability of RSA ❖ Example Digest (e.g.SHA- 256) Input message Signature Cipher.encrypt (e.g. RSA) Private key Signature Cipher.decrypt (e.g. RSA) Public key Message Digest Digest (e.g.SHA- 256) Input message
  • 14. Message Authentication Code ❖ Very similar to signatures: features, API, usage ❖ Different implementations: ❖ Message Digest + secret value (e.g. HmacSHA1, HmacSHA256) ❖ Chained usage of symmetric cryptographic encryption algorithm (Poly1305- AES)
  • 15. Miscellaneous: Base64 encoding ❖ What is Base64 encoding? ❖ It is not encryption :) ❖ It is just a way to encode/decode binary content (byte array) into textual representation ❖ Compared to binaryHex string representation, it takes less space
  • 16. Example: JWT ❖ JSON Web Tokens ❖ Similar to digital certificates ❖ Example Example from the jwt.io
  • 17. Miscellaneous: Cryptographic Providers ❖ Java Cryptographic Provider: provider of (cryptographic) algorithm implementations => HashMap of cryptographic algorithm names and their implementations ❖ MessageDigestSpi, SignatureSpi, CipherSpi… (SPI = Service Provider Interface) ❖ Best known providers: BouncyCastle, IAIK, Sun PKCS#11, OpenSSL ❖ Security.getProviders()
  • 18. Let us recap! ❖ Feedback time: ❖ How do you like the Strategy/Factory pattern used in Java Cryptography Architecture? ❖ Do you find examples relevant for the topic? ❖ A few additional words: ❖ Trying to simplify the topic, Java KeyStore was excluded from the talk ❖ There is another nice application of Decorator design pattern: DigestInput/OutputStream, Signature, Cipher IO Streams
  • 19. Additional Resources ❖ Examples from this talk: https://github.com/alexradul/java-cryptography-playbook ❖ Cryptography for Java Developers: https://www.youtube.com/watch?v=1925zmDP_BY ❖ Real-World Cryptography book: https://www.manning.com/books/real-world-cryptography ❖ Understanding PKI book: https://www.oreilly.com/library/view/understanding-pki- concepts/0672323915/ ❖ Bouncy Castle: https://www.bouncycastle.org/ ❖ Very rich and versatile Java cryptographic provider ❖ Library encapsulating different cryptographic formats & protocols: org.bouncycastle/bcpkix-jdk15on