1 / 94

Applied Cryptography Week 9 Java Tools

Applied Cryptography Week 9 Java Tools. Michael McCarthy. Java Tools. Security Provider Architecture Example Programs Message Digests Symmetric Encryption Digital Signature Algorithm (DSA) Password Based Encryption (PBE)

ollie
Download Presentation

Applied Cryptography Week 9 Java Tools

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 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

  5. 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

  6. 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

  7. SUNJSSE Application Programmer SUNRSAS16N 1.3 Java.Security.Security Engine Class Provider Class Algorithm Class Security Class Message Digest From same vendor SUN Asks providers if they can handle a MessageDigest.MD5 Provider “MessageDigest.MDS” From same vendor SUNJCE Holds a list of providers engine algorithm KeyPairGenerator.DSA Security Provider SSI.Provider Applied Cryptography Map (engine, algorithm) pair to a class

  8. 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

  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 ExamineSecurity 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 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 later SunJCE version 1.4 Cipher.DES KeyStore.JCEKS Alg.Alias.SecretKeyFactory.TripleDES SecretKeyFactory.DES SunJGSS version 1.0 Applied Cryptography

  13. 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

  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 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

  16. 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

  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 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

  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 providing this service. The programmer will make a request to the Security class And 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");

  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 XYZKeyPairGenerator Running initialize Got key pair Algorithm = XYZ Applied Cryptography

  31. 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

  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());

  33. // 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);

  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 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

  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

  40. 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

  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 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

  44. // 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

  45. // 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

  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 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

  49. 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

  50. // 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 = new FileInputStream(args[1]); FileInputStream pfis = new FileInputStream(args[2]); Applied Cryptography

More Related