Category: Education

Presentation Description

No description available.


By: pacx (118 month(s) ago)

i want to download this presentation

By: vishwajit321 (123 month(s) ago)

i want to download this presentation ...

By: niteenacharya (124 month(s) ago)

i want to download this presentation ...

By: sazharuddin18 (130 month(s) ago)

This is a very good presentation. i want to download this presentation.

Presentation Transcript

Introduction to Java Cryptography: 

Introduction to Java Cryptography Matt Secoske


Covering: Brief history of Crypto JCA/JCE History API Public Key Infrastructure (PKI) Secure Communications with Java

History of Cryptography: 

History of Cryptography Egyptian Hieroglyphs Substitution Ciphers (Paper based) DES Private Key - Diffie Hellman / RSA Quantum Cryptography > 500 BCE 300 BCE 1976 1984 AES 2001 The Enigma (electro mech) 1920s Classic Cryptography Modern Cryptography


Ciphers One - Way functions irreversible calculation cannot derive input from output Two - Way functions Reversible

An example: 


Uses for Cryptography:: 

Uses for Cryptography: Cryptographic Hashes (Digests) Message Authentication Idempotency Encryption (Symmetric / Asymmetric) Secure communications Secure Storage Privacy Digital Signatures Identity / Trust Tamper detection


JCA / JCE JCA - Java Cryptography Architecture Part of JDK 1.1 release Authentication (Digests, Signatures) package JCE - Java Cryptography Extension Initially a separate extension (part of JDK as of 1.4) Encryption, Key Generation algorithms javax.crypto package


JCE Provides standardized interface for access cryptographic functions Uses Factory / Strategy patterns to provide consistent API for all algorithms Provider plug-in architecture to allow third party implementations.


Configuration Provider List Stored in: JAVA_HOME/lib/security/ Order is very important First provider to implement algorithm is default Example: security.provider.5=com.sun.crypto.provider.SunJCE


Restricted! Due to import/export restrictions on cryptographic mechanisms (both h/w and s/w), the JCE comes default with “strong” algorithm strengths If you want to use unlimited strength, download the “Unrestricted Policy File” from Sun Allows unlimited key sizes


Providers Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding","SunJCE"); Flexible extension Allows detailed selection of algorithm Algorithm/Mode/Pad Provider (opt)


Providers Dynamically add providers at Runtime: import; import javax.crypto.Cipher; import org.bouncycastle.jce.provider.BouncyCastleProvider; … Security.addProvider(new BouncyCastleProvider()); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding", "BC");

Getting Provider Details: 

