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

Introduction to Cryptography.pptx

  • 1.
    Aleksandar Radulovic Introduction to Cryptographyin Java Spiced up with Design Patterns and some examples
  • 2.
    What you shouldn’texpect? ❖ 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 ofCryptography ❖ 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 PublicKey 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 AsymmetricCiphers ❖ 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 ❖ Blockvs 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: MessageAuthentication ❖ 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 ❖ JSONWeb 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 ❖ Examplesfrom 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