Applied Cryptography1 Applied Cryptography Week 9 Java Tools Michael McCarthy.
-
date post
21-Dec-2015 -
Category
Documents
-
view
221 -
download
0
Transcript of Applied Cryptography1 Applied Cryptography Week 9 Java Tools Michael McCarthy.
Applied Cryptography 1
Applied CryptographyWeek 9 Java Tools
Michael McCarthy
Applied Cryptography 2
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 3
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 4
The Security Architecture
Java describes operations (engines). There may be severalvendors that have implementations of these engines.
This is all set up so that the programmer can select whichvendor’s code to use.
Applied Cryptography 5
Example Engine Classes
MessageDigest Signature KeyFactory KeyPairGenerator SecureRandom A program may simply request a particular engine
(such as a MessageDigest object) implementing a particularalgorithm (such as the secure hash algorithm SHA-1)and get an implementation from one of the installed providers.
Applied Cryptography 6
The Architecture Of Security Providers
Engines are always abstract and independent of any particularalgorithm. Think of engines as operations. A Message Digestoperation 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 administratorsets the provider.
Applied Cryptography 7
ApplicationProgrammer
Engine Class
Java.Security.Security
Security Class
SUNJSSE
SUNRSAS16N1.3
Provider Class Algorithm Class
Message Digest
Asks providers ifthey can handle aMessageDigest.MD5
Provider
SUN
SUNJCE
“MessageDigest.MDS”
engine algorithm Holds a listof providers
KeyPairGenerator.DSA Security Provider
Map (engine, algorithm) pair to a class
SSI.Provider
Fromsamevendor
Fromsamevendor
Applied Cryptography 8
From jre/lib/security/java.security
# Each Provider may implement several engines #security.provider.1=sun.security.provider.Sunsecurity.provider.2=com.sun.net.ssl.internal.ssl.Providersecurity.provider.3=com.sun.rsajca.Providersecurity.provider.4=com.sun.crypto.provider.SunJCEsecurity.provider.5=sun.security.jgss.SunProvider
Applied Cryptography 9
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 10
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 11
java ExamineSecuritySUN 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
Providers
Engine, Algorithm provided
Applied Cryptography 12
SunRsaSign version 1.0 KeyFactory.RSA Signature.MD5withRSA Signature.SHA1withRSA Signature.MD2withRSA KeyPairGenerator.RSA Many deletions BouncyCastle added laterSunJCE version 1.4 Cipher.DES KeyStore.JCEKS Alg.Alias.SecretKeyFactory.TripleDES SecretKeyFactory.DESSunJGSS version 1.0
Applied Cryptography 13
MessageDigest is an Engineimport 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 14
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 15
java ComputeAMessageDigestSHA-1The 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
java ComputeAMessageDigestSHA-1The 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
Add a period…
Applied Cryptography 16
We Can Choose an Algorithmimport 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 17
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 18
java ComputeAMessageDigestMD5The hash value of 'Applied Cryptography.' is16 -26 -44 -19 -78 23 13 88 12 -49 17 6 126 -66 -1 -84
Applied Cryptography 19
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 20
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 21
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 providingthis service.
The programmer will make a request to the Security classAnd can specify the engine, algorithm, and the provider
Applied Cryptography 22
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 23
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 24
// 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 25
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 26
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 27
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 28
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");
Applied Cryptography 29
// 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 30
java XYZKeyPairGeneratorRunning initializeGot key pairAlgorithm = XYZ
Applied Cryptography 31
Symmetric Encryption Example
java WorkingWithBlowfishABCDEFG as bytes41 42 43 44 45 46 47Cipher text as bytes9e dd 46 30 b1 14 79 6bAfter decryptionABCDEFG
Applied Cryptography 32
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());
Applied Cryptography 33
// Build a key from scratch// Symmetric keys come from the KeyGenerator engine// Asymmetric keys come from the KeyPairGenerator engineKeyGenerator kg = KeyGenerator.getInstance("Blowfish");kg.init(128); // key size
// create the key dataKey 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 keycipher.init(Cipher.ENCRYPT_MODE, k);
Applied Cryptography 34
// 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 35
// display a byte in hexpublic 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 36
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: H E L L O 3 3 3 padding bytes always present H E L L O J O E 8 8 8 8 8 8 8 8
Applied Cryptography 37
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 38
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 39
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
Applied Cryptography 40
Working With DSA
• 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
Signing
Applied Cryptography 41
// 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 42
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 43
// We get the file to be signedFileInputStream 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 signedwhile (bis.available() != 0) { len=bis.read(buff); dsasig.update(buff, 0, len); }
// We close the buffered input stream and the file input streambis.close();fis.close();
Applied Cryptography 44
// We get the signaturebyte[] realSignature = dsasig.sign();
// We write the signature to a fileFileOutputStream fos = new FileOutputStream(arg[1]);fos.write(realSignature);fos.close();
// Dsiplay the signature in hexSystem.out.println("The Signature of " + arg[0] + " in hex\n");
displayBytes(realSignature);
// We write the public key to a filebyte[] pkey = publ.getEncoded();FileOutputStream keyfos = new FileOutputStream(arg[2]);keyfos.write(pkey);keyfos.close();
Applied Cryptography 45
// Display the public key in hexSystem.out.println("The DSA public key in hex\n");displayBytes(pkey);}catch (Exception e) { System.out.println("Caught Exception: " + e); } }
Applied Cryptography 46
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 47
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 48
3b 57 e7 c6 a8 a6 15 0f 04 fb 83 f6 d3 c5 1e c3 02 35 54 13 5a 1691 32 f6 75 f3 ae 2b 61 d7 2a ef f2 22 03 19 9d d1 48 01 c7 02 1500 97 60 50 8f 15 23 0b cc b2 92 b9 82 a2 eb 84 0b f0 58 1c f5 0281 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 0bfa 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 7514 04 4e c4 e8 3e 58 4e 19 ca 49 7f 59 39 90 b4 43 14 43 99 07 5362 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 49
Working With DSA
• 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
Verifying
Applied Cryptography 50
// VerifyFile.java from “Java 2 Network Security” IBMimport 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 = new FileInputStream(args[1]); FileInputStream pfis = new FileInputStream(args[2]);
Applied Cryptography 51
//Get the public key of the senderbyte[] 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 verifiedbyte[] sigToVerify = new byte[sfis.available()];sfis.read(sigToVerify);sfis.close();
Applied Cryptography 52
// Initialize the signature - update() method used to update the // data to be verifiedSignature 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 53
// Verify the signatureboolean 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 54
D:\McCarthy\www\95-804\signfile>java VerifyFile SignFile.java SignatureFile.txt PublicKeyFile.txtVerified: The signature on the file is correct.
From "Java Security" by Garms and SomerField
55
Password Based Encryption
Plaintext
Password
New Salt
PBE CipherCiphertext
salt Cipher text
Base 64 encoded
Base 64 Encoded
From "Java Security" by Garms and SomerField
56
PBE DecryptionPlaintext
Password Salt
PBE Cipher
Ciphertext
salt Cipher text
Base 64 Decode
Base 64 Decode
Applied Cryptography 57
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 58
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 64public 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;
Applied Cryptography 59
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 60
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 61
// 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 62
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 63
// 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 64
Session Key ExampleUse an RSA public key to encrypt a blowfish key
In order to run the following program you must downloadJCE with provider and lightweight API from www.bouncycastle.org
Place the downloaded Jar file in all of the many /jre/lib/ext directorieson 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 65
Output First
java SimpleRSAExampleGenerating a symmetric Blowfish keyGenerating an RSA Key pairBuilding a cipher based on the public keyAbout to encrypt the symmetric keyDecrypt the symmetric key
Applied Cryptography 66
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 67
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); KeyPair keyPair = keyPairGenerator.genKeyPair();
Applied Cryptography 68
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 69
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 70
Reading Certificates
(1) Create a certificate using keytool
(2) Use Java classes to read the data
Applied Cryptography 71
Use Keytool to Create Keys
keytool -genkey -alias mjm -keyalg DSA -keystore coolkeys
Enter keystore password: sesameWhat is your first and last name? [Unknown]: Mike McCarthyWhat is the name of your organizational unit? [Unknown]: Heinz SchoolWhat is the name of your organization? [Unknown]: CMUWhat is the name of your City or Locality? [Unknown]: Pgh
Applied Cryptography 72
What is the name of your State or Province? [Unknown]: PAWhat is the two-letter country code for this unit? [Unknown]: USIs 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 73
Use keytool to look at coolkeys
keytool -v -list -keystore coolkeysEnter keystore password: sesame
Keystore type: jksKeystore provider: SUN
Your keystore contains 1 entry
Alias name: mjmCreation date: Apr 20, 2003Entry type: keyEntryCertificate chain length: 1Certificate[1]:
Applied Cryptography 74
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: 3ea35081Valid from: Sun Apr 20 21:59:29 EDT 2003 until: Sat Jul 19
21:59:29 EDT 2003Certificate 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 75
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 76
Use keytool to look at the certificatekeytool -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: 3ea35081Valid 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 77
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 78
// 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 79
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 80
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.@r0010: 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 81
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 82
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 83
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 84
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.@r0010: 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 85
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 86
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 87
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 88
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 89
// 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 90
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 91
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 92
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 93
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 94
public static void main(String args[]) { DHAgreement demo = new DHAgreement(); new Thread(demo).start(); new Thread(demo).start(); }}