Sei sulla pagina 1di 36

Introduction to

Java Cryptography
Matt Secoske
http://blog.secosoft.net
http://objectpartners.com

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Covering:

• Brief history of Crypto


• JCA/JCE
– History
– API
• Public Key Infrastructure (PKI)
• Secure Communications with Java

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Eg
yp

> 500 BCE
tian 
Hi
erog
Su ly p
b

300 BCE
s hs
Cip titu
her tion
s (
Pa
per
 ba
s ed
)

Classic Cryptography
1920s
Th

En
DE igma
S  (e
lec
1976

tro
Pri  m
History of Cryptography

v ech
Di ate 
ffie Ke )
1984

 He y ­ 
Qu llm
ant an 
um / R
SA
2001

 Cr
AE yp
tog
S
Modern Cryptography

rap
hy
Intro to Java Cryptograph
Matt Secoske NFJS 2007
Ciphers

• One - Way functions


– irreversible calculation
– cannot derive input from output
• Two - Way functions
– Reversible

Intro to Java Cryptograph


Matt Secoske NFJS 2007
An example

Alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Key: PQOYWVNBGULSZCKXDFEMIJRHTA

Message: THE QUICK BROWN FOX


Cipher Text: MBW DIGOL QFKRC VKH

Intro to Java Cryptograph


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

Intro to Java Cryptograph


Matt Secoske NFJS 2007
JCA / JCE

• JCA - Java Cryptography Architecture


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

Intro to Java Cryptograph


Matt Secoske NFJS 2007
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.

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Configuration
• Provider List
– Stored in:
JAVA_HOME/lib/security/java.security
– Order is very important
– First provider to implement algorithm is default
– Example:
security.provider.1=sun.security.provider.Sun
security.provider.2=com.apple.crypto.provider.Apple
security.provider.3=sun.security.rsa.SunRsaSign
security.provider.4=com.sun.net.ssl.internal.ssl.Provider
security.provider.5=com.sun.crypto.provider.SunJCE
security.provider.6=sun.security.jgss.SunProvider
security.provider.7=com.sun.security.sasl.Provider
Intro to Java Cryptograph
Matt Secoske NFJS 2007
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

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Providers
• Flexible extension
• Allows detailed selection of algorithm

Cipher cipher =
Cipher.getInstance("DES/ECB/PKCS5Padding","SunJCE");
Algorithm/Mode/Pad Provider (opt)

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Providers
Dynamically add providers at Runtime:
import java.security.Security;
import javax.crypto.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

Security.addProvider(new BouncyCastleProvider());
Cipher cipher =
Cipher.getInstance("DES/ECB/PKCS5Padding", "BC");

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Getting Provider Details
import java.security.Provider;
import java.security.Security;
import java.security.Provider.Service;
...
for(Provider p : Security.getProviders()) {

System.out.println(”=====================
===");
System.out.println("Provider: "+ p.getName());
for(Service s : p.getServices()) {
System.out.println(s.getAlgorithm());
}
}
Intro to Java Cryptograph
Matt Secoske NFJS 2007
Random Numbers
• Aid in generating timestamps, salts, keys, etc
import java.security.SecureRandom;

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

Intro to Java Cryptograph


Matt Secoske NFJS 2007
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 http://www.cits.rub.de/MD5Collisions/

Intro to Java Cryptograph


Matt Secoske NFJS 2007
try {

MessageDigest md = MessageDigest.getInstance("SHA");
byte[] digest = md.digest("Hello World".getBytes());

} catch (NoSuchAlgorithmException nsae) {


}

// digest = 0a4d55a8d778e5022fab701977c5d840bbc486d0

Intro to Java Cryptograph


Matt Secoske NFJS 2007
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

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Symmetric Encryption Illustrated
Encryption Decryption

http://en.wikipedia.org/wiki/Block_cipher

Intro to Java Cryptograph


Matt Secoske NFJS 2007
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

Intro to Java Cryptograph


Matt Secoske NFJS 2007
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

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Password Based Encryption

• Uses standard symmetric algorithms


• Combines a password and a salt to form key
• Only as secure as the password chosen

Intro to Java Cryptograph


Matt Secoske NFJS 2007
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

Intro to Java Cryptograph


Matt Secoske NFJS 2007
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

http://en.wikipedia.org/wiki/Asymmetric_key_algorithm
Intro to Java Cryptograph
Matt Secoske NFJS 2007
Asymmetric Encryption Illustrated
• Use Public Key to:
– send messages to Private Key holder
– verify digital signature of Private Key

http://en.wikipedia.org/wiki/Asymmetric_key_algorithm
Intro to Java Cryptograph
Matt Secoske NFJS 2007
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 Root
– Which trust (sign) common certificates
CA CA
– The common certificate, including
CA
its hierarchy is a certificate chain
• Hierarchy is managed cert

with Certificate Revocation Lists

Intro to Java Cryptograph


Matt Secoske NFJS 2007
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

Intro to Java Cryptograph


Matt Secoske NFJS 2007
KeyTool
• Generate a self signed certificate
~$ keytool -genkey -alias mykey -keyalg RSA -keysize 1024 -keystore my_keys.store -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 my_keys.store -storetype JCEKS -storepass password
~$

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Signature
char[] password = "password".toCharArray();
KeyStore ks = KeyStore.getInstance("JCEKS");
FileInputStream fis = new FileInputStream("my_keys.store");
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));
//6592a835c24d98efa1cda70c179ab9d1b887b4dd0682c3451176fd921e12dab9fa6189813f22c7a
8248654a8d87f356b5565fc952104af04ceb1138e9be3034137944a98262876089e9875c1ad3f67
3cb035d9d56a1dc9e359b45dcd8029e69065728072569ce235fa4fec0f9b560606bc080e7b5c5af3
fb7846f2db600a9732
sig.initVerify(cert);
boolean valid = sig.verify(signature);
System.out.println("Valid? " + valid);

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Secure Communications

• SSL with the JSSE


• SSH/SFTP with the JSch library

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Java Secure Socket Extension
• SSL/TLS support
• Provides implementations for
– Socket
– ServerSocket
• 100% Java
• Part of the JDK as of 1.4
• javax.net package

Intro to Java Cryptograph


Matt Secoske NFJS 2007
SSL Handshake

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Creating an SSL Socket

SSLSocketFactory factory =
(SSLSocketFactory) SSLSocketFactory.getDefault();

Socket s =
factory.createSocket("https://google.com", 443);

// use the Input/Output streams as usual

Intro to Java Cryptograph


Matt Secoske NFJS 2007
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

Intro to Java Cryptograph


Matt Secoske NFJS 2007
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(System.in);
channel.setOutputStream(System.out);

channel.connect();

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Additional Resources
• Wikipedia has tons of excellent articles on
Cryptography http://en.wikipedia.org/wiki/Cryptography
• “Beginning Cryptography with Java” by
David Hook
• Sun’s JCE Documentation:
http://java.sun.com/j2se/1.5.0/docs/guide/security/CryptoSpec.html

• Bouncy Castle JCE Provider


http://bouncycastle.org

Intro to Java Cryptograph


Matt Secoske NFJS 2007
Thank You!

slides at: http://blog.secosoft.net

Intro to Java Cryptograph


Matt Secoske NFJS 2007

Potrebbero piacerti anche