Download Java Tools - Andrew.cmu.edu

Document related concepts
no text concepts found
Transcript
Applied Cryptography
Week 3 Java Tools
Michael McCarthy
Applied Cryptography
1
Java Tools
• Security Provider Architecture
• Example Programs
Message Digests
Symmetric Encryption
Digital Signature Algorithm (DSA)
Password Based Encryption (PBE)
Session Key Encryption (RSA)
Reading certificates
Diffie-Hellman Key Exchange
Applied Cryptography
2
Java Tools
• The Security API is a core API of the Java programming language,
built around the java.security package (and its subpackages).
Since JDK 1.1 "Java Cryptography Architecture" (JCA)
includes Digital Signatures and Message Digests
Since JDK 1.4 the Java Cryptography Extension (JCE) is included.
This extends the JCA API to include APIs for
encryption, key exchange, and
Message Authentication Code (MAC).
Applied Cryptography
3
The Security Architecture
Java describes operations (engines). There may be several
vendors that have implementations of these engines.
This is all set up so that the programmer can select which
vendor’s code to use.
Applied Cryptography
4
Example Engine Classes
MessageDigest
Signature
KeyFactory
KeyPairGenerator
SecureRandom
A program may simply request a particular engine
(such as a MessageDigest object) implementing a particular
algorithm (such as the secure hash algorithm SHA-1)
and get an implementation from one of the installed providers.
Applied Cryptography
5
The Architecture Of Security
Providers
Engines are always abstract and independent of any particular
algorithm. Think of engines as operations. A Message Digest
operation may be computed in several ways (MD5, SHA1).
Different providers will implement MD5 differently.
An algorithm is an implementation of an engine.
The programmer works with the engine. The administrator
sets the provider.
Applied Cryptography
6
SUNJSSE
Application
Programmer
SUNRSAS16N
1.3
Java.Security.Security
Engine Class
Provider Class
Security Class
Algorithm Class
Message Digest
SUN
Asks providers if
they can handle a
MessageDigest.MD5
From
same
vendor
Provider
“MessageDigest.MDS”
engine algorithm
KeyPairGenerator.DSA
Holds a list
of providers
SUNJCE
From
same
vendor
Security Provider
Applied Cryptography
Map (engine, algorithm) pair to a class
7
From
jre/lib/security/java.security
# Each Provider may implement several engines
#
security.provider.1=sun.security.provider.Sun
security.provider.2=com.sun.net.ssl.internal.ssl.Provider
security.provider.3=com.sun.rsajca.Provider
security.provider.4=com.sun.crypto.provider.SunJCE
security.provider.5=sun.security.jgss.SunProvider
Applied Cryptography
8
Looking at Providers
// Page 161 of "Java Security" Oaks
import java.security.*;
import java.util.*;
public class ExamineSecurity {
public static void main(String args[]) {
Applied Cryptography
9
try {
Provider p[] = Security.getProviders();
for(int i = 0; i < p.length; i++) {
System.out.println(p[i]);
for(Enumeration e = p[i].keys(); e.hasMoreElements(); )
System.out.println("\t" + e.nextElement());
}
}
catch(Exception e) {
System.out.println(e);
}
}
}
Applied Cryptography
10
java ExamineSecurity
Providers
SUN version 1.2
Signature.SHA1withDSA KeySize
Signature.SHA1withDSA ImplementedIn
CertificateFactory.X509 ImplementedIn
AlgorithmParameterGenerator.DSA
Alg.Alias.Signature.SHA/DSA
Pages deleted …
SunJSSE version 1.4
SSLContext.SSL
KeyManagerFactory.SunX509
Signature.MD5withRSA
Signature.SHA1withRSA
KeyFactory.RSA Applied Cryptography
Engine, Algorithm
provided
11
SunRsaSign version 1.0
KeyFactory.RSA
Signature.MD5withRSA
Signature.SHA1withRSA
Signature.MD2withRSA
KeyPairGenerator.RSA
Many deletions
BouncyCastle
added later
SunJCE version 1.4
Cipher.DES
KeyStore.JCEKS
Alg.Alias.SecretKeyFactory.TripleDES
SecretKeyFactory.DES
SunJGSS version 1.0
Applied Cryptography
12
MessageDigest is an Engine
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class ComputeAMessageDigest {
public static void main(String args[]) {
MessageDigest sha=null;
try {
// engine
algorithm
sha = MessageDigest.getInstance("SHA-1");
}
catch(NoSuchAlgorithmException e) {
System.out.println("No
such algorithm");
Applied Cryptography
}
13
System.out.println(sha.getAlgorithm());
String s = "Applied Cryptography";
byte a[] = s.getBytes();
sha.update(a);
byte[] hash = sha.digest();
System.out.println("The hash value of ‘" + s + “’ is ");
for(int i = 0; i < hash.length; i++) {
System.out.print(hash[i] + " ");
}
}
}
Applied Cryptography
14
java ComputeAMessageDigest
SHA-1
The hash value of ‘Applied Cryptography’ is
-57 -97 -77 -73 -64 -13 87 -8 2 -45 44 -16 65 -77 -36 -27 65 51
-109 –104
Add a period…
java ComputeAMessageDigest
SHA-1
The hash value of ‘Applied Cryptography.’ is
-61 106 41 -23 -31 48 0 114 -104 -99 127 -107 -87 -73 77 50 -47
115 -84 -112
Applied Cryptography
15
We Can Choose an Algorithm
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class ComputeAMessageDigest {
public static void main(String args[]) {
MessageDigest sha=null;
try {
// engine
algorithm
sha = MessageDigest.getInstance("MD5");
}
catch(NoSuchAlgorithmException e) {
System.out.println("No such algorithm");
}
Applied Cryptography
16
System.out.println(sha.getAlgorithm());
String s = "Applied Cryptography.";
byte a[] = s.getBytes();
sha.update(a);
byte[] hash = sha.digest();
System.out.println("The hash value of '" + s + "' is ");
for(int i = 0; i < hash.length; i++) {
System.out.print(hash[i] + " ");
}
}
}
Applied Cryptography
17
java ComputeAMessageDigest
MD5
The hash value of 'Applied Cryptography.' is
16 -26 -44 -19 -78 23 13 88 12 -49 17 6 126 -66 -1 -84
Applied Cryptography
18
We Can Choose a Provider
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
public class ComputeSecureRandom {
public static void main(String args[]) {
SecureRandom random = null;
try {
// Secure Hash Algorithm Pseudo Rand Num Gen
random = SecureRandom.getInstance("SHA1PRNG", "SUN");
}
Applied Cryptography
19
catch(NoSuchAlgorithmException e) {
System.out.println("No such algorithm");
}
catch(NoSuchProviderException e) {
System.out.println("No such provider");
}
byte[] myRandomBytes = new byte[10]; // may be any size
random.nextBytes(myRandomBytes);
System.out.println("The random bytes are ");
for(int i = 0; i < myRandomBytes.length; i++) {
System.out.print(myRandomBytes[i]+ " ");
}
}
}
Applied Cryptography
20
Writing Your Own Security
Provider
You must extend the SPI (Security Provider Interface)
of the engine you want to provide.
You must tell the Security class that you are providing
this service.
The programmer will make a request to the Security class
And can specify the engine, algorithm, and the provider
Applied Cryptography
21
A Simple Provider
import java.security.Provider;
public class XYZProvider extends Provider {
public XYZProvider() {
super("XYZCoolProvider", 1.0, "XYZ Security Provider");
// (Engine name, Algorithm name)--> class
put("KeyPairGenerator.XYZ", "XYZKeyPairGenerator");
}
}
Applied Cryptography
22
A Simple Class to Hold a Key
// A class to hold key data for a shift cipher
import java.security.*;
public class XYZKey implements Key, PublicKey, PrivateKey {
private int rotValue;
// required for Key (PublicKey and PrivateKey are markers)
public String getAlgorithm() {
return "XYZ";
}
Applied Cryptography
23
// required for Key
public String getFormat() {
return "XYZ Special Format";
}
public void setRotValue(int i) { rotValue = i; }
public int getRotValue() { return rotValue; }
// required for Key
public byte[] getEncoded() {
byte b[] = new byte[4];
b[3] = (byte)((rotValue >> 24) & 0xff);
b[2] = (byte)((rotValue >> 16) & 0xff);
b[1] = (byte)((rotValue >> 8) & 0xff);
b[0] = (byte)((rotValue >> 0) & 0xff);
return b;
}
}
Applied Cryptography
24
A KeyPairGenerator is an Engine
// From Oaks page 176 with modifications
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Security;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
Applied Cryptography
25
public class XYZKeyPairGenerator extends KeyPairGenerator {
SecureRandom random;
public XYZKeyPairGenerator() {
super("XYZ");
}
public void initialize(int strength, SecureRandom sr) {
System.out.println("Running initialize");
random = sr;
}
Applied Cryptography
26
public KeyPair generateKeyPair() {
int r = random.nextInt() % 25;
XYZKey pub = new XYZKey();
XYZKey priv = new XYZKey();
pub.setRotValue(r);
priv.setRotValue(-r);
KeyPair kp = new KeyPair(pub,priv);
return kp;
}
Applied Cryptography
27
public static void main(String args[]) throws
NoSuchAlgorithmException,
NoSuchProviderException {
// add a new Provider to the Security class
// the new Provider is called XYZCoolProvider and it maps the engine,
// algorithm
// pair "KeyPairGenerator.XYZ" to the class "XYZKeyPairGenerator"
Security.addProvider(new XYZProvider());
// At this point Security knows about the mapping
// Try to get an instance of an XYZKeyPairGenerator
// by requesting from Security a KeyPairGenerator with algorithm XYZ
// and provider XYZCoolProvider – provider name is optional
KeyPairGenerator kpg =
KeyPairGenerator.getInstance("XYZ","XYZCoolProvider");
28
// All KeyPair generators can be initialized
kpg.initialize(0, new SecureRandom());
// get a KeyPair
KeyPair kp = kpg.generateKeyPair();
System.out.println("Got key pair ");
PrivateKey privK = kp.getPrivate();
PublicKey pubK = kp.getPublic();
System.out.println("Algorithm = " + pubK.getAlgorithm());
}
}
Applied Cryptography
29
java XYZKeyPairGenerator
Running initialize
Got key pair
Algorithm = XYZ
Applied Cryptography
30
Symmetric Encryption Example
java WorkingWithBlowfish
ABCDEFG as bytes
41 42 43 44 45 46 47
Cipher text as bytes
9e dd 46 30 b1 14 79 6b
After decryption
ABCDEFG
Applied Cryptography
31
WorkingWithBlowFish.java
import java.security.*;
import javax.crypto.KeyGenerator;
import javax.crypto.Cipher;
public class WorkingWithBlowfish {
public static void main(String args[])throws Exception {
String clear = "ABCDEFG";
System.out.println(clear + " as bytes " );
displayBytes(clear.getBytes());
32
// Build a key from scratch
// Symmetric keys come from the KeyGenerator engine
// Asymmetric keys come from the KeyPairGenerator engine
KeyGenerator kg = KeyGenerator.getInstance("Blowfish");
kg.init(128); // key size
// create the key data
Key k = kg.generateKey();
// We need a Blowfish cipher based on that key
// We specify the algorithm/mode/padding
Cipher cipher = Cipher.getInstance
("Blowfish/ECB/PKCS5Padding");
// initialize the ciper with the key
cipher.init(Cipher.ENCRYPT_MODE, k);
33
// encrypt
byte[] cipherText = cipher.doFinal(clear.getBytes());
System.out.println("Cipher text as bytes " );
displayBytes(cipherText);
// change to decrypt mode using the same key
cipher.init(Cipher.DECRYPT_MODE, k);
byte[] clearBytes = cipher.doFinal(cipherText);
String result = new String(clearBytes);
System.out.println("After decryption \n" + result);
}
Applied Cryptography
34
// display a byte in hex
public static void displayBytes(byte [] b) {
for (int i = 0; i < b.length; i++) {
byte aByte = b[i];
String hexLo = Integer.toHexString( aByte & 0x0F );
String hexHi = Integer.toHexString( (aByte >> 4) & 0x0F );
System.out.print(hexHi + hexLo + " ");
}
System.out.println();
}
}
Applied Cryptography
35
Algorithm/Mode/Padding
("Blowfish/ECB/PKCS5Padding");
Block ciphers operate on fixed size chunks of data (often 64 bits).
So, sometimes we must add padding to the plaintext.
Typically two options:
No Padding (the plaintext size must be a multiple of 64
bits)
PKCS#5 (Public Key Cryptography Standard)
8 Byte block Example:
HELLO333
padding bytes always present
HELLOJOE
8 8 8 88 888
Applied Cryptography
36
Algorithm/Mode/Padding
("Blowfish/ECB/PKCS5Padding");
The Mode
Block ciphers operate on fixed size chunks
Stream ciphers operate on a byte at a time
ECB (Electronic Code Book ) Mode
Same plaintext block will always encrypt to the same ciphertext
block
Fine for sending single chunks of data (like a key)
Bad for sending a long streams of English text(frequency analysis)
Applied Cryptography
37
Algorithm/Mode/Padding
("Blowfish/ECB/PKCS5Padding");
The Mode
CBC (Cipher Block Chaining)
Uses information from previous blocks to encrypt
the current block.
The same long message still encrypts the same way
every time it is sent.
So, we add random bits in an Initialization Vector or
IV to initialize the cipher. This IV may be public and
should be different for every message.
Applied Cryptography
38
Algorithm/Mode/Padding
("Blowfish/ECB/PKCS5Padding");
CFB (Cipher Feedback)
Like CBC but works on small chunks of data.
Useful for chat session encryption.
Requires an IV for each message sent with the same key.
OFB (Output Feedback)
Like CFB and CBC and requires an IV
One bit error in the ciphertext produces one bad bit in the
plaintext
39
Working With DSA
Signing
• We want to sign an Ascii or binary file
• Use KeyPairGenerator engine to create a DSA key
• Use Signature engine based on SHA1 with DSA
to sign the file
•Display and save the signature and public key
Applied Cryptography
40
// SignFile.java from IBM's "Java 2 Network Security" 2nd. Ed.
import java.io.*;
import java.security.*;
class SignFile
{
public static void main(String arg[])
{
if (arg.length != 3)
System.out.println(
"Usage: java SignFile DATAFILE”+
“SIGNATUREFILE PUBLICKEYFILE");
else
Applied Cryptography
41
try
{
// We create the keypair –
// Key strength can be 1024 inside the United States
KeyPairGenerator KPG = KeyPairGenerator.getInstance
("DSA", "SUN");
SecureRandom r = new SecureRandom();
KPG.initialize(1024, r);
KeyPair KP = KPG.generateKeyPair();
// We get the generated keys
PrivateKey priv = KP.getPrivate();
PublicKey publ = KP.getPublic();
// We intialize the signature
Signature dsasig = Signature.getInstance("SHA1withDSA", "SUN"
dsasig.initSign(priv); Applied Cryptography
42
// We get the file to be signed
FileInputStream fis = new FileInputStream(arg[0]);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buff = new byte[1024];
int len;
// We call the update() method of Signature class ->
// Updates the data to be signed
while (bis.available() != 0)
{
len=bis.read(buff);
dsasig.update(buff, 0, len);
}
// We close the buffered input stream and the file input stream
bis.close();
fis.close();
Applied Cryptography
43
// We get the signature
byte[] realSignature = dsasig.sign();
// We write the signature to a file
FileOutputStream fos = new FileOutputStream(arg[1]);
fos.write(realSignature);
fos.close();
// Dsiplay the signature in hex
System.out.println("The Signature of " + arg[0] + " in hex\n");
displayBytes(realSignature);
// We write the public key to a file
byte[] pkey = publ.getEncoded();
FileOutputStream keyfos = new FileOutputStream(arg[2]);
keyfos.write(pkey);
keyfos.close();
Applied Cryptography
44
// Display the public key in hex
System.out.println("The DSA public key in hex\n");
displayBytes(pkey);
}
catch (Exception e)
{
System.out.println("Caught Exception: " + e);
}
}
Applied Cryptography
45
public static void displayBytes(byte [] b) {
for (int i = 0; i < b.length; i++) {
byte aByte = b[i];
String hexLo = Integer.toHexString( aByte & 0x0F );
String hexHi = Integer.toHexString( (aByte >> 4) & 0x0F );
System.out.print(hexHi + hexLo + " ");
}
System.out.println();
}
}
Applied Cryptography
46
D:\McCarthy\www\95-804\signfile>
java SignFile SignFile.java SignatureFile.txt PublicKeyFile.txt
The Signature of SignFile.java in hex
30 2c 02 14 3b 35 a9 e5 53 41 35 1e 86 43 5c 00 a6 46 be 37 82 1f fc
fb 02 14 08 98 b8 ab 8d 64 af c3 72 ae 84 fb 1b 1d ea cd e4 d0 eb 79
The DSA public key in hex
30 82 01 b8 30 82 01 2c 06 07 2a 86 48 ce 38 04 01 30 82 01 1f 02
81 81 00 fd 7f 53 81 1d 75 12 29 52 df 4a 9c 2e ec e4 e7 f6 11 b7 52
3c ef 44 00 c3 1e 3f 80 b6 51 26 69 45 5d 40 22 51 fb 59 3d 8d 58
fa bf c5 f5 ba 30 f6 cb 9b 55 6c d7 81 3b 80 1d 34 6f f2 66 60 b7
6b 99 50 a5 a4 9f 9f e8 04 7b 10 22 c2 4f bb a9 d7 fe b7 c6 1b f8
Applied Cryptography
47
3b 57 e7 c6 a8 a6 15 0f 04 fb 83 f6 d3 c5 1e c3 02 35 54 13 5a 16
91 32 f6 75 f3 ae 2b 61 d7 2a ef f2 22 03 19 9d d1 48 01 c7 02 15
00 97 60 50 8f 15 23 0b cc b2 92 b9 82 a2 eb 84 0b f0 58 1c f5 02
81 81 00 f7 e1 a0 85 d6 9b 3d de cb bc ab 5c 36 b8 57 b9 79 94 af
bb fa 3a ea 82 f9 57 4c 0b 3d 07 82 67 51 59 57 8e ba d4 59 4f e6
71 07 10 81 80 b4 49 16 71 23 e8 4c 28 16 13 b7 cf 09 32 8c c8 a6
e1 3c 16 7a 8b 54 7c 8d 28 e0 a3 ae 1e 2b b3 a6 75 91 6e a3 7f 0b
fa 21 35 62 f1 fb 62 7a 01 24 3b cc a4 f1 be a8 51 90 89 a8 83 df
e1 5a e5 9f 06 92 8b 66 5e 80 7b 55 25 64 01 4c 3b fe cf 49 2a 03
81 85 00 02 81 81 00 83 ea 93 df e3 b8 ea c4 97 34 e0 17 c4 16 75
14 04 4e c4 e8 3e 58 4e 19 ca 49 7f 59 39 90 b4 43 14 43 99 07 53
62 72 a3 b0 ca e4 0b d4 23 28 3f 1b f6 94 a7 e2 54 b4 d5 d8 28 6f
2e 37 3c a0 c6 0d a8 a2 dd 02 1f b3 5d dc 8f b3 73 43 f8 12 47 59
5b d6 f6 4c 48 7d 50 69 c9 b8 f6 58 cd 92 2f 7e de 48 95 df c0 69
5e 30 cb 8b b8 26 74 44 92 17 b7 a6 3b 96 9b d6 07 34 8a 5f d3 68
1f e6 6e
Applied Cryptography
48
Working With DSA
Verifying
• We want to verify the signature on an Ascii or
binary file
• Read the public key of the signer
• Read the signature
• Read the file and verify that the signature was created
by the holder of the associated private key and that
the file was not altered
Applied Cryptography
49
// VerifyFile.java from “Java 2 Network Security” IBM
import java.io.*;
import java.security.*;
import java.security.spec.*;
class VerifyFile
{
public static void main(String args[])
{
if (args.length != 3)
System.out.println("Usage: java VerifyFile DATAFILE” +
“SIGNATUREFILE PUBLICKEYFILE");
else
try
{
FileInputStream fis = new FileInputStream(args[0]);
FileInputStream sfis = Applied
new Cryptography
FileInputStream(args[1]);
50
FileInputStream pfis = new FileInputStream(args[2]);
//Get the public key of the sender
byte[] encKey = new byte[pfis.available()];
pfis.read(encKey);
pfis.close();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec
(encKey);
KeyFactory KeyFac = KeyFactory.getInstance("DSA", "SUN");
PublicKey pubkey = KeyFac.generatePublic(pubKeySpec);
// Get the signature on the file - This will be verified
byte[] sigToVerify = new byte[sfis.available()];
sfis.read(sigToVerify);
sfis.close();
Applied Cryptography
51
// Initialize the signature - update() method used to update the
// data to be verified
Signature dsasig = Signature.getInstance("SHA1withDSA", "SUN");
dsasig.initVerify(pubkey);
BufferedInputStream buf = new BufferedInputStream(fis);
byte[] buff = new byte[1024];
int len;
while(buf.available() != 0)
{
len = buf.read(buff);
dsasig.update(buff, 0, len);
}
buf.close();
fis.close();
Applied Cryptography
52
// Verify the signature
boolean verifies = dsasig.verify(sigToVerify);
if (verifies)
System.out.println("Verified: “+
“The signature on the file is correct.");
else
System.out.println("Warning:”+
“The signature on the file has been tampered with.");
}
catch (Exception e)
{
System.out.println("Caught Exception: " + e);
}
}
}
Applied Cryptography
53
D:\McCarthy\www\95-804\signfile>java VerifyFile SignFile.java
SignatureFile.txt PublicKeyFile.txt
Verified: The signature on the file is correct.
Applied Cryptography
54
Password Based Encryption
Plaintext
Ciphertext
PBE Cipher
Password
Base 64 encoded
New Salt
Base 64 Encoded
salt
From "Java Security" by Garms and
SomerField
Cipher text
55
PBE Decryption
Plaintext
Base 64 Decode
Ciphertext
salt
Cipher text
PBE Cipher
Base 64 Decode
Salt
Password
From "Java Security" by Garms and
SomerField
56
Output First
java PBE -e sesame "This text needs to be private"
KXz4XlJdrac=Ldj2ZNxBr9In4AZH4H3V7Gq1loENqntj3Dw8o/jgjDI=
java PBE -d sesame
KXz4XlJdrac=Ldj2ZNxBr9In4AZH4H3V7Gq1loENqntj3Dw8o/jgjDI=
This text needs to be private
Applied Cryptography
57
PBE Example
// From "Professional Java Security" by Garms and Somerfield
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;
import sun.misc.*;
// For Base 64
public class PBE {
// Name the algorithm
private static String algorithm = "PBEWithMD5AndDES";
// hash the password 1000 times, making it harder for Eve
private static int ITERATIONS = 1000;
58
private static void usage() {
System.out.println("Usage: java PBE -e|-d password text");
System.exit(1);
}
public static void main(String args[]) throws Exception {
if(args.length != 3) usage();
char[] password = args[1].toCharArray();
String text = args[2];
String output = null;
// are we decrypting or encrypting
if("-e".equals(args[0])) output = encrypt(password,text);
else
if("-d".equals(args[0])) output = decrypt (password, text);
else usage();
System.out.println(output);
Applied Cryptography
}
59
private static String encrypt(char [] password, String plainText)
throws Exception {
// create a random salt of 64 bits
byte[] salt = new byte[8];
Random random = new Random();
random.nextBytes(salt);
// create the PBEKeyspec with the password
PBEKeySpec keySpec = new PBEKeySpec(password);
// get secret key factory based on selected algorithm
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance(algorithm);
// get a secret key
SecretKey key = keyFactory.generateSecret(keySpec);
Applied Cryptography
60
// create a parameter spec holding salt and iteration count
PBEParameterSpec paramSpec =
new PBEParameterSpec(salt,ITERATIONS)
// prepare a cipher for encrypting
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
// encrypt
byte [] cipherText = cipher.doFinal(plainText.getBytes());
// convert the salt and the encrypted bytes to Base 64
BASE64Encoder encoder = new BASE64Encoder();
String saltString = encoder.encode(salt);
String cipherTextString = encoder.encode(cipherText);
return saltString + cipherTextString;
}
Applied Cryptography
61
private static String decrypt(char[] password, String text)
throws Exception {
// split the text into salt and cipherText strings
String salt = text.substring(0,12);
String cipherText = text.substring(12, text.length());
// Base 64 decode
BASE64Decoder decoder = new BASE64Decoder();
byte[] saltArray = decoder.decodeBuffer(salt);
byte[] cipherTextArray = decoder.decodeBuffer(cipherText);
// Build PBEKeySpec based on the password
PBEKeySpec keySpec = new PBEKeySpec(password);
// get key factory based on selected algorithm
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance(algorithm);
Applied Cryptography
62
// create the key
SecretKey key = keyFactory.generateSecret(keySpec);
// Create a parameter spec for the salt and iterations
PBEParameterSpec paramSpec =
new PBEParameterSpec(saltArray, ITERATIONS);
// get a cipher for decryption
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
// decrypt
byte[] plainTextArray = cipher.doFinal(cipherTextArray);
return new String(plainTextArray);
}
}
Applied Cryptography
63
Session Key Example
Use an RSA public key to encrypt a blowfish key
In order to run the following program you must download
JCE with provider and lightweight API from
www.bouncycastle.org
Place the downloaded Jar file in all of the many /jre/lib/ext directories
on your computer.
And add the following line to all
/jre/lib/security/java.security files on your computer.
security.provider.6=org.bouncycastle.jce.provider.BouncyCastleProvider
Applied Cryptography
64
Output First
java SimpleRSAExample
Generating a symmetric Blowfish key
Generating an RSA Key pair
Building a cipher based on the public key
About to encrypt the symmetric key
Decrypt the symmetric key
Applied Cryptography
65
Session Key Encryption
// From "Professional Java Security" by Garms and Somerfield
// Session Key encryption
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;
import sun.misc.*;
Applied Cryptography
66
public class SimpleRSAExample {
public static void main(String args[]) throws Exception {
System.out.println("Generating a symmetric Blowfish key");
KeyGenerator keyGenerator = KeyGenerator.getInstance
("Blowfish");
keyGenerator.init(128);
Key blowFishKey = keyGenerator.generateKey();
System.out.println("Generating an RSA Key pair");
KeyPairGenerator keyPairGenerator =
KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
67
KeyPair keyPair = keyPairGenerator.genKeyPair();
System.out.println("Building a cipher based on the public key");
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
System.out.println("About to encrypt the symmetric key");
byte blowFishKeyBytes[] = blowFishKey.getEncoded();
byte cipherText[] = cipher.doFinal(blowFishKeyBytes);
System.out.println("Decrypt the symmetric key");
cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
byte decryptedKeyBytes[] = cipher.doFinal(cipherText);
SecretKey theBlowFishKey = new SecretKeySpec
(decryptedKeyBytes, "Blowfish");
}
}
Applied Cryptography
68
Reading Certificates
• X.509 certificates are the most widely used
• The JDK uses X.509 certificates by default
• Contains Version, Serial Number, Signature
Algorithm, Validity, Subject (X.500 names
– CN, OU, O, …), Subject’s Public Key,
and Signature
• Three versions X.509v1, v2, v3
Applied Cryptography
69
Reading Certificates
(1) Create a certificate using keytool
(2) Use Java classes to read the data
Applied Cryptography
70
Use Keytool to Create Keys
keytool -genkey -alias mjm -keyalg DSA -keystore coolkeys
Enter keystore password: sesame
What is your first and last name?
[Unknown]: Mike McCarthy
What is the name of your organizational unit?
[Unknown]: Heinz School
What is the name of your organization?
[Unknown]: CMU
What is the name of your City or Locality?
[Unknown]: Pgh
Applied Cryptography
71
What is the name of your State or Province?
[Unknown]: PA
What is the two-letter country code for this unit?
[Unknown]: US
Is CN=Mike McCarthy, OU=Heinz School, O=CMU,
L=Pgh, ST=PA, C=US correct?
[no]: yes
Enter key password for <mjm>
(RETURN if same as keystore password):
04/20/2003 09:59 PM
1,238 coolkeys
Applied Cryptography
72
Use keytool to look at coolkeys
keytool -v -list -keystore coolkeys
Enter keystore password: sesame
Keystore type: jks
Keystore provider: SUN
Your keystore contains 1 entry
Alias name: mjm
Creation date: Apr 20, 2003
Entry type: keyEntry
Certificate chain length: 1
Certificate[1]:
Applied Cryptography
73
Owner: CN=Mike McCarthy, OU=Heinz School, O=CMU,
L=Pgh, ST=PA, C=US
Issuer: CN=Mike McCarthy, OU=Heinz School, O=CMU,
L=Pgh, ST=PA, C=US
Serial number: 3ea35081
Valid from: Sun Apr 20 21:59:29 EDT 2003 until: Sat Jul 19
21:59:29 EDT 2003
Certificate fingerprints:
MD5: B6:D0:89:2C:4F:AB:A6:3C:2C:5F:D6:2E:73:F5:E6:96
SHA1:
E3:44:06:1A:19:6B:D6:27:DB:24:AA:7C:79:D2:9D:F5:92:3C
:71:5B
Applied Cryptography
74
Use keytool to create a certificate
keytool -export -alias mjm -keystore
coolkeys -file cool.cer
Enter keystore password: sesame
Certificate stored in file <cool.cer>
Applied Cryptography
75
Use keytool to look at the certificate
keytool -printcert -v -file cool.cer
Owner: CN=Mike McCarthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA,
C=US
Issuer: CN=Mike McCarthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA,
C=US
Serial number: 3ea35081
Valid from: Sun Apr 20 21:59:29 EDT 2003 until: Sat Jul 19 21:59:29 EDT
2003
Certificate fingerprints:
MD5: B6:D0:89:2C:4F:AB:A6:3C:2C:5F:D6:2E:73:F5:E6:96
SHA1:
E3:44:06:1A:19:6B:D6:27:DB:24:AA:7C:79:D2:9D:F5:92:3C:71:5B
Applied Cryptography
76
A Java Program to read the
certificate
from
cool.cer
// Reading Certificate data from a certificate file
// Adapted from Professional Java Security, Garms and Somerfield
import java.io.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
public class PrintCertInfo {
public static void main(String args[]) throws Exception {
// create a factory to handle X.509
CertificateFactory certFactory =
CertificateFactory.getInstance("X.509");
Applied Cryptography
77
// open an existing certificate file
FileInputStream fis = new FileInputStream(args[0]);
// Tell the factory about the file and retrieve a
// certificate
Certificate cert = certFactory.generateCertificate(fis);
// close the file
fis.close();
// call the certificate's toString
System.out.println(cert);
}
}
Applied Cryptography
78
java PrintCertInfo cool.cer
[
[
Version: V1
Subject: CN=Mike McCarthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US
Signature Algorithm: SHA1withDSA, OID = 1.2.840.10040.4.3
Key: Sun DSA Public Key
Parameters:DSA
p:
fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80
b6512669455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b
801d346f f26660b76b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6
1bf83b57 e7c6a8a6 150f04fb83f6d3c5 1ec30235 54135a16 9132f675
f3ae2b61 d72aeff2 2203199d d14801c7
q:
9760508f 15230bcc b292b982 a2eb840b f0581cf5
g:
f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267
5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1
3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b
cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a
Applied Cryptography
79
y:
aac3eb5c 6371449a 9ef90719 5d911014 ecd65e5a e959d9ff 5799edd3 a63a8dd2
36785e2a c0b4275b a17e9b50 efeb1c4e 6ea47846 872db0d6 3db1619d 6ed31f67
5ef9f1e4 f94491e3 47ed9cdb a7ffe054 ab2a2b45 9ecee6a1 2b75bd79 ff603f9a
35f40f83 3f235573 b489fab8 d2974004 45b00a44 d55a6348 d6d3df43 7f41e954
Validity: [From: Sun Apr 20 21:59:29 EDT 2003,
To: Sat Jul 19 21:59:29 EDT 2003]
Issuer: CN=Mike McCarthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US
SerialNumber: [ 3ea35081]
]
Algorithm: [SHA1withDSA]
Signature:
0000: 30 2C 02 14 7B 9C 92 2D AE B8 CE A2 72 0A 40 72
0010: C7 79 23 76 6D 7D 9F 86 02 14 3B 82 C1 6D 12 B8
0020: 6A 7C 6B 34 20 0A 92 A6 DA 37 76 34 57 F2
0,.....-....r.@r
.y#vm.....;..m..
j.k4 ....7v4W.
]
Applied Cryptography
80
A Java Program to read the
certificate from coolkeys
import java.io.*;
import java.security.cert.CertificateFactory;
import java.security.cert.Certificate;
import java.security.KeyStore;
// Code adapted from Professional Java Security, by Garms and Somerfield
public class PrintCertFromKeyStore {
public static void main(String args[]) throws Exception {
if(args.length != 3) {
System.err.println("Usage: java PrintCertInfo keystore alias password");
System.exit(1);
}
Applied Cryptography
81
String keyFileName = args[0];
String alias = args[1];
char[] passWord = args[2].toCharArray();
FileInputStream fis = new FileInputStream(keyFileName);
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(fis, passWord);
// Get a Certificate object
Certificate cert = keyStore.getCertificate(alias);
// Call cert's toString
System.out.println(cert);
}
}
Applied Cryptography
82
java PrintCertFromKeyStore coolkeys mjm sesame
[
[
Version: V1
Subject: CN=Mike McCarthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US
Signature Algorithm: SHA1withDSA, OID = 1.2.840.10040.4.3
Key: Sun DSA Public Key
Parameters:DSA
p:
fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80
b6512669455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b
801d346f f26660b76b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6
1bf83b57 e7c6a8a6 150f04fb83f6d3c5 1ec30235 54135a16 9132f675
f3ae2b61 d72aeff2 2203199d d14801c7
q:
9760508f 15230bcc b292b982 a2eb840b f0581cf5
g:
f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b
3d0782675159578e bad4594f e6710710 8180b449 167123e8 4c281613
b7cf0932 8cc8a6e13c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f
0bfa2135 62f1fb62 7a01243bcca4f1be a8519089 a883dfe1 5ae59f06
928b665e 807b5525 64014c3b fecf492a
Applied Cryptography
83
y:
aac3eb5c 6371449a 9ef90719 5d911014 ecd65e5a e959d9ff 5799edd3 a63a8dd2
36785e2a c0b4275b a17e9b50 efeb1c4e 6ea47846 872db0d6 3db1619d 6ed31f67
5ef9f1e4 f94491e3 47ed9cdb a7ffe054 ab2a2b45 9ecee6a1 2b75bd79 ff603f9a
35f40f83 3f235573 b489fab8 d2974004 45b00a44 d55a6348 d6d3df43 7f41e954
Validity: [From: Sun Apr 20 21:59:29 EDT 2003,
To: Sat Jul 19 21:59:29 EDT 2003]
Issuer: CN=Mike McCarthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US
SerialNumber: [ 3ea35081]
]
Algorithm: [SHA1withDSA]
Signature:
0000: 30 2C 02 14 7B 9C 92 2D AE B8 CE A2 72 0A 40 72 0,.....-....r.@r
0010: C7 79 23 76 6D 7D 9F 86 02 14 3B 82 C1 6D 12 B8 .y#vm.....;..m..
0020: 6A 7C 6B 34 20 0A 92 A6 DA 37 76 34 57 F2
j.k4 ....7v4W.
]
Applied Cryptography
84
Diffie-Hellman Key Exchange
// Diffie-Hellman : Example modified from "Java Security" by Oaks
/* From RSA Inc.
P and G are public and may be used by all users.
P is a prime and G is a generator. G is an integer less than P
with the following property: for every n between 1 and P - 1
inclusive, there is a k such that n = G^k mod P.
Alice generates a random private value a and Bob generates a
random private value b.
Alice's public value = G^a mod P.
Bob's public value = G^b mod P.
Alice computes k = G^a^b mod P.
Bob computes k' = G^b^a mod P.
Each knows k = k'.
Assumption: It is hard to compute G^a^b mod P given G^a mod P and G^b mod P.
*/
Applied Cryptography
85
import java.math.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
public class DHAgreement implements Runnable {
byte bob[];
byte alice[];
boolean doneAlice = false;
byte cipherText[];
Applied Cryptography
86
BigInteger aliceP; // Prime
BigInteger aliceG; // Generator
int aliceL;
// Length in bits of private value
public synchronized void run() {
if(!doneAlice) {
doneAlice = true;
doAlice();
}
else doBob();
}
Applied Cryptography
87
public synchronized void doAlice() {
try {
// Create a pair of keys for Alice
KeyPairGenerator kpg =
KeyPairGenerator.getInstance("DH");
kpg.initialize(512); // may be set to 1024 but DH Key
// construction is costly
KeyPair kp = kpg.generateKeyPair();
DHParameterSpec dhSpec =
((DHPublicKey) kp.getPublic()).getParams();
aliceG = dhSpec.getG();
aliceP = dhSpec.getP();
aliceL = dhSpec.getL();
alice = kp.getPublic().getEncoded();
Applied Cryptography
88
// tell at most one thread waiting for a condition to change
notify();
KeyAgreement ka = KeyAgreement.getInstance("DH");
ka.init(kp.getPrivate());
while(bob == null) {
wait(); // wait for notification
}
KeyFactory kf = KeyFactory.getInstance("DH");
X509EncodedKeySpec x509Spec = new
X509EncodedKeySpec(bob);
PublicKey pk = kf.generatePublic(x509Spec);
ka.doPhase(pk,true);
Applied Cryptography
89
byte secret[] = ka.generateSecret();
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
DESKeySpec desSpec = new DESKeySpec(secret);
SecretKey key = skf.generateSecret(desSpec);
Cipher c = Cipher.getInstance("DES/ECB/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE,key);
cipherText = c.doFinal("Attack at dawn!".getBytes());
notify();
}
catch (Exception e) {
e.printStackTrace();
}
}
Applied Cryptography
90
public synchronized void doBob() {
try {
while(alice == null) {
wait();
}
KeyPairGenerator kpg =
KeyPairGenerator.getInstance("DH");
DHParameterSpec dhSpec =
new DHParameterSpec(aliceP, aliceG, aliceL);
kpg.initialize(dhSpec);
KeyPair kp = kpg.generateKeyPair();
bob = kp.getPublic().getEncoded();
// tell at most one thread waiting for a condition to change
notify();
Applied Cryptography
91
KeyAgreement ka = KeyAgreement.getInstance("DH");
ka.init(kp.getPrivate());
KeyFactory kf = KeyFactory.getInstance("DH");
X509EncodedKeySpec x509Spec =
new X509EncodedKeySpec(alice);
PublicKey pk = kf.generatePublic(x509Spec);
ka.doPhase(pk,true);
byte secret[] = ka.generateSecret();
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES")
DESKeySpec desSpec = new DESKeySpec(secret);
SecretKey key = skf.generateSecret(desSpec);
Applied Cryptography
92
Cipher c = Cipher.getInstance("DES/ECB/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE,key);
while(cipherText == null) {
wait();
}
byte plainText[] = c.doFinal(cipherText);
System.out.println("Bob received : " + new String(plainText));
}
catch (Exception e) {
e.printStackTrace();
}
}
Applied Cryptography
93
public static void main(String args[]) {
DHAgreement demo = new DHAgreement();
new Thread(demo).start();
new Thread(demo).start();
}
}
Applied Cryptography
94
Related documents