Getting Provider Details import; import; import; ... for(Provider p : Security.getProviders()) { System.out.println(”========================"); System.out.println("Provider: "+ p.getName()); for(Service s : p.getServices()) { System.out.println(s.getAlgorithm()); } }

Random Numbers: 

Random Numbers Aid in generating timestamps, salts, keys, etc import; SecureRandom random = new SecureRandom(); // try to come up with a relatively unique seed long seed = System.nanoTime() ^ Runtime.getRuntime().freeMemory(); random.setSeed(seed); byte bytes[] = new byte[20]; random.nextBytes(bytes); //bytes=150526efd293b645e31b1dbba98b600ce38228dc

Cryptographic Hashes: 

Cryptographic Hashes MessageDigest One way function: creates statistically* unique value for given input Algorithms: SHA/1/256/512 MD5** * For a given value, the only truly unique value is the value itself ** MD5 is no longer considered secure. See

try { MessageDigest md = MessageDigest.getInstance("SHA"); byte[] digest = md.digest("Hello World".getBytes()); } catch (NoSuchAlgorithmException nsae) { } // digest = 0a4d55a8d778e5022fab701977c5d840bbc486d0: 

try { MessageDigest md = MessageDigest.getInstance("SHA"); byte[] digest = md.digest("Hello World".getBytes()); } catch (NoSuchAlgorithmException nsae) { } // digest = 0a4d55a8d778e5022fab701977c5d840bbc486d0

Symmetric Ciphers: 

Symmetric Ciphers aka Secret Key cryptography A key is shared between two (or more) parties Anyone with the key can decrypt the message or send a new one Typically faster than Asymmetric algorithms Types: Block - processes a block of bytes at a time Stream - one bit at a time

Symmetric Encryption Illustrated: Symmetric Encryption Illustrated

Symmetric Algorithms: 

Symmetric Algorithms DES Date Encryption Standard (from 1976) 8 byte (56 bits + checksum) keys Triple-DES aka (DES-ede) ede = Encrypt - Decrypt - Encrypt 2 DES Keys or 3 DES Keys (stronger) AES (Rijndael) Advanced Encryption Standard Standard since 2001 128, 192, 256 bit key sizes

Encrypting / Decrypting with Cipher: 

Encrypting / Decrypting with Cipher byte[] keyMaterial = "my super secret password".getBytes(); String message = "Hello, World!"; SecretKeySpec key = new SecretKeySpec(keyMaterial, "AES"); // encrypting Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key ); byte[] plaintext = message.getBytes("8859_1"); // plaintext = 48656c6c6f2c20576f726c6421 byte[] ciphertext = cipher.doFinal(plaintext); // ciphertext = 93a5f36dfbfb518b2f94d61616d4505 // decrypting cipher.init(Cipher.DECRYPT_MODE, key); byte[] plaintext2 = cipher.doFinal(ciphertext); // plaintext2 = 48656c6c6f2c20576f726c6421

Password Based Encryption: 

Password Based Encryption Uses standard symmetric algorithms Combines a password and a salt to form key Only as secure as the password chosen

PBE with TripleDES: 

PBE with TripleDES String keyMaterial = "my super secret password"; byte[] salt = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; int iterationCount = 2048; PBEKeySpec keySpec = new PBEKeySpec(keyMaterial.toCharArray(), salt, iterationCount); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHAAnd3KeyTripleDES", "BC"); Key key = keyFactory.generateSecret(keySpec); String message = "Hello, World!"; // encrypting Cipher cipher = Cipher.getInstance("PBEWithSHAAnd3KeyTripleDES", "BC"); cipher.init(Cipher.ENCRYPT_MODE, key ); byte[] plaintext = message.getBytes("8859_1"); // plaintext = 48656c6c6f2c20576f726c6421 byte[] ciphertext = cipher.doFinal(plaintext); // ciphertext = 16c6640f2b7f55cf416be9130b905eca

Asymmetric Ciphers : 

Asymmetric Ciphers aka Public Key Cryptography Key consists of two related parts: Public key - typically contained in a certificate Private key - kept secret Mathematically hard (but possible) to derive private key from public key

Asymmetric Encryption Illustrated: Asymmetric Encryption Illustrated Use Public Key to: send messages to Private Key holder verify digital signature of Private Key

Public Key Infrastructure (PKI) (in a very small nutshell): 

Public Key Infrastructure (PKI) (in a very small nutshell) Certificates (Public Keys) form a hierarchy of trust starting with a root certificate which trusts (signs) Certificate Authorities Which trust (sign) common certificates The common certificate, including its hierarchy is a certificate chain Hierarchy is managed with Certificate Revocation Lists

Key Stores: 

Key Stores Store and retrieve keys and Certificates from a password protected file or hardware device Keytool : command line interface for accessing keystore files CACerts - contains common root certificates JAVA_HOME/lib/security/cacerts Default keystore ~/.keystore (Mac/Linux) \document and settings\profile\.keystore


KeyTool Generate a self signed certificate ~$ keytool -genkey -alias mykey -keyalg RSA -keysize 1024 -keystore -storetype JCEKS -storepass password What is your first and last name? [Unknown]: Common Name What is the name of your organizational unit? [Unknown]: OU What is the name of your organization? [Unknown]: O What is the name of your City or Locality? [Unknown]: L What is the name of your State or Province? [Unknown]: S What is the two-letter country code for this unit? [Unknown]: US Is CN=Common Name, OU=OU, O=O, L=L, ST=S, C=US correct? [no]: yes Enter key password for <mykey> (RETURN if same as keystore password): ~$ keytool -selfcert -alias mykey -keystore -storetype JCEKS -storepass password ~$


Signature char[] password = "password".toCharArray(); KeyStore ks = KeyStore.getInstance("JCEKS"); FileInputStream fis = new FileInputStream(""); ks.load(fis, password); Key privateKey = ks.getKey("mykey", password); X509Certificate cert = (X509Certificate) ks.getCertificate("mykey"); fis.close(); byte[] mydata = "Bob, your secret is safe with me".getBytes(); Signature sig = Signature.getInstance("SHA1withRSA"); sig.initSign((PrivateKey) privateKey); sig.update(mydata); byte[] signature = sig.sign(); System.out.println("signature: " + toHex(signature)); //6592a835c24d98efa1cda70c179ab9d1b887b4dd0682c3451176fd921e12dab9fa6189813f22c7a8248654a8d87f356b5565fc952104af04ceb1138e9be3034137944a98262876089e9875c1ad3f673cb035d9d56a1dc9e359b45dcd8029e69065728072569ce235fa4fec0f9b560606bc080e7b5c5af3fb7846f2db600a9732 sig.initVerify(cert); boolean valid = sig.verify(signature); System.out.println("Valid? " + valid);

Secure Communications: 

Secure Communications SSL with the JSSE SSH/SFTP with the JSch library

Java Secure Socket Extension: 

Java Secure Socket Extension SSL/TLS support Provides implementations for Socket ServerSocket 100% Java Part of the JDK as of 1.4 package

SSL Handshake: 

SSL Handshake

Creating an SSL Socket: 

Creating an SSL Socket SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); Socket s = factory.createSocket("", 443); // use the Input/Output streams as usual


JSch Java Secure Channel library Features SSH / SFTP Port forwarding Builds on top of JSSE Used by SSH/SCP Ant tasks Many examples, but lacks documentation

Creating an SSH Connection with JSch: 

Creating an SSH Connection with JSch JSch jsch=new JSch(); jsch.setKnownHosts("~/.ssh/known_hosts"); Session session=jsch.getSession("user", "host", 22); session.setPassword("password"); // optional… this usually should not be used Hashtable config = new Hashtable(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(30000); Channel channel=session.openChannel("shell"); channel.setInputStream(; channel.setOutputStream(System.out); channel.connect();

Additional Resources: 

Additional Resources Wikipedia has tons of excellent articles on Cryptography “Beginning Cryptography with Java” by David Hook Sun’s JCE Documentation: Bouncy Castle JCE Provider


Thank You! slides at:

authorStream Live Help