Скачать презентацию Applied Cryptography Week 3 Java Tools Michael Mc Скачать презентацию Applied Cryptography Week 3 Java Tools Michael Mc

a7abfa0045591cebe59485515590f8ea.ppt

  • Количество слайдов: 94

Applied Cryptography Week 3 Java Tools Michael Mc. Carthy Applied Cryptography 1 Applied Cryptography Week 3 Java Tools Michael Mc. Carthy Applied Cryptography 1

Java Tools • Security Provider Architecture • Example Programs Message Digests Symmetric Encryption Digital 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 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 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 Message. Digest Signature Key. Factory Key. Pair. Generator Secure. Random A Example Engine Classes Message. Digest Signature Key. Factory Key. Pair. Generator Secure. Random A program may simply request a particular engine (such as a Message. Digest 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 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 (MD 5, SHA 1). Different providers will implement MD 5 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 SUNRSAS 16 N 1. 3 Java. Security Engine Class Provider Class SUNJSSE Application Programmer SUNRSAS 16 N 1. 3 Java. Security Engine Class Provider Class Security Class Algorithm Class Message Digest SUN Asks providers if they can handle a Message. Digest. MD 5 From same vendor Provider “Message. Digest. MDS” engine algorithm Key. Pair. Generator. DSA Holds a list of providers SUNJCE From same vendor Security Provider SSI. Pro 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. 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. Sun. JCE security. provider. 5=sun. security. jgss. Sun. Provider Applied Cryptography 8

Looking at Providers // Page 161 of Looking at Providers // Page 161 of "Java Security" Oaks import java. security. *; import java. util. *; public class Examine. Security { public static void main(String args[]) { Applied Cryptography 9

try { Provider p[] = Security. get. Providers(); for(int i = 0; i < try { Provider p[] = Security. get. Providers(); for(int i = 0; i < p. length; i++) { System. out. println(p[i]); for(Enumeration e = p[i]. keys(); e. has. More. Elements(); ) System. out. println("t" + e. next. Element()); } } catch(Exception e) { System. out. println(e); } } } Applied Cryptography 10

java Examine. Security Providers SUN version 1. 2 Signature. SHA 1 with. DSA Key. java Examine. Security Providers SUN version 1. 2 Signature. SHA 1 with. DSA Key. Size Signature. SHA 1 with. DSA Implemented. In Certificate. Factory. X 509 Implemented. In Algorithm. Parameter. Generator. DSA Alg. Alias. Signature. SHA/DSA Pages deleted … Sun. JSSE version 1. 4 SSLContext. SSL Key. Manager. Factory. Sun. X 509 Signature. MD 5 with. RSA Signature. SHA 1 with. RSA Key. Factory. RSA Applied Cryptography Engine, Algorithm provided 11

Sun. Rsa. Sign version 1. 0 Key. Factory. RSA Signature. MD 5 with. RSA Sun. Rsa. Sign version 1. 0 Key. Factory. RSA Signature. MD 5 with. RSA Signature. SHA 1 with. RSA Signature. MD 2 with. RSA Key. Pair. Generator. RSA Many deletions Bouncy. Castle added later Sun. JCE version 1. 4 Cipher. DES Key. Store. JCEKS Alg. Alias. Secret. Key. Factory. Triple. DES Secret. Key. Factory. DES Sun. JGSS version 1. 0 Applied Cryptography 12

Message. Digest is an Engine import java. security. Message. Digest; import java. security. No. Message. Digest is an Engine import java. security. Message. Digest; import java. security. No. Such. Algorithm. Exception; public class Compute. AMessage. Digest { public static void main(String args[]) { Message. Digest sha=null; try { // engine algorithm sha = Message. Digest. get. Instance("SHA-1"); } catch(No. Such. Algorithm. Exception e) { System. out. println("No such algorithm"); Applied Cryptography } 13

System. out. println(sha. get. Algorithm()); String s = System. out. println(sha. get. Algorithm()); String s = "Applied Cryptography"; byte a[] = s. get. Bytes(); 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 Compute. AMessage. Digest SHA-1 The hash value of ‘Applied Cryptography’ is -57 -97 java Compute. AMessage. Digest SHA-1 The hash value of ‘Applied Cryptography’ is -57 -97 -73 -64 -13 87 -8 2 -45 44 -16 65 -77 -36 -27 65 51 -109 – 104 Add a period… java Compute. AMessage. Digest 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. Message. Digest; import java. security. No. We Can Choose an Algorithm import java. security. Message. Digest; import java. security. No. Such. Algorithm. Exception; public class Compute. AMessage. Digest { public static void main(String args[]) { Message. Digest sha=null; try { // engine algorithm sha = Message. Digest. get. Instance("MD 5"); } catch(No. Such. Algorithm. Exception e) { System. out. println("No such algorithm"); } Applied Cryptography 16

System. out. println(sha. get. Algorithm()); String s =

java Compute. AMessage. Digest MD 5 The hash value of 'Applied Cryptography. ' is java Compute. AMessage. Digest MD 5 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. No. Such. Algorithm. Exception; import java. We Can Choose a Provider import java. security. No. Such. Algorithm. Exception; import java. security. No. Such. Provider. Exception; import java. security. Secure. Random; public class Compute. Secure. Random { public static void main(String args[]) { Secure. Random random = null; try { // Secure Hash Algorithm Pseudo Rand Num Gen random = Secure. Random. get. Instance("SHA 1 PRNG", "SUN"); } Applied Cryptography 19

catch(No. Such. Algorithm. Exception e) { System. out. println( catch(No. Such. Algorithm. Exception e) { System. out. println("No such algorithm"); } catch(No. Such. Provider. Exception e) { System. out. println("No such provider"); } byte[] my. Random. Bytes = new byte[10]; // may be any size random. next. Bytes(my. Random. Bytes); System. out. println("The random bytes are "); for(int i = 0; i < my. Random. Bytes. length; i++) { System. out. print(my. Random. Bytes[i]+ " "); } } } Applied Cryptography 20

Writing Your Own Security Provider You must extend the SPI (Security Provider Interface) of 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 A Simple Provider import java. security. Provider; public class XYZProvider extends Provider { public XYZProvider() { super("XYZCool. Provider", 1. 0, "XYZ Security Provider"); // (Engine name, Algorithm name)--> class put("Key. Pair. Generator. XYZ", "XYZKey. Pair. Generator"); } } Applied Cryptography 22

A Simple Class to Hold a Key // A class to hold key data 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, Public. Key, Private. Key { private int rot. Value; // required for Key (Public. Key and Private. Key are markers) public String get. Algorithm() { return "XYZ"; } Applied Cryptography 23

// required for Key public String get. Format() { return // required for Key public String get. Format() { return "XYZ Special Format"; } public void set. Rot. Value(int i) { rot. Value = i; } public int get. Rot. Value() { return rot. Value; } // required for Key public byte[] get. Encoded() { byte b[] = new byte[4]; b[3] = (byte)((rot. Value >> 24) & 0 xff); b[2] = (byte)((rot. Value >> 16) & 0 xff); b[1] = (byte)((rot. Value >> 8) & 0 xff); b[0] = (byte)((rot. Value >> 0) & 0 xff); return b; } } Applied Cryptography 24

A Key. Pair. Generator is an Engine // From Oaks page 176 with modifications A Key. Pair. Generator is an Engine // From Oaks page 176 with modifications import java. security. Key. Pair. Generator; import java. security. Secure. Random; import java. security. Security; import java. security. Key. Pair; import java. security. No. Such. Algorithm. Exception; import java. security. No. Such. Provider. Exception; import java. security. Private. Key; import java. security. Public. Key; Applied Cryptography 25

public class XYZKey. Pair. Generator extends Key. Pair. Generator { Secure. Random random; public public class XYZKey. Pair. Generator extends Key. Pair. Generator { Secure. Random random; public XYZKey. Pair. Generator() { super("XYZ"); } public void initialize(int strength, Secure. Random sr) { System. out. println("Running initialize"); random = sr; } Applied Cryptography 26

public Key. Pair generate. Key. Pair() { int r = random. next. Int() % public Key. Pair generate. Key. Pair() { int r = random. next. Int() % 25; XYZKey pub = new XYZKey(); XYZKey priv = new XYZKey(); pub. set. Rot. Value(r); priv. set. Rot. Value(-r); Key. Pair kp = new Key. Pair(pub, priv); return kp; } Applied Cryptography 27

public static void main(String args[]) throws No. Such. Algorithm. Exception, No. Such. Provider. Exception public static void main(String args[]) throws No. Such. Algorithm. Exception, No. Such. Provider. Exception { // add a new Provider to the Security class // the new Provider is called XYZCool. Provider and it maps the engine, // algorithm // pair "Key. Pair. Generator. XYZ" to the class "XYZKey. Pair. Generator" Security. add. Provider(new XYZProvider()); // At this point Security knows about the mapping // Try to get an instance of an XYZKey. Pair. Generator // by requesting from Security a Key. Pair. Generator with algorithm XYZ // and provider XYZCool. Provider – provider name is optional Key. Pair. Generator kpg = Key. Pair. Generator. get. Instance("XYZ", "XYZCool. Provider"); 28

// All Key. Pair generators can be initialized kpg. initialize(0, new Secure. Random()); // // All Key. Pair generators can be initialized kpg. initialize(0, new Secure. Random()); // get a Key. Pair kp = kpg. generate. Key. Pair(); System. out. println("Got key pair "); Private. Key priv. K = kp. get. Private(); Public. Key pub. K = kp. get. Public(); System. out. println("Algorithm = " + pub. K. get. Algorithm()); } } Applied Cryptography 29

java XYZKey. Pair. Generator Running initialize Got key pair Algorithm = XYZ Applied Cryptography java XYZKey. Pair. Generator Running initialize Got key pair Algorithm = XYZ Applied Cryptography 30

Symmetric Encryption Example java Working. With. Blowfish ABCDEFG as bytes 41 42 43 44 Symmetric Encryption Example java Working. With. Blowfish ABCDEFG as bytes 41 42 43 44 45 46 47 Cipher text as bytes 9 e dd 46 30 b 1 14 79 6 b After decryption ABCDEFG Applied Cryptography 31

Working. With. Blow. Fish. java import java. security. *; import javax. crypto. Key. Generator; Working. With. Blow. Fish. java import java. security. *; import javax. crypto. Key. Generator; import javax. crypto. Cipher; public class Working. With. Blowfish { public static void main(String args[])throws Exception { String clear = "ABCDEFG"; System. out. println(clear + " as bytes " ); display. Bytes(clear. get. Bytes()); 32

// Build a key from scratch // Symmetric keys come from the Key. Generator // Build a key from scratch // Symmetric keys come from the Key. Generator engine // Asymmetric keys come from the Key. Pair. Generator engine Key. Generator kg = Key. Generator. get. Instance("Blowfish"); kg. init(128); // key size // create the key data Key k = kg. generate. Key(); // We need a Blowfish cipher based on that key // We specify the algorithm/mode/padding Cipher cipher = Cipher. get. Instance ("Blowfish/ECB/PKCS 5 Padding"); // initialize the ciper with the key cipher. init(Cipher. ENCRYPT_MODE, k); 33

// encrypt byte[] cipher. Text = cipher. do. Final(clear. get. Bytes()); System. out. println( // encrypt byte[] cipher. Text = cipher. do. Final(clear. get. Bytes()); System. out. println("Cipher text as bytes " ); display. Bytes(cipher. Text); // change to decrypt mode using the same key cipher. init(Cipher. DECRYPT_MODE, k); byte[] clear. Bytes = cipher. do. Final(cipher. Text); String result = new String(clear. Bytes); System. out. println("After decryption n" + result); } Applied Cryptography 34

// display a byte in hex public static void display. Bytes(byte [] b) { // display a byte in hex public static void display. Bytes(byte [] b) { for (int i = 0; i < b. length; i++) { byte a. Byte = b[i]; String hex. Lo = Integer. to. Hex. String( a. Byte & 0 x 0 F ); String hex. Hi = Integer. to. Hex. String( (a. Byte >> 4) & 0 x 0 F ); System. out. print(hex. Hi + hex. Lo + " "); } System. out. println(); } } Applied Cryptography 35

Algorithm/Mode/Padding ( Algorithm/Mode/Padding ("Blowfish/ECB/PKCS 5 Padding"); 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: HELLO 333 padding bytes always present HELLOJOE 8 88 888 Applied Cryptography 36

Algorithm/Mode/Padding ( Algorithm/Mode/Padding ("Blowfish/ECB/PKCS 5 Padding"); 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 ( Algorithm/Mode/Padding ("Blowfish/ECB/PKCS 5 Padding"); 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 ( Algorithm/Mode/Padding ("Blowfish/ECB/PKCS 5 Padding"); 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 Working With DSA Signing • We want to sign an Ascii or binary file • Use Key. Pair. Generator engine to create a DSA key • Use Signature engine based on SHA 1 with DSA to sign the file • Display and save the signature and public key Applied Cryptography 40

// Sign. File. java from IBM's // Sign. File. java from IBM's "Java 2 Network Security" 2 nd. Ed. import java. io. *; import java. security. *; class Sign. File { public static void main(String arg[]) { if (arg. length != 3) System. out. println( "Usage: java Sign. File DATAFILE”+ “SIGNATUREFILE PUBLICKEYFILE"); else Applied Cryptography 41

try { // We create the keypair – // Key strength can be 1024 try { // We create the keypair – // Key strength can be 1024 inside the United States Key. Pair. Generator KPG = Key. Pair. Generator. get. Instance ("DSA", "SUN"); Secure. Random r = new Secure. Random(); KPG. initialize(1024, r); Key. Pair KP = KPG. generate. Key. Pair(); // We get the generated keys Private. Key priv = KP. get. Private(); Public. Key publ = KP. get. Public(); // We intialize the signature Signature dsasig = Signature. get. Instance("SHA 1 with. DSA", "SUN" dsasig. init. Sign(priv); Applied Cryptography 42

// We get the file to be signed File. Input. Stream fis = new // We get the file to be signed File. Input. Stream fis = new File. Input. Stream(arg[0]); Buffered. Input. Stream bis = new Buffered. Input. Stream(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[] real. Signature = dsasig. sign(); // We write // We get the signature byte[] real. Signature = dsasig. sign(); // We write the signature to a file File. Output. Stream fos = new File. Output. Stream(arg[1]); fos. write(real. Signature); fos. close(); // Dsiplay the signature in hex System. out. println("The Signature of " + arg[0] + " in hexn"); display. Bytes(real. Signature); // We write the public key to a file byte[] pkey = publ. get. Encoded(); File. Output. Stream keyfos = new File. Output. Stream(arg[2]); keyfos. write(pkey); keyfos. close(); Applied Cryptography 44

// Display the public key in hex System. out. println( // Display the public key in hex System. out. println("The DSA public key in hexn"); display. Bytes(pkey); } catch (Exception e) { System. out. println("Caught Exception: " + e); } } Applied Cryptography 45

public static void display. Bytes(byte [] b) { for (int i = 0; i public static void display. Bytes(byte [] b) { for (int i = 0; i < b. length; i++) { byte a. Byte = b[i]; String hex. Lo = Integer. to. Hex. String( a. Byte & 0 x 0 F ); String hex. Hi = Integer. to. Hex. String( (a. Byte >> 4) & 0 x 0 F ); System. out. print(hex. Hi + hex. Lo + " "); } System. out. println(); } } Applied Cryptography 46

D: Mc. Carthywww95 -804signfile> java Sign. File. java Signature. File. txt Public. Key. File. D: Mc. Carthywww95 -804signfile> java Sign. File. java Signature. File. txt Public. Key. File. txt The Signature of Sign. File. java in hex 30 2 c 02 14 3 b 35 a 9 e 5 53 41 35 1 e 86 43 5 c 00 a 6 46 be 37 82 1 f fc fb 02 14 08 98 b 8 ab 8 d 64 af c 3 72 ae 84 fb 1 b 1 d ea cd e 4 d 0 eb 79 The DSA public key in hex 30 82 01 b 8 30 82 01 2 c 06 07 2 a 86 48 ce 38 04 01 30 82 01 1 f 02 81 81 00 fd 7 f 53 81 1 d 75 12 29 52 df 4 a 9 c 2 e ec e 4 e 7 f 6 11 b 7 52 3 c ef 44 00 c 3 1 e 3 f 80 b 6 51 26 69 45 5 d 40 22 51 fb 59 3 d 8 d 58 fa bf c 5 f 5 ba 30 f 6 cb 9 b 55 6 c d 7 81 3 b 80 1 d 34 6 f f 2 66 60 b 7 6 b 99 50 a 5 a 4 9 f 9 f e 8 04 7 b 10 22 c 2 4 f bb a 9 d 7 fe b 7 c 6 1 b f 8 Applied Cryptography 47

3 b 57 e 7 c 6 a 8 a 6 15 0 f 3 b 57 e 7 c 6 a 8 a 6 15 0 f 04 fb 83 f 6 d 3 c 5 1 e c 3 02 35 54 13 5 a 16 91 32 f 6 75 f 3 ae 2 b 61 d 7 2 a ef f 2 22 03 19 9 d d 1 48 01 c 7 02 15 00 97 60 50 8 f 15 23 0 b cc b 2 92 b 9 82 a 2 eb 84 0 b f 0 58 1 c f 5 02 81 81 00 f 7 e 1 a 0 85 d 6 9 b 3 d de cb bc ab 5 c 36 b 8 57 b 9 79 94 af bb fa 3 a ea 82 f 9 57 4 c 0 b 3 d 07 82 67 51 59 57 8 e ba d 4 59 4 f e 6 71 07 10 81 80 b 4 49 16 71 23 e 8 4 c 28 16 13 b 7 cf 09 32 8 c c 8 a 6 e 1 3 c 16 7 a 8 b 54 7 c 8 d 28 e 0 a 3 ae 1 e 2 b b 3 a 6 75 91 6 e a 3 7 f 0 b fa 21 35 62 f 1 fb 62 7 a 01 24 3 b cc a 4 f 1 be a 8 51 90 89 a 8 83 df e 1 5 a e 5 9 f 06 92 8 b 66 5 e 80 7 b 55 25 64 01 4 c 3 b fe cf 49 2 a 03 81 85 00 02 81 81 00 83 ea 93 df e 3 b 8 ea c 4 97 34 e 0 17 c 4 16 75 14 04 4 e c 4 e 8 3 e 58 4 e 19 ca 49 7 f 59 39 90 b 4 43 14 43 99 07 53 62 72 a 3 b 0 ca e 4 0 b d 4 23 28 3 f 1 b f 6 94 a 7 e 2 54 b 4 d 5 d 8 28 6 f 2 e 37 3 c a 0 c 6 0 d a 8 a 2 dd 02 1 f b 3 5 d dc 8 f b 3 73 43 f 8 12 47 59 5 b d 6 f 6 4 c 48 7 d 50 69 c 9 b 8 f 6 58 cd 92 2 f 7 e de 48 95 df c 0 69 5 e 30 cb 8 b b 8 26 74 44 92 17 b 7 a 6 3 b 96 9 b d 6 07 34 8 a 5 f d 3 68 1 f e 6 6 e Applied Cryptography 48

Working With DSA Verifying • We want to verify the signature on an Ascii 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

// Verify. File. java from “Java 2 Network Security” IBM import java. io. *; // Verify. File. java from “Java 2 Network Security” IBM import java. io. *; import java. security. spec. *; class Verify. File { public static void main(String args[]) { if (args. length != 3) System. out. println("Usage: java Verify. File DATAFILE” + “SIGNATUREFILE PUBLICKEYFILE"); else try { File. Input. Stream fis = new File. Input. Stream(args[0]); File. Input. Stream sfis = Applied Cryptography new File. Input. Stream(args[1]); 50 File. Input. Stream pfis = new File. Input. Stream(args[2]);

//Get the public key of the sender byte[] enc. Key = new byte[pfis. available()]; //Get the public key of the sender byte[] enc. Key = new byte[pfis. available()]; pfis. read(enc. Key); pfis. close(); X 509 Encoded. Key. Spec pub. Key. Spec = new X 509 Encoded. Key. Spec (enc. Key); Key. Factory Key. Fac = Key. Factory. get. Instance("DSA", "SUN"); Public. Key pubkey = Key. Fac. generate. Public(pub. Key. Spec); // Get the signature on the file - This will be verified byte[] sig. To. Verify = new byte[sfis. available()]; sfis. read(sig. To. Verify); sfis. close(); Applied Cryptography 51

// Initialize the signature - update() method used to update the // data to // Initialize the signature - update() method used to update the // data to be verified Signature dsasig = Signature. get. Instance("SHA 1 with. DSA", "SUN"); dsasig. init. Verify(pubkey); Buffered. Input. Stream buf = new Buffered. Input. Stream(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(sig. To. Verify); if (verifies) System. // Verify the signature boolean verifies = dsasig. verify(sig. To. Verify); 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: Mc. Carthywww95 -804signfile>java Verify. File Sign. File. java Signature. File. txt Public. Key. D: Mc. Carthywww95 -804signfile>java Verify. File Sign. File. java Signature. File. txt Public. Key. File. 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 Password Based Encryption Plaintext Ciphertext PBE Cipher Password Base 64 encoded New Salt Base 64 Encoded salt From "Java Security" by Garms and Somer. Field Cipher text 55

PBE Decryption Base 64 Decode salt Ciphertext Plaintext Cipher text PBE Cipher Base 64 PBE Decryption Base 64 Decode salt Ciphertext Plaintext Cipher text PBE Cipher Base 64 Decode Salt Password From "Java Security" by Garms and Somer. Field 56

Output First java PBE -e sesame Output First java PBE -e sesame "This text needs to be private" KXz 4 Xl. Jdrac=Ldj 2 ZNx. Br 9 In 4 AZH 4 H 3 V 7 Gq 1 lo. ENqntj 3 Dw 8 o/jgj. DI= java PBE -d sesame KXz 4 Xl. Jdrac=Ldj 2 ZNx. Br 9 In 4 AZH 4 H 3 V 7 Gq 1 lo. ENqntj 3 Dw 8 o/jgj. DI= This text needs to be private Applied Cryptography 57

PBE Example // From PBE Example // From "Professional Java Security" by Garms and Somerfield import java. security. *; import javax. crypto. spec. *; import java. util. *; import sun. misc. *; // For Base 64 public class PBE { // Name the algorithm private static String algorithm = "PBEWith. MD 5 And. DES"; // hash the password 1000 times, making it harder for Eve private static int ITERATIONS = 1000; 58

private static void usage() { System. out. println( 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]. to. Char. Array(); 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); Cryptography Applied } 59

private static String encrypt(char [] password, String plain. Text) throws Exception { // create private static String encrypt(char [] password, String plain. Text) throws Exception { // create a random salt of 64 bits byte[] salt = new byte[8]; Random random = new Random(); random. next. Bytes(salt); // create the PBEKeyspec with the password PBEKey. Spec key. Spec = new PBEKey. Spec(password); // get secret key factory based on selected algorithm Secret. Key. Factory key. Factory = Secret. Key. Factory. get. Instance(algorithm); // get a secret key Secret. Key key = key. Factory. generate. Secret(key. Spec); Applied Cryptography 60

// create a parameter spec holding salt and iteration count PBEParameter. Spec param. Spec // create a parameter spec holding salt and iteration count PBEParameter. Spec param. Spec = new PBEParameter. Spec(salt, ITERATIONS) // prepare a cipher for encrypting Cipher cipher = Cipher. get. Instance(algorithm); cipher. init(Cipher. ENCRYPT_MODE, key, param. Spec); // encrypt byte [] cipher. Text = cipher. do. Final(plain. Text. get. Bytes()); // convert the salt and the encrypted bytes to Base 64 BASE 64 Encoder encoder = new BASE 64 Encoder(); String salt. String = encoder. encode(salt); String cipher. Text. String = encoder. encode(cipher. Text); return salt. String + cipher. Text. String; } Applied Cryptography 61

private static String decrypt(char[] password, String text) throws Exception { // split the text private static String decrypt(char[] password, String text) throws Exception { // split the text into salt and cipher. Text strings String salt = text. substring(0, 12); String cipher. Text = text. substring(12, text. length()); // Base 64 decode BASE 64 Decoder decoder = new BASE 64 Decoder(); byte[] salt. Array = decoder. decode. Buffer(salt); byte[] cipher. Text. Array = decoder. decode. Buffer(cipher. Text); // Build PBEKey. Spec based on the password PBEKey. Spec key. Spec = new PBEKey. Spec(password); // get key factory based on selected algorithm Secret. Key. Factory key. Factory = Secret. Key. Factory. get. Instance(algorithm); Applied Cryptography 62

// create the key Secret. Key key = key. Factory. generate. Secret(key. Spec); // // create the key Secret. Key key = key. Factory. generate. Secret(key. Spec); // Create a parameter spec for the salt and iterations PBEParameter. Spec param. Spec = new PBEParameter. Spec(salt. Array, ITERATIONS); // get a cipher for decryption Cipher cipher = Cipher. get. Instance(algorithm); cipher. init(Cipher. DECRYPT_MODE, key, param. Spec); // decrypt byte[] plain. Text. Array = cipher. do. Final(cipher. Text. Array); return new String(plain. Text. Array); } } Applied Cryptography 63

Session Key Example Use an RSA public key to encrypt a blowfish key In 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. Bouncy. Castle. Provider Applied Cryptography 64

Output First java Simple. RSAExample Generating a symmetric Blowfish key Generating an RSA Key Output First java Simple. RSAExample 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 Session Key Encryption // From "Professional Java Security" by Garms and Somerfield // Session Key encryption import java. security. *; import javax. crypto. spec. *; import java. util. *; import sun. misc. *; Applied Cryptography 66

public class Simple. RSAExample { public static void main(String args[]) throws Exception { System. public class Simple. RSAExample { public static void main(String args[]) throws Exception { System. out. println("Generating a symmetric Blowfish key"); Key. Generator key. Generator = Key. Generator. get. Instance ("Blowfish"); key. Generator. init(128); Key blow. Fish. Key = key. Generator. generate. Key(); System. out. println("Generating an RSA Key pair"); Key. Pair. Generator key. Pair. Generator = Key. Pair. Generator. get. Instance("RSA"); key. Pair. Generator. initialize(1024); 67 Key. Pair key. Pair = key. Pair. Generator. gen. Key. Pair();

System. out. println( System. out. println("Building a cipher based on the public key"); Cipher cipher = Cipher. get. Instance("RSA/ECB/PKCS 1 Padding"); cipher. init(Cipher. ENCRYPT_MODE, key. Pair. get. Public()); System. out. println("About to encrypt the symmetric key"); byte blow. Fish. Key. Bytes[] = blow. Fish. Key. get. Encoded(); byte cipher. Text[] = cipher. do. Final(blow. Fish. Key. Bytes); System. out. println("Decrypt the symmetric key"); cipher. init(Cipher. DECRYPT_MODE, key. Pair. get. Private()); byte decrypted. Key. Bytes[] = cipher. do. Final(cipher. Text); Secret. Key the. Blow. Fish. Key = new Secret. Key. Spec (decrypted. Key. Bytes, "Blowfish"); } } Applied Cryptography 68

Reading Certificates • X. 509 certificates are the most widely used • The JDK 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. 509 v 1, v 2, v 3 Applied Cryptography 69

Reading Certificates (1) Create a certificate using keytool (2) Use Java classes to read 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 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 Mc. Carthy 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 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 Mc. Carthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US correct? [no]: yes Enter key password for (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: 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: key. Entry Certificate chain length: 1 Certificate[1]: Applied Cryptography 73

Owner: CN=Mike Mc. Carthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US Issuer: CN=Mike Mc. Carthy, Owner: CN=Mike Mc. Carthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US Issuer: CN=Mike Mc. Carthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US Serial number: 3 ea 35081 Valid from: Sun Apr 20 21: 59: 29 EDT 2003 until: Sat Jul 19 21: 59: 29 EDT 2003 Certificate fingerprints: MD 5: B 6: D 0: 89: 2 C: 4 F: AB: A 6: 3 C: 2 C: 5 F: D 6: 2 E: 73: F 5: E 6: 96 SHA 1: E 3: 44: 06: 1 A: 19: 6 B: D 6: 27: DB: 24: AA: 7 C: 79: D 2: 9 D: F 5: 92: 3 C : 71: 5 B Applied Cryptography 74

Use keytool to create a certificate keytool -export -alias mjm -keystore coolkeys -file cool. Use keytool to create a certificate keytool -export -alias mjm -keystore coolkeys -file cool. cer Enter keystore password: sesame Certificate stored in file Applied Cryptography 75

Use keytool to look at the certificate keytool -printcert -v -file cool. cer Owner: Use keytool to look at the certificate keytool -printcert -v -file cool. cer Owner: CN=Mike Mc. Carthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US Issuer: CN=Mike Mc. Carthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US Serial number: 3 ea 35081 Valid from: Sun Apr 20 21: 59: 29 EDT 2003 until: Sat Jul 19 21: 59: 29 EDT 2003 Certificate fingerprints: MD 5: B 6: D 0: 89: 2 C: 4 F: AB: A 6: 3 C: 2 C: 5 F: D 6: 2 E: 73: F 5: E 6: 96 SHA 1: E 3: 44: 06: 1 A: 19: 6 B: D 6: 27: DB: 24: AA: 7 C: 79: D 2: 9 D: F 5: 92: 3 C: 71: 5 B Applied Cryptography 76

A Java Program to read the certificate from cool. cer // Reading Certificate data 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. Factory; public class Print. Cert. Info { public static void main(String args[]) throws Exception { // create a factory to handle X. 509 Certificate. Factory cert. Factory = Certificate. Factory. get. Instance("X. 509"); Applied Cryptography 77

// open an existing certificate file File. Input. Stream fis = new File. Input. // open an existing certificate file File. Input. Stream fis = new File. Input. Stream(args[0]); // Tell the factory about the file and retrieve a // certificate Certificate cert = cert. Factory. generate. Certificate(fis); // close the file fis. close(); // call the certificate's to. String System. out. println(cert); } } Applied Cryptography 78

java Print. Cert. Info cool. cer [ [ Version: V 1 Subject: CN=Mike Mc. java Print. Cert. Info cool. cer [ [ Version: V 1 Subject: CN=Mike Mc. Carthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US Signature Algorithm: SHA 1 with. DSA, OID = 1. 2. 840. 10040. 4. 3 Key: Sun DSA Public Key Parameters: DSA p: fd 7 f 5381 1 d 751229 52 df 4 a 9 c 2 eece 4 e 7 f 611 b 752 3 cef 4400 c 31 e 3 f 80 b 6512669455 d 4022 51 fb 593 d 8 d 58 fabf c 5 f 5 ba 30 f 6 cb 9 b 55 6 cd 7813 b 801 d 346 f f 26660 b 76 b 9950 a 5 a 49 f 9 fe 8 047 b 1022 c 24 fbba 9 d 7 feb 7 c 6 1 bf 83 b 57 e 7 c 6 a 8 a 6 150 f 04 fb 83 f 6 d 3 c 5 1 ec 30235 54135 a 16 9132 f 675 f 3 ae 2 b 61 d 72 aeff 2 2203199 d d 14801 c 7 q: 9760508 f 15230 bcc b 292 b 982 a 2 eb 840 b f 0581 cf 5 g: f 7 e 1 a 085 d 69 b 3 dde cbbcab 5 c 36 b 857 b 9 7994 afbb fa 3 aea 82 f 9574 c 0 b 3 d 078267 5159578 e bad 4594 f e 6710710 8180 b 449 167123 e 8 4 c 281613 b 7 cf 0932 8 cc 8 a 6 e 1 3 c 167 a 8 b 547 c 8 d 28 e 0 a 3 ae 1 e 2 bb 3 a 675 916 ea 37 f 0 bfa 2135 62 f 1 fb 62 7 a 01243 b cca 4 f 1 be a 8519089 a 883 dfe 1 5 ae 59 f 06 928 b 665 e 807 b 5525 64014 c 3 b fecf 492 a Applied Cryptography 79

y: aac 3 eb 5 c 6371449 a 9 ef 90719 5 d 911014 y: aac 3 eb 5 c 6371449 a 9 ef 90719 5 d 911014 ecd 65 e 5 a e 959 d 9 ff 5799 edd 3 a 63 a 8 dd 2 36785 e 2 a c 0 b 4275 b a 17 e 9 b 50 efeb 1 c 4 e 6 ea 47846 872 db 0 d 6 3 db 1619 d 6 ed 31 f 67 5 ef 9 f 1 e 4 f 94491 e 3 47 ed 9 cdb a 7 ffe 054 ab 2 a 2 b 45 9 ecee 6 a 1 2 b 75 bd 79 ff 603 f 9 a 35 f 40 f 83 3 f 235573 b 489 fab 8 d 2974004 45 b 00 a 44 d 55 a 6348 d 6 d 3 df 43 7 f 41 e 954 Validity: [From: Sun Apr 20 21: 59: 29 EDT 2003, To: Sat Jul 19 21: 59: 29 EDT 2003] Issuer: CN=Mike Mc. Carthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US Serial. Number: [ 3 ea 35081] ] Algorithm: [SHA 1 with. DSA] Signature: 0000: 30 2 C 02 14 7 B 9 C 92 2 D AE B 8 CE A 2 72 0 A 40 72 0, . . . -. . r. @r 0010: C 7 79 23 76 6 D 7 D 9 F 86 02 14 3 B 82 C 1 6 D 12 B 8. y#vm. . . ; . . m. . 0020: 6 A 7 C 6 B 34 20 0 A 92 A 6 DA 37 76 34 57 F 2 j. k 4. . 7 v 4 W. ] Applied Cryptography 80

A Java Program to read the certificate from coolkeys import java. io. *; import A Java Program to read the certificate from coolkeys import java. io. *; import java. security. cert. Certificate. Factory; import java. security. cert. Certificate; import java. security. Key. Store; // Code adapted from Professional Java Security, by Garms and Somerfield public class Print. Cert. From. Key. Store { public static void main(String args[]) throws Exception { if(args. length != 3) { System. err. println("Usage: java Print. Cert. Info keystore alias password"); System. exit(1); } Applied Cryptography 81

String key. File. Name = args[0]; String alias = args[1]; char[] pass. Word = String key. File. Name = args[0]; String alias = args[1]; char[] pass. Word = args[2]. to. Char. Array(); File. Input. Stream fis = new File. Input. Stream(key. File. Name); Key. Store key. Store = Key. Store. get. Instance("JKS"); key. Store. load(fis, pass. Word); // Get a Certificate object Certificate cert = key. Store. get. Certificate(alias); // Call cert's to. String System. out. println(cert); } } Applied Cryptography 82

java Print. Cert. From. Key. Store coolkeys mjm sesame [ [ Version: V 1 java Print. Cert. From. Key. Store coolkeys mjm sesame [ [ Version: V 1 Subject: CN=Mike Mc. Carthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US Signature Algorithm: SHA 1 with. DSA, OID = 1. 2. 840. 10040. 4. 3 Key: Sun DSA Public Key Parameters: DSA p: fd 7 f 5381 1 d 751229 52 df 4 a 9 c 2 eece 4 e 7 f 611 b 752 3 cef 4400 c 31 e 3 f 80 b 6512669455 d 4022 51 fb 593 d 8 d 58 fabf c 5 f 5 ba 30 f 6 cb 9 b 55 6 cd 7813 b 801 d 346 f f 26660 b 76 b 9950 a 5 a 49 f 9 fe 8 047 b 1022 c 24 fbba 9 d 7 feb 7 c 6 1 bf 83 b 57 e 7 c 6 a 8 a 6 150 f 04 fb 83 f 6 d 3 c 5 1 ec 30235 54135 a 16 9132 f 675 f 3 ae 2 b 61 d 72 aeff 2 2203199 d d 14801 c 7 q: 9760508 f 15230 bcc b 292 b 982 a 2 eb 840 b f 0581 cf 5 g: f 7 e 1 a 085 d 69 b 3 dde cbbcab 5 c 36 b 857 b 9 7994 afbb fa 3 aea 82 f 9574 c 0 b 3 d 0782675159578 e bad 4594 f e 6710710 8180 b 449 167123 e 8 4 c 281613 b 7 cf 0932 8 cc 8 a 6 e 13 c 167 a 8 b 547 c 8 d 28 e 0 a 3 ae 1 e 2 bb 3 a 675 916 ea 37 f 0 bfa 2135 62 f 1 fb 62 7 a 01243 bcca 4 f 1 be a 8519089 a 883 dfe 1 5 ae 59 f 06 928 b 665 e 807 b 5525 64014 c 3 b fecf 492 a Applied Cryptography 83

y: aac 3 eb 5 c 6371449 a 9 ef 90719 5 d 911014 y: aac 3 eb 5 c 6371449 a 9 ef 90719 5 d 911014 ecd 65 e 5 a e 959 d 9 ff 5799 edd 3 a 63 a 8 dd 2 36785 e 2 a c 0 b 4275 b a 17 e 9 b 50 efeb 1 c 4 e 6 ea 47846 872 db 0 d 6 3 db 1619 d 6 ed 31 f 67 5 ef 9 f 1 e 4 f 94491 e 3 47 ed 9 cdb a 7 ffe 054 ab 2 a 2 b 45 9 ecee 6 a 1 2 b 75 bd 79 ff 603 f 9 a 35 f 40 f 83 3 f 235573 b 489 fab 8 d 2974004 45 b 00 a 44 d 55 a 6348 d 6 d 3 df 43 7 f 41 e 954 Validity: [From: Sun Apr 20 21: 59: 29 EDT 2003, To: Sat Jul 19 21: 59: 29 EDT 2003] Issuer: CN=Mike Mc. Carthy, OU=Heinz School, O=CMU, L=Pgh, ST=PA, C=US Serial. Number: [ 3 ea 35081] ] Algorithm: [SHA 1 with. DSA] Signature: 0000: 30 2 C 02 14 7 B 9 C 92 2 D AE B 8 CE A 2 72 0 A 40 72 0, . . . -. . r. @r 0010: C 7 79 23 76 6 D 7 D 9 F 86 02 14 3 B 82 C 1 6 D 12 B 8. y#vm. . . ; . . m. . 0020: 6 A 7 C 6 B 34 20 0 A 92 A 6 DA 37 76 34 57 F 2 j. k 4. . 7 v 4 W. ] Applied Cryptography 84

Diffie-Hellman Key Exchange // Diffie-Hellman : Example modified from 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. spec. *; import javax. crypto. interfaces. *; import java. math. *; import java. security. spec. *; import javax. crypto. interfaces. *; public class DHAgreement implements Runnable { byte bob[]; byte alice[]; boolean done. Alice = false; byte cipher. Text[]; Applied Cryptography 86

Big. Integer alice. P; // Prime Big. Integer alice. G; // Generator int alice. Big. Integer alice. P; // Prime Big. Integer alice. G; // Generator int alice. L; // Length in bits of private value public synchronized void run() { if(!done. Alice) { done. Alice = true; do. Alice(); } else do. Bob(); } Applied Cryptography 87

public synchronized void do. Alice() { try { // Create a pair of keys public synchronized void do. Alice() { try { // Create a pair of keys for Alice Key. Pair. Generator kpg = Key. Pair. Generator. get. Instance("DH"); kpg. initialize(512); // may be set to 1024 but DH Key // construction is costly Key. Pair kp = kpg. generate. Key. Pair(); DHParameter. Spec dh. Spec = ((DHPublic. Key) kp. get. Public()). get. Params(); alice. G = dh. Spec. get. G(); alice. P = dh. Spec. get. P(); alice. L = dh. Spec. get. L(); alice = kp. get. Public(). get. Encoded(); Applied Cryptography 88

// tell at most one thread waiting for a condition to change notify(); Key. // tell at most one thread waiting for a condition to change notify(); Key. Agreement ka = Key. Agreement. get. Instance("DH"); ka. init(kp. get. Private()); while(bob == null) { wait(); // wait for notification } Key. Factory kf = Key. Factory. get. Instance("DH"); X 509 Encoded. Key. Spec x 509 Spec = new X 509 Encoded. Key. Spec(bob); Public. Key pk = kf. generate. Public(x 509 Spec); ka. do. Phase(pk, true); Applied Cryptography 89

byte secret[] = ka. generate. Secret(); Secret. Key. Factory skf = Secret. Key. Factory. byte secret[] = ka. generate. Secret(); Secret. Key. Factory skf = Secret. Key. Factory. get. Instance("DES"); DESKey. Spec des. Spec = new DESKey. Spec(secret); Secret. Key key = skf. generate. Secret(des. Spec); Cipher c = Cipher. get. Instance("DES/ECB/PKCS 5 Padding"); c. init(Cipher. ENCRYPT_MODE, key); cipher. Text = c. do. Final("Attack at dawn!". get. Bytes()); notify(); } catch (Exception e) { e. print. Stack. Trace(); } } Applied Cryptography 90

public synchronized void do. Bob() { try { while(alice == null) { wait(); } public synchronized void do. Bob() { try { while(alice == null) { wait(); } Key. Pair. Generator kpg = Key. Pair. Generator. get. Instance("DH"); DHParameter. Spec dh. Spec = new DHParameter. Spec(alice. P, alice. G, alice. L); kpg. initialize(dh. Spec); Key. Pair kp = kpg. generate. Key. Pair(); bob = kp. get. Public(). get. Encoded(); // tell at most one thread waiting for a condition to change notify(); Applied Cryptography 91

Key. Agreement ka = Key. Agreement. get. Instance( Key. Agreement ka = Key. Agreement. get. Instance("DH"); ka. init(kp. get. Private()); Key. Factory kf = Key. Factory. get. Instance("DH"); X 509 Encoded. Key. Spec x 509 Spec = new X 509 Encoded. Key. Spec(alice); Public. Key pk = kf. generate. Public(x 509 Spec); ka. do. Phase(pk, true); byte secret[] = ka. generate. Secret(); Secret. Key. Factory skf = Secret. Key. Factory. get. Instance("DES" DESKey. Spec des. Spec = new DESKey. Spec(secret); Secret. Key key = skf. generate. Secret(des. Spec); Applied Cryptography 92

Cipher c = Cipher. get. Instance( Cipher c = Cipher. get. Instance("DES/ECB/PKCS 5 Padding"); c. init(Cipher. DECRYPT_MODE, key); while(cipher. Text == null) { wait(); } byte plain. Text[] = c. do. Final(cipher. Text); System. out. println("Bob received : " + new String(plain. Text)); } catch (Exception e) { e. print. Stack. Trace(); } } Applied Cryptography 93

public static void main(String args[]) { DHAgreement demo = new DHAgreement(); new Thread(demo). start(); public static void main(String args[]) { DHAgreement demo = new DHAgreement(); new Thread(demo). start(); } } Applied Cryptography 94