Encryption Boot Camp on the JVM

3,072 views
2,940 views

Published on

Does your application transmit customer information? Are there fields of sensitive customer data stored in your DB? Can your application be used on insecure networks? If so, you need a working knowledge of encryption and how to leverage Open Source APIs and libraries to make securing your data as easy as possible. Encryption is quickly becoming a developer’s new frontier of responsibility in many data-centric applications.

In today’s data-sensitive and news-sensationalizing world, don’t become the next headline by an inadvertent release of private customer or company data. Secure your persisted, transmitted and in-memory data and learn the terminology you’ll need to navigate the ecosystem of symmetric and public/private key encryption.

Published in: Technology, Education
2 Comments
2 Likes
Statistics
Notes
  • Great presentation! Probably the only presentation that had my focus the entire session! I hope you can come back next year a do a kind of follow up on this. Maybe dig deeper into asymetric keys, PKI, Certificate Authorities and such.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Nice presentation! While I'm not a programmer, I can appreciate the amount of work you put into laying out your information cleanly.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
3,072
On SlideShare
0
From Embeds
0
Number of Embeds
322
Actions
Shares
0
Downloads
152
Comments
2
Likes
2
Embeds 0
No embeds

No notes for slide

Encryption Boot Camp on the JVM

  1. 1. OT CA MP TI ON BO sion P is your mis CRYrity EN ecu s
  2. 2. SECURITY What’s ON THE J your po VM sition?
  3. 3. RYPTI NG? not ENC say probably s sta tistic
  4. 4. WO RRI ED? s houl d be You
  5. 5. Matthew McCullough @matthewmccull #EncryptBC http://speakerrate.com/matthew.mccullough
  6. 6. ANCIENT HISTORY Everything old is new again
  7. 7. ht Sig ain Pl Sensitive Data
  8. 8. Recipient or Storage ht Sig ain Pl Sensitive Data
  9. 9. Recipient or Storage ht Sig ur ed ain ts O b sc Pl C o nt en Sensitive Data
  10. 10. ll over ’m a ew “I n thisryption nc boss” e ff stu
  11. 11. 44 B.C. That’s 2,054 years ago...
  12. 12. Julius Caesar
  13. 13. Caesar Cipher a.k.a. ROT(2) Shift Cipher A B C D E F G A B C D E F G
  14. 14. Caesar Cipher a.k.a. ROT(2) Shift Cipher A B C D E F G A B C D E F G
  15. 15. Caesar Cipher Rotation = Integer Rot(x)
  16. 16. Caesar Cipher Z M S R
  17. 17. Caesar Cipher Z M S R A N T S if encrypted with ROT(-1)
  18. 18. Caesar Cipher Z M S R A N T S if encrypted with ROT(-1) B O U T if encrypted with ROT(-2)
  19. 19. /** * A naively simple rotation cipher implementation. * USAGE: groovy RotateWord.groovy <yourword> */ public class RotateWord { /** * Rotate one character by the specified amount */ private static char rotateChar(char c, int rotationAmount) { //a == 97, z == 122 int num = (int)c int rotated = num + rotationAmount int adjusted //Handle roll-around wrapping
  20. 20. /** * A naively simple rotation cipher implementation. * USAGE: groovy RotateWord.groovy <yourword> */ public class RotateWord { /** * Rotate one character by the specified amount */ private static char rotateChar(char c, int rotationAmount) { //a == 97, z == 122 int num = (int)c int rotated = num + rotationAmount int adjusted //Handle roll-around wrapping if (rotated > 122) adjusted = rotated - 26 else if (rotated < 97) adjusted = rotated + 26 else adjusted = rotated
  21. 21. */ public class RotateWord { /** * Rotate one character by the specified amount */ private static char rotateChar(char c, int rotationAmount) { //a == 97, z == 122 int num = (int)c int rotated = num + rotationAmount int adjusted //Handle roll-around wrapping if (rotated > 122) adjusted = rotated - 26 else if (rotated < 97) adjusted = rotated + 26 else adjusted = rotated char adjustedChar = (char)adjusted return adjustedChar } /**
  22. 22. */ private static char rotateChar(char c, int rotationAmount) { //a == 97, z == 122 int num = (int)c int rotated = num + rotationAmount int adjusted //Handle roll-around wrapping if (rotated > 122) adjusted = rotated - 26 else if (rotated < 97) adjusted = rotated + 26 else adjusted = rotated char adjustedChar = (char)adjusted return adjustedChar } /** * Rotate the entire String by the specified rotation amount. */ public static String rotateAllChars(String plainText, int rotationAmount) { String encodedMessage = ""
  23. 23. else if (rotated < 97) adjusted = rotated + 26 else adjusted = rotated char adjustedChar = (char)adjusted return adjustedChar } /** * Rotate the entire String by the specified rotation amount. */ public static String rotateAllChars(String plainText, int rotationAmount) { String encodedMessage = "" //Loop through each character in the plaintext for (int i = 0; i < plainText.length(); i++) { //TODO: Improve to handle upper and lower case letters char c = plainText.toLowerCase().charAt(i) encodedMessage += rotateChar(c, rotationAmount) } return encodedMessage }
  24. 24. char adjustedChar = (char)adjusted return adjustedChar } /** * Rotate the entire String by the specified rotation amount. */ public static String rotateAllChars(String plainText, int rotationAmount) { String encodedMessage = "" //Loop through each character in the plaintext for (int i = 0; i < plainText.length(); i++) { //TODO: Improve to handle upper and lower case letters char c = plainText.toLowerCase().charAt(i) encodedMessage += rotateChar(c, rotationAmount) } return encodedMessage } public static void main (String[] args) { String originalword = args[0] println "Rot(-3) Word: " + rotateAllChars(originalword, -3)
  25. 25. } public static void main (String[] args) { String originalword = args[0] println "Rot(-3) Word: " + rotateAllChars(originalword, -3) println "Rot(-2) Word: " + rotateAllChars(originalword, -2) println "Rot(-1) Word: " + rotateAllChars(originalword, -1) println "Original Word: ${originalword}" println "Rot(1) Word: " + rotateAllChars(originalword, 1) println "Rot(2) Word: " + rotateAllChars(originalword, 2) println "Rot(3) Word: " + rotateAllChars(originalword, 3) println "Rot(4) Word: " + rotateAllChars(originalword, 4) println "Rot(5) Word: " + rotateAllChars(originalword, 5) println "Rot(6) Word: " + rotateAllChars(originalword, 6) println "Rot(7) Word: " + rotateAllChars(originalword, 7) } }
  26. 26. > groovy RotateWord.groovy ants Rot(-3) Word: xkqp Rot(-2) Word: ylrq Rot(-1) Word: zmsr Original Word: ants Rot(1) Word: bout Rot(2) Word: cpvu Rot(3) Word: dqwv
  27. 27. > groovy RotateWord.groovy ants Rot(-3) Word: xkqp Rot(-2) Word: ylrq Rot(-1) Word: zmsr Original Word: ants Rot(1) Word: bout Rot(2) Word: cpvu Rot(3) Word: dqwv
  28. 28. BROKEN Perfectly safe data is a myth
  29. 29. Compromised ! Every algorithm is vulnerable ! crack by brute force ! Crack by rainbow tables ! Function of time + money + hardware
  30. 30. $2000 Whic h wo uld you $500 hit?
  31. 31. $10,000 Now whic h wo uld you $50 hit?
  32. 32. JCE PRIMER The world of Java crypto
  33. 33. Java Cryptography Extension known as JCE
  34. 34. Java Cryptography Extension known as JCE included in all JREs Since Java 1.2
  35. 35. Java Cryptography Extension known as JCE included in all JREs Since Java 1.2 Pluggable provider architecture
  36. 36. Java Cryptography Extension known as JCE included in all JREs Since Java 1.2 Pluggable provider architecture JCE extends Java Cryptography Architecture (JCA)
  37. 37. JCE Providers ! Default Sun JRE providers ! SUN ! SunJCE ! SunJSSE ! SunRsaSign ! Bouncycastle provider ! Adds AES capabilities
  38. 38. Registering a Provider ! Static ! <java-home>/lib/security/java.security ! security.provider.n=masterClassName
  39. 39. Registering a Provider ! Dynamic ! java.security.Security class ! addProvider() ! insertProviderAt() ! not persistent across VM instances
  40. 40. EnCryption & the Law country borders stop bits
  41. 41. JCE Strength ! Jurisdiction Policy Files ! “Strong” ! “Unlimited”
  42. 42. JCE Strength ! Strong strength included in all JREs ! Unlimited strength is a separate download available based on US export rules
  43. 43. Worldwide Policy // File: default_local.policy // Some countries have import limits on crypto strength. // This policy file is worldwide importable. grant { permission javax.crypto.CryptoPermission "DES", 64; permission javax.crypto.CryptoPermission "DESede", *; permission javax.crypto.CryptoPermission "RC2", 128, "javax.crypto.spec.RC2ParameterSpec", 128; permission javax.crypto.CryptoPermission "RC4", 128; permission javax.crypto.CryptoPermission "RC5", 128, "javax.crypto.spec.RC5ParameterSpec", *, 12, *; permission javax.crypto.CryptoPermission "RSA", 2048; permission javax.crypto.CryptoPermission *, 128; };
  44. 44. Max Key Sizes Algorithm Max Key Size DES 64 DESede 168 3des RC2 128 RC4 128 RC5 128 RSA 2048 Others 128
  45. 45. Key Size & Security 160 bit DES Symmetric Key Size
  46. 46. Key Size & Security 1024 bit RSA Asymmetric Key Size 160 bit DES Symmetric Key Size
  47. 47. Key Size & Security 1024 bit RSA Asymmetric Key Size 160 bit DES Symmetric Key Size 112 bits Security
  48. 48. Key Size & Security 1024 bit RSA Asymmetric Key Size 160 bit DES Symmetric Key Size 112 bits 128 bits Security Security
  49. 49. Random Numbers Seed the machine
  50. 50. SecureRandom ! java.security.SecureRandom ! Cryptographically strong random number generator (RNG) ! “Unable to distinguish from a true random source”
  51. 51. package com.ambientideas; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /** * Use the SecureRandom java security class to generate * a more expensive, but cryptographically secure random number. */ public class SecureRandomNumber { public static void main( String[] args ) throws NoSuchAlgorithmException { //Do the expensive one time setup of the // random number generator instance
  52. 52. import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /** * Use the SecureRandom java security class to generate * a more expensive, but cryptographically secure random number. */ public class SecureRandomNumber { public static void main( String[] args ) throws NoSuchAlgorithmException { //Do the expensive one time setup of the // random number generator instance SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); //Get the next random number String randomNum = new Integer( prng.nextInt() ).toString(); System.out.println("Random number: " + randomNum); } }
  53. 53. * a more expensive, but cryptographically secure random number. */ public class SecureRandomNumber { public static void main( String[] args ) throws NoSuchAlgorithmException { //Do the expensive one time setup of the // random number generator instance SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); //Get the next random number String randomNum = new Integer( prng.nextInt() ).toString(); System.out.println("Random number: " + randomNum); } }
  54. 54. Result Random number: 1633471380
  55. 55. Digests & Hashes One way functions
  56. 56. What is a Digest? ! Small set of bytes representing a large message ! Small change in message = large change in digest ! Integrity check for large data ! Password storage mechanism
  57. 57. MessageDigest ! java.security.MessageDigest ! Multiple algorithms available ! MD5 (128 bit) ! SHA-1 (160 bit)
  58. 58. MessageDigest ! ! MD5 U. S. Department of Homeland Security said MD5 "considered cryptographically broken and unsuitable for further use"
  59. 59. http://xkcd.com/538/
  60. 60. System.out.println("Message1 SHA1 digest: " + shaAndBase64Encode(message1)); System.out.println("Message2 SHA1 digest: " + shaAndBase64Encode(message2)); } /** * Helper function to both SHA-1 hash and * base64 encode the resulting bytes to a String */ public static String shaAndBase64Encode(String message) throws NoSuchAlgorithmException { MessageDigest sha = MessageDigest.getInstance("SHA-1"); //Salt could be applied here //Integer salt = <some random number generator> //sha.update(salt.getBytes()); byte[] digest = sha.digest(message.getBytes()); return new sun.misc.BASE64Encoder().encode(digest); } }
  61. 61. * * Demonstrate that very similar messages * have radically different hashes. */ public class MessageDigestSHA { public static void main( String[] args ) throws NoSuchAlgorithmException { //Set up the message to be encoded String message1 = "Four score and seven years ago"; String message2 = "Four score and seven tears ago"; System.out.println("Message1 SHA1 digest: " + shaAndBase64Encode(message1)); System.out.println("Message2 SHA1 digest: " + shaAndBase64Encode(message2)); } /** * Helper function to both SHA-1 hash and * base64 encode the resulting bytes to a String */ public static String shaAndBase64Encode(String message) throws NoSuchAlgorithmException { MessageDigest sha = MessageDigest.getInstance("SHA-1");
  62. 62. Input String message1 = "Four score and seven years ago"; String message2 = "Four score and seven tears ago"; Result Message1 SHA1 digest: DmCJIg4Bq/xpGIxVXxo3IB0vo38= Message2 SHA1 digest: oaLHt8tr31ttngCDjyYuWowF5Mc=
  63. 63. JDK Keytool Key generation, storage & management
  64. 64. Keytool ! Creates ! Keystore ! Truststore ! Functions ! -genkey ! -list ! -import ! -export ! -certreq
  65. 65. Creating a keystore keytool -genkeypair -keyalg RSA -keysize 2048 - keystore myapp.keystore Enter keystore password: ******** Re-enter new password: ******** What is your first and last name? [Unknown]: Matthew McCullough What is the name of your organizational unit? [Unknown]: Consulting What is the name of your organization? [Unknown]: Ambient Ideas, LLC What is the name of your City or Locality? [Unknown]: Denver What is the name of your State or Province? [Unknown]: Colorado What is the two-letter country code for this unit? [Unknown]: US
  66. 66. keytool -genkeypair -keyalg RSA -keysize 2048 - Creating a keystore keystore myapp.keystore Enter keystore password: ******** Re-enter new password: ******** What is your first and last name? [Unknown]: Matthew McCullough What is the name of your organizational unit? [Unknown]: Consulting What is the name of your organization? [Unknown]: Ambient Ideas, LLC What is the name of your City or Locality? [Unknown]: Denver What is the name of your State or Province? [Unknown]: Colorado What is the two-letter country code for this unit? [Unknown]: US Is CN=Matthew McCullough, OU=Consulting, O="Ambient Ideas, LLC", L=Denver, ST=Colorado, C=US correct? [no]: yes Enter key password for <mykey> ! (RETURN if same as keystore password):
  67. 67. Using a keystore java -Djavax.net.ssl.keyStore=keystore -Djavax.net.ssl.keyStorePassword=y3$1t1s ServerApp Using a Truststore java -Djavax.net.ssl.trustStore=truststore -Djavax.net.ssl.trustStorePassword=tru$tM3 ClientApp
  68. 68. JSSE Network communications security
  69. 69. JSSE ! Java Secure Socket Extension ! Built on top of JCE ! Specific to networking ! Standard as of JRE 1.4 ! Implementations of ! Secure Sockets Layer (SSL) 2.0 and 3.0 ! Transport Layer Security (TLS) 1.0
  70. 70. JAAS Authentication and Authorization
  71. 71. JAAS ! Java Authentication and Authorization Service ! Single sign on helper ! Supports biometric, smartcard devices ! Adds “user” control (above code control)
  72. 72. SYMMETRIC My key is your key
  73. 73. Why Symmetric? ! Fast ! Bulk data ! Controlled environment ! Never decrypted at remote end
  74. 74. Symmetric Problems ! Keys vulnerable to capture
  75. 75. Symmetric Problems ! Keys vulnerable to capture ! Eavesdropping on future communications after key compromise ! Key distribution challenges ! Triangular number key growth
  76. 76. Symmetric Problems ! Triangular number key growth
  77. 77. DES & 3DES ! Block cipher ! DES is known to be broken ! 3DES and DESede ! basically three passes of DES ! Reasonably strong
  78. 78. Blowfish ! Secure replacement for DES ! Faster than DES ! Block cipher
  79. 79. RC4 ! Rivest’s code 4 ! Stream cipher
  80. 80. AES ! Advanced Encryption Standard ! Government standard ! Rijndael algorithm (Joan Daemen, Vincent Rijmen) ! 4 years of evaluation ! Final in December 2000 ! Very Secure ! block cipher
  81. 81. import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import sun.misc.BASE64Encoder; /** * Use the SecureRandom java security class to generate * a more expensive, but cryptographically secure random number. */ public class SymmetricEncrypt { public static void main( String[] args ) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { final String message1 = "Four score and seven years ago";
  82. 82. import sun.misc.BASE64Encoder; /** * Use the SecureRandom java security class to generate * a more expensive, but cryptographically secure random number. */ public class SymmetricEncrypt { public static void main( String[] args ) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { final String message1 = "Four score and seven years ago"; //Build a new encryption key final KeyGenerator keyGen = KeyGenerator.getInstance("DESede"); keyGen.init(168); final SecretKey desKey = keyGen.generateKey(); //Set up the cipher final Cipher desCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); ////////////////////////////////////// //Put the cipher in encryption mode desCipher.init(Cipher.ENCRYPT_MODE, desKey); //Encrypt and output the base64 data byte[] clearText = message1.getBytes(); byte[] encryptedBytes = desCipher.doFinal(clearText); BASE64Encoder b64e = new sun.misc.BASE64Encoder();
  83. 83. { final String message1 = "Four score and seven years ago"; //Build a new encryption key final KeyGenerator keyGen = KeyGenerator.getInstance("DESede"); keyGen.init(168); final SecretKey desKey = keyGen.generateKey(); //Set up the cipher final Cipher desCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); ////////////////////////////////////// //Put the cipher in encryption mode desCipher.init(Cipher.ENCRYPT_MODE, desKey); //Encrypt and output the base64 data byte[] clearText = message1.getBytes(); byte[] encryptedBytes = desCipher.doFinal(clearText); BASE64Encoder b64e = new sun.misc.BASE64Encoder(); String base64Encrypted = b64e.encode(encryptedBytes); System.out.println("Encrypted text: " + base64Encrypted); ////////////////////////////////////// //Put the cipher in decryption mode desCipher.init(Cipher.DECRYPT_MODE, desKey); //Decrypt and output the original string byte[] decryptedBytes = desCipher.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Decrypted text: " + decryptedText); } }
  84. 84. //Set up the cipher final Cipher desCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); ////////////////////////////////////// //Put the cipher in encryption mode desCipher.init(Cipher.ENCRYPT_MODE, desKey); //Encrypt and output the base64 data byte[] clearText = message1.getBytes(); byte[] encryptedBytes = desCipher.doFinal(clearText); BASE64Encoder b64e = new sun.misc.BASE64Encoder(); String base64Encrypted = b64e.encode(encryptedBytes); System.out.println("Encrypted text: " + base64Encrypted); ////////////////////////////////////// //Put the cipher in decryption mode desCipher.init(Cipher.DECRYPT_MODE, desKey); //Decrypt and output the original string byte[] decryptedBytes = desCipher.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Decrypted text: " + decryptedText); } }
  85. 85. Input String message1 = "Four score and seven years ago"; Result Encrypted text: P0FT6N3XXrohtsz7OLh3FGYY0wErkPIur1DP6Csbj4g= Decrypted text: Four score and seven years ago
  86. 86. Encrypted isn’t enough? http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation
  87. 87. ASYMMETRIC Throwing away keys faster than an intern locksmith
  88. 88. Diffie-Hellman ! Key Agreement Protocol ! Alice & Bob independently generate the shared (session) key ! asymmetric Key handshake ! 1970s ! Vulnerable to MITM attack ! Fixed by ! PKI ! signing the agreed key
  89. 89. DH Diagrammed
  90. 90. RSA ! Ron Rivest, Adi Shamir, Leonard Adleman ! Published in 1978 ! M.I.T. Patented in 1983 ! Patent Expired in 2000
  91. 91. import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import sun.misc.BASE64Encoder; /** * Use the SecureRandom java security class to generate * a more expensive, but cryptographically secure random number.
  92. 92. { public static void main( String[] args ) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { final String message1 = "Four score and seven years ago"; // Generate the Key Pair final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(1024, random); KeyPair pair = keyGen.generateKeyPair(); final PrivateKey privKey = pair.getPrivate(); final PublicKey pubKey = pair.getPublic(); //Encrypt using the private key Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsa.init(Cipher.ENCRYPT_MODE, privKey); byte[] encryptedBytes = rsa.doFinal(message1.getBytes()); BASE64Encoder b64e = new sun.misc.BASE64Encoder();
  93. 93. keyGen.initialize(1024, random); KeyPair pair = keyGen.generateKeyPair(); final PrivateKey privKey = pair.getPrivate(); final PublicKey pubKey = pair.getPublic(); //Encrypt using the private key Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsa.init(Cipher.ENCRYPT_MODE, privKey); byte[] encryptedBytes = rsa.doFinal(message1.getBytes()); BASE64Encoder b64e = new sun.misc.BASE64Encoder(); String base64Encrypted = b64e.encode(encryptedBytes); System.out.println("Encrypted text: " + base64Encrypted); //Decrypt using the private key rsa.init(Cipher.DECRYPT_MODE, pubKey); byte[] decryptedBytes = rsa.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Decrypted text: " + decryptedText); } }
  94. 94. final PrivateKey privKey = pair.getPrivate(); final PublicKey pubKey = pair.getPublic(); //Encrypt using the private key Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsa.init(Cipher.ENCRYPT_MODE, privKey); byte[] encryptedBytes = rsa.doFinal(message1.getBytes()); BASE64Encoder b64e = new sun.misc.BASE64Encoder(); String base64Encrypted = b64e.encode(encryptedBytes); System.out.println("Encrypted text: " + base64Encrypted); //Decrypt using the private key rsa.init(Cipher.DECRYPT_MODE, pubKey); byte[] decryptedBytes = rsa.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Decrypted text: " + decryptedText); } }
  95. 95. Input String message1 = "Four score and seven years ago"; Result Encrypted text: A8Is+4r7sDn28fD6IQvZiR5JxPs/vh7UnXrF38acJt6R/ ARisj/zLtC7Xn6iJgNQPhc16wkVZhCF em7oNoim+ooTUDDZQ+E3qP6y/ DZJGkLBoZuZVLeLAW1LUtHSzduRUOg1uMynJz14wxzwfV8wfRwf atpySkOhGqWS63bPNRs= Decrypted text: Four score and seven years ago
  96. 96. OTHER FRAMEWORKS and alternative JCE providers
  97. 97. Bouncy Castle ! JCE Provider ! Many more encryption and digest algorithms than the Sun provider (AES)
  98. 98. Jasypt
  99. 99. Jasypt Frictionless Java encryption
  100. 100. Gnu
  101. 101. Gnu Open source library
  102. 102. WIFI You are the weakest link
  103. 103. WIFI Algorithms !WEP
  104. 104. WIFI Algorithms !WEP !WPA
  105. 105. WIFI Algorithms !WEP !WPA !WPA2
  106. 106. WIFI Algorithms !WEP !WPA !WPA2 TKIP AES
  107. 107. WIFI Algorithms !WEP !WPA TKIP !WPA2 AES
  108. 108. TJ Maxx
  109. 109. TJ Maxx ! $1 billon USD final cost ! 45 million credit card numbers stolen
  110. 110. riticized the s have c “ Many secur strength o ity expert f WEP enc 2 ry m ption. WEP ost recent 001, and st month cracked in archers la w ly as initially broken by G erman rese ord inary usin g an three top in under lap seconds et UK — Tom Espiner, ZDN ”
  111. 111. WIFI Interception ! Hey Look! A MyFreeWIFI SSID... ! Tempting ! Ridiculously unsafe
  112. 112. Tools of the Trade ! AirCrack ! AirSnort ! WireShark ! Silent Proxies
  113. 113. WEP Cracking ! Listen for packets ! Slow ! Untraceable ! Inject bad packets ! Listen for reply ! Faster ! leaves a footprint
  114. 114. WireShark Demo
  115. 115. Upside-Down-Ternet Demo
  116. 116. PRINTED MATERIALS Dead tree propagation of security
  117. 117. 1997
  118. 118. 19981.2 Java 11& .
  119. 119. 2004 Java 14 .
  120. 120. 2005 Java 5
  121. 121. 2008
  122. 122. ENCRYPTION B O O T C AM P ted sion comple security mis
  123. 123. ENCRYPTION B O O T C AM P ted sion comple security mis @matthewmccull #EncryptBC matthewm@ambientideas.com http://ambientideas.com/blog http://speakerrate.com/matthew.mccullough
  124. 124. REFERENCES
  125. 125. References ! Sun docs ! http://java.sun.com/javase/6/docs/technotes/ guides/security/crypto/CryptoSpec.html ! http://java.sun.com/javase/technologies/security/ ! http://java.sun.com/javase/6/docs/technotes/ guides/security/jsse/JSSERefGuide.html ! http://java.sun.com/javase/6/docs/api/java/ security/Security.html ! BouncyCastle JCE Provider ! http://www.bouncycastle.org/documentation.html
  126. 126. References ! Sample Code ! http://github.com/matthewmccullough/ encryption-jvm-bootcamp ! Miscellaneous ! http://www.ietf.org/rfc/rfc3852.txt ! http://en.wikipedia.org/wiki/ Abstract_Syntax_Notation_One
  127. 127. Acronyms ! CMS ! Cryptographic Message Syntax (CMS) objects ! RFC 3852 ! PKCS#7 (formerly RFC 2630, 3369) ! http://www.ietf.org/rfc/rfc3852.txt ! ASN.1 ! Abstract Syntax Notation One ! 1984 X.409, 1988 X.208, 1995 X.680, 2002 ! http://www.asn1.org/
  128. 128. CREDITS
  129. 129. ! http://www.ambientideasphotography.com ! http://stockfootageforfree.com/ ! http://xkcd.com/538/ ! http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation ! http://matdonline.free.fr/RSA-Diffie-Hellman-explained-in-5- minutes.htm ! http://www.isg.rhul.ac.uk/node/329 ! http://www.isg.rhul.ac.uk/files/IMG_9819.JPG ! http://www.usc.edu/dept/molecular-science/pictures/RSA-2003.jpg ! All others, iStockPhoto.com
  130. 130. Outtakes
  131. 131. Steganography ! Data in pictures ! Not necessarily encrypted ! Merely hidden in pedestrian files
  132. 132. Steganography ! MP3 ! JPEG ! DIVX ! TCP Retry Packets ! Email Headers
  133. 133. Steganography ! High signal to noise ratio ! Slow but ! Inconspicuous
  134. 134. Cracks in the News ! Thomas Jefferson letter ! London Tube Oyster cards ! GSM ! Iraq drone video feeds ! Pacemakers ! Zune ! WPA ! Blue-ray ! DVD ! Skype ! Windows Vista BitLocker
  135. 135. Encryption & The Law ! Encryption considered a munition under international law ! 1999 Relaxation of rules
  136. 136. Digital Signatures ! Hash with Private Key ! Public Private Key Systems ! Public Key Infrastructure (PKI)
  137. 137. Breakthroughs ! IBM ! Statistics on encrypted data ! No compromise on security or anonymity
  138. 138. Keys ! Clickers/Tokens ! One Time Pads (paper)
  139. 139. Misc ! Message Digests == Hash? ! Certificates (x509 v3) ! Digital signatures ! Just means hashing a message, then signing the hash with the private key ! Later verified by decrypting the hash with the public key, then re-running the hash and comparing the two hashes. ! Block vs Stream ciphers
  140. 140. Cryptographic Message Syntax
  141. 141. Cryptographic Message Syntax Sign / Digest / Auth / Encrypt
  142. 142. Session Keys ! symmetric key exchanged securely by a private/public key initial transaction
  143. 143. Elliptic Curve ! Faster than standard public key encryption ! ECC ! Based on elliptic curve logarithm problem
  144. 144. B OOT C AM P Y PTIiONour mission NCRurity s y E ec s © Matthew McCullough, Ambient Ideas, LLC Friday, January 15, 2010 1
  145. 145. SECURITY What’s ON THE J your po VM sition? Friday, January 15, 2010 2
  146. 146. HACK ATT EMPTS PE R >3 00,00 D AY 0 Friday, January 15, 2010 3
  147. 147. TING? not ENCRayP robably ss Y p ic statist Friday, January 15, 2010 4
  148. 148. ? RIEDbe WOR You should Friday, January 15, 2010 5
  149. 149. Matthew McCullough @matthewmccull #EncryptBC http://speakerrate.com/matthew.mccullough Friday, January 15, 2010 6
  150. 150. ANCIENT HISTORY Everything old is new again Friday, January 15, 2010 7
  151. 151. Recipient or Storage ht Sig ur ed ain c bs O ts Pl en o nt C Sensitive Data Friday, January 15, 2010 8 Craziest idea ever! Everyone knows you need to keep secret information hidden in a body cavity and physically transport it to the recipient. All the movies do that.
  152. 152. er ll ov “I’m a ew n thisryption enc ff boss” stu Friday, January 15, 2010 9 Even though we make minor adjustments, they are often seeded by our predecessors. Even encryption is over old with a fresh coat of paint
  153. 153. 44 B.C. That’s 2,054 years ago... Friday, January 15, 2010 10
  154. 154. Julius Caesar Friday, January 15, 2010 11 And even the Egyptians before him were trying math for encryption. http://www.amazon.com/Code-Book-Science-Secrecy-Cryptography/ dp/0385495323/ref=sr_1_7? ie=UTF8&s=books&qid=1263535206&sr=8-7
  155. 155. Caesar Cipher a.k.a. ROT(2) Shift Cipher A B C D E F G A B C D E F G Friday, January 15, 2010 12
  156. 156. Caesar Cipher Rotation = Integer Rot(x) Friday, January 15, 2010 13
  157. 157. Caesar Cipher Encrypted Word Z M S R A N T S if encrypted with ROT(-1) B O U T if encrypted with ROT(-2) 30s 25s 20s 15s 10s 5s Stop Friday, January 15, 2010 14 This is not an eye test at your optometrist English dictionary attack would be a good approach. ANTS and BOUT are solutions [ROT(+1) and ROT(+2)]
  158. 158. /** * A naively simple rotation cipher implementation. * USAGE: groovy RotateWord.groovy <yourword> */ public class RotateWord { /** * Rotate one character by the specified amount */ private static char rotateChar(char c, int rotationAmount) { //a == 97, z == 122 int num = (int)c int rotated = num + rotationAmount int adjusted //Handle roll-around wrapping Friday, January=>rotated - 26 if (rotated 122) adjusted 15, 2010 15 else if (rotated < 97) Look at how much effort it is to write even the simplest cipher (Caesar) adjusted = rotated + 26 else implementation ourselves.adjusted = rotated char adjustedChar = (char)adjusted return adjustedChar } /** * Rotate the entire String by the specified rotation amount. */ public static String rotateAllChars(String plainText, int rotationAmount) { String encodedMessage = "" //Loop through each character in the plaintext for (int i = 0; i < plainText.length(); i++) { //TODO: Improve to handle upper and lower case letters char c = plainText.toLowerCase().charAt(i) encodedMessage += rotateChar(c, rotationAmount) }
  159. 159. > groovy RotateWord.groovy ants Rot(-3) Word: xkqp Rot(-2) Word: ylrq Rot(-1) Word: zmsr Original Word: ants Rot(1) Word: bout Rot(2) Word: cpvu Rot(3) Word: dqwv Friday, January 15, 2010 16 Think about the combinatoric and steganographic possibilities.
  160. 160. BROKEN Perfectly safe data is a myth Friday, January 15, 2010 17
  161. 161. Compromised ! Every algorithm is vulnerable ! crack by brute force ! Crack by rainbow tables ! Function of time + money + hardware Friday, January 15, 2010 18
  162. 162. $2000 Whic h wo uld 0 you $50 hit? Friday, January 15, 2010 19 Go into a jewelry store. Two possible storage containers to hit. Your informant has told you how much is in each. 4X as much in the safe as in the wooden box.
  163. 163. $10,000 Now whic h wo uld 0 you $5 hit? Friday, January 15, 2010 20 Now the jewelry box contains 1/200th what the safe does. Would you still hit the wooden box?
  164. 164. JCE PRIMER The world of Java crypto Friday, January 15, 2010 21
  165. 165. Java Cryptography Extension known as JCE included in all JREs Since Java 1.2 Pluggable provider architecture JCE extends Java Cryptography Architecture (JCA) Friday, January 15, 2010 22
  166. 166. JCE Providers ! Default Sun JRE providers ! SUN ! SunJCE ! SunJSSE ! SunRsaSign ! Bouncycastle provider ! Adds AES capabilities Friday, January 15, 2010 23
  167. 167. Registering a Provider ! Static ! <java-home>/lib/security/java.security ! security.provider.n=masterClassName Friday, January 15, 2010 24
  168. 168. Registering a Provider ! Dynamic ! java.security.Security class ! addProvider() ! insertProviderAt() ! not persistent across VM instances Friday, January 15, 2010 25 Can only be done by "trusted" programs with the appropriate privilege
  169. 169. EnCryption & the Law country borders stop bits Friday, January 15, 2010 26
  170. 170. JCE Strength ! Jurisdiction Policy Files ! “Strong” ! “Unlimited” Friday, January 15, 2010 27
  171. 171. JCE Strength ! Strong strength included in all JREs ! Unlimited strength is a separate download available based on US export rules Friday, January 15, 2010 28
  172. 172. Friday, January 15, 2010 29
  173. 173. Friday, January 15, 2010 30
  174. 174. Worldwide Policy // File: default_local.policy // Some countries have import limits on crypto strength. // This policy file is worldwide importable. grant { permission javax.crypto.CryptoPermission "DES", 64; permission javax.crypto.CryptoPermission "DESede", *; permission javax.crypto.CryptoPermission "RC2", 128, "javax.crypto.spec.RC2ParameterSpec", 128; permission javax.crypto.CryptoPermission "RC4", 128; permission javax.crypto.CryptoPermission "RC5", 128, "javax.crypto.spec.RC5ParameterSpec", *, 12, *; permission javax.crypto.CryptoPermission "RSA", 2048; permission javax.crypto.CryptoPermission *, 128; }; Friday, January 15, 2010 31
  175. 175. Max Key Sizes Algorithm Max Key Size DES 64 DESede 168 3des RC2 128 RC4 128 RC5 128 RSA 2048 Others 128 Friday, January 15, 2010 32 http://java.sun.com/j2se/1.4.2/docs/guide/security/jce/ JCERefGuide.html#AppE
  176. 176. Key Size & Security 1024 bit RSA Asymmetric Key Size 160 bit DES Symmetric Key Size 112 bits 128 bits Security Security Friday, January 15, 2010 33 Speed is 1000x slower on asymmetric
  177. 177. Random Numbers Seed the machine Friday, January 15, 2010 34
  178. 178. SecureRandom ! java.security.SecureRandom ! Cryptographically strong random number generator (RNG) ! “Unable to distinguish from a true random source” Friday, January 15, 2010 35 A cryptographically strong random number generator passes all statistical tests that run in polynomial time asymptotically. It will pass any statistical test for randomness that does not require an exponentially increasing to infinite amount of time to run. All such polynomial time statistical tests will be unable to distinguish the random number generator from a true random source. http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#Concepts http://java.sun.com/javase/6/docs/api/java/security/SecureRandom.html http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#AppA
  179. 179. package com.ambientideas; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /** * Use the SecureRandom java security class to generate * a more expensive, but cryptographically secure random number. */ public class SecureRandomNumber { public static void main( String[] args ) throws NoSuchAlgorithmException { //Do the expensive one time setup of the // random number generator instance Friday, January 15, 2010 = SecureRandom.getInstance("SHA1PRNG"); SecureRandom prng 36 //Get the next random number String randomNum = new Integer( prng.nextInt() ).toString(); System.out.println("Random number: " + randomNum); } }
  180. 180. import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /** * Use the SecureRandom java security class to generate * a more expensive, but cryptographically secure random number. */ public class SecureRandomNumber { public static void main( String[] args ) throws NoSuchAlgorithmException { //Do the expensive one time setup of the // random number generator instance SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); //Get the next random number String randomNum = new Integer( prng.nextInt() ).toString(); System.out.println("Random number: " + randomNum); } } Friday, January 15, 2010 37
  181. 181. * Use the SecureRandom java security class to generate * a more expensive, but cryptographically secure random number. */ public class SecureRandomNumber { public static void main( String[] args ) throws NoSuchAlgorithmException { //Do the expensive one time setup of the // random number generator instance SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); //Get the next random number String randomNum = new Integer( prng.nextInt() ).toString(); System.out.println("Random number: " + randomNum); } } Friday, January 15, 2010 38
  182. 182. Result Random number: 1633471380 Friday, January 15, 2010 39
  183. 183. Digests & Hashes One way functions Friday, January 15, 2010 40
  184. 184. What is a Digest? ! Small set of bytes representing a large message ! Small change in message = large change in digest ! Integrity check for large data ! Password storage mechanism Friday, January 15, 2010 41 OWASP says passwords should never be stored in plaintext http://www.owasp.org/index.php/Hashing_Java
  185. 185. MessageDigest ! java.security.MessageDigest ! Multiple algorithms available ! MD5 (128 bit) ! SHA-1 (160 bit) Friday, January 15, 2010 42
  186. 186. MessageDigest ! ! MD5 U. S. Department of Homeland Security said MD5 "considered cryptographically broken and unsuitable for further use" Friday, January 15, 2010 43 http://en.wikipedia.org/wiki/MD5
  187. 187. http://xkcd.com/538/ Friday, January 15, 2010 44 $5 wrench XKCD: http://xkcd.com/538/ Missy Elliott XKCD: http://xkcd.com/153/
  188. 188. System.out.println("Message1 SHA1 digest: " + shaAndBase64Encode(message1)); System.out.println("Message2 SHA1 digest: " + shaAndBase64Encode(message2)); } /** * Helper function to both SHA-1 hash and * base64 encode the resulting bytes to a String */ public static String shaAndBase64Encode(String message) throws NoSuchAlgorithmException { MessageDigest sha = MessageDigest.getInstance("SHA-1"); //Salt could be applied here //Integer salt = <some random number generator> //sha.update(salt.getBytes()); byte[] digest = sha.digest(message.getBytes()); return new sun.misc.BASE64Encoder().encode(digest); } } Friday, January 15, 2010 45
  189. 189. * Digest a string message via SHA1. * * Demonstrate that very similar messages * have radically different hashes. */ public class MessageDigestSHA { public static void main( String[] args ) throws NoSuchAlgorithmException { //Set up the message to be encoded String message1 = "Four score and seven years ago"; String message2 = "Four score and seven tears ago"; System.out.println("Message1 SHA1 digest: " + shaAndBase64Encode(message1)); System.out.println("Message2 SHA1 digest: " + shaAndBase64Encode(message2)); } /** * Helper function to both SHA-1 hash and * base64 encode the resulting bytes to a String */ public static String shaAndBase64Encode(String message) throws NoSuchAlgorithmException { MessageDigest sha = MessageDigest.getInstance("SHA-1"); Friday, January 15, 2010 46 //Salt could be applied here //Integer salt = <some random number generator> //sha.update(salt.getBytes()); byte[] digest = sha.digest(message.getBytes()); return new sun.misc.BASE64Encoder().encode(digest); } }
  190. 190. Input String message1 = "Four score and seven years ago"; String message2 = "Four score and seven tears ago"; Result Message1 SHA1 digest: DmCJIg4Bq/xpGIxVXxo3IB0vo38= Message2 SHA1 digest: oaLHt8tr31ttngCDjyYuWowF5Mc= Friday, January 15, 2010 47
  191. 191. JDK Keytool Key generation, storage & management Friday, January 15, 2010 48
  192. 192. Keytool ! Creates ! Keystore ! Truststore ! Functions ! -genkey ! -list ! -import ! -export ! -certreq Friday, January 15, 2010 49
  193. 193. Creating a keystore keytool -genkeypair -keyalg RSA -keysize 2048 - keystore myapp.keystore Enter keystore password: ******** Re-enter new password: ******** What is your first and last name? [Unknown]: Matthew McCullough What is the name of your organizational unit? [Unknown]: Consulting What is the name of your organization? [Unknown]: Ambient Ideas, LLC What is the name of your City or Locality? [Unknown]: Denver What is the name of your State or Province? [Unknown]: Colorado What is the two-letter country code for this unit? [Unknown]: US Is CN=Matthew McCullough, OU=Consulting, O="Ambient Friday, January 15, L=Denver, ST=Colorado, C=US correct? Ideas, LLC", 2010 50 [no]: yes Enter key password for <mykey> ! (RETURN if same as keystore password):
  194. 194. keytool -genkeypair -keyalg RSA -keysize 2048 - Creating a keystore keystore myapp.keystore Enter keystore password: ******** Re-enter new password: ******** What is your first and last name? [Unknown]: Matthew McCullough What is the name of your organizational unit? [Unknown]: Consulting What is the name of your organization? [Unknown]: Ambient Ideas, LLC What is the name of your City or Locality? [Unknown]: Denver What is the name of your State or Province? [Unknown]: Colorado What is the two-letter country code for this unit? [Unknown]: US Is CN=Matthew McCullough, OU=Consulting, O="Ambient Ideas, LLC", L=Denver, ST=Colorado, C=US correct? [no]: yes Enter key password for <mykey> ! (RETURN if same as keystore password): Friday, January 15, 2010 51
  195. 195. Using a keystore java -Djavax.net.ssl.keyStore=keystore -Djavax.net.ssl.keyStorePassword=y3$1t1s ServerApp Using a Truststore java -Djavax.net.ssl.trustStore=truststore -Djavax.net.ssl.trustStorePassword=tru$tM3 ClientApp Friday, January 15, 2010 52
  196. 196. JSSE Network communications security Friday, January 15, 2010 53
  197. 197. JSSE ! Java Secure Socket Extension ! Built on top of JCE ! Specific to networking ! Standard as of JRE 1.4 ! Implementations of ! Secure Sockets Layer (SSL) 2.0 and 3.0 ! Transport Layer Security (TLS) 1.0 Friday, January 15, 2010 54 http://java.sun.com/j2se/1.4.2/docs/guide/security/jsse/JSSERefGuide.html Previously an optional add on up through JRE 1.3 http://en.wikipedia.org/wiki/Transport_Layer_Security TLS 1.0 in 1999. Improvements to SSL 3.0 (1996)
  198. 198. JAAS Authentication and Authorization Friday, January 15, 2010 55
  199. 199. JAAS ! Java Authentication and Authorization Service ! Single sign on helper ! Supports biometric, smartcard devices ! Adds “user” control (above code control) Friday, January 15, 2010 56
  200. 200. SYMMETRIC My key is your key Friday, January 15, 2010 57
  201. 201. Why Symmetric? ! Fast ! Bulk data ! Controlled environment ! Never decrypted at remote end Friday, January 15, 2010 58
  202. 202. Symmetric Problems ! Keys vulnerable to capture ! Eavesdropping on future communications after key compromise ! Key distribution challenges ! Triangular number key growth Friday, January 15, 2010 59 How do you distribute keys? System-wide number of keys for N nodes to talk securely to any node is Tn http://mathworld.wolfram.com/TriangularNumber.html
  203. 203. Symmetric Problems ! Triangular number key growth Friday, January 15, 2010 60
  204. 204. DES & 3DES ! Block cipher ! DES is known to be broken ! 3DES and DESede ! basically three passes of DES ! Reasonably strong Friday, January 15, 2010 61
  205. 205. Blowfish ! Secure replacement for DES ! Faster than DES ! Block cipher Friday, January 15, 2010 62 Sounds like a new flavor of Ben and Jerry’s ice cream
  206. 206. RC4 ! Rivest’s code 4 ! Stream cipher Friday, January 15, 2010 63
  207. 207. AES ! Advanced Encryption Standard ! Government standard ! Rijndael algorithm (Joan Daemen, Vincent Rijmen) ! 4 years of evaluation ! Final in December 2000 ! Very Secure ! block cipher Friday, January 15, 2010 64
  208. 208. import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import sun.misc.BASE64Encoder; /** * Use the SecureRandom java security class to generate * a more expensive, but cryptographically secure random number. */ public class SymmetricEncrypt { public static void main( String[] args ) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { final String message1 = "Four score and seven years ago"; Friday, Januarya15, 2010 //Build new encryption key 65 final KeyGenerator keyGen = KeyGenerator.getInstance("DESede"); keyGen.init(168); final SecretKey desKey = keyGen.generateKey(); //Set up the cipher final Cipher desCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); ////////////////////////////////////// //Put the cipher in encryption mode desCipher.init(Cipher.ENCRYPT_MODE, desKey); //Encrypt and output the base64 data byte[] clearText = message1.getBytes(); byte[] encryptedBytes = desCipher.doFinal(clearText); BASE64Encoder b64e = new sun.misc.BASE64Encoder(); String base64Encrypted = b64e.encode(encryptedBytes); System.out.println("Encrypted text: " + base64Encrypted); ////////////////////////////////////// //Put the cipher in decryption mode desCipher.init(Cipher.DECRYPT_MODE, desKey); //Decrypt and output the original string byte[] decryptedBytes = desCipher.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Decrypted text: " + decryptedText); } }
  209. 209. import javax.crypto.SecretKey; import sun.misc.BASE64Encoder; /** * Use the SecureRandom java security class to generate * a more expensive, but cryptographically secure random number. */ public class SymmetricEncrypt { public static void main( String[] args ) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { final String message1 = "Four score and seven years ago"; //Build a new encryption key final KeyGenerator keyGen = KeyGenerator.getInstance("DESede"); keyGen.init(168); final SecretKey desKey = keyGen.generateKey(); //Set up the cipher final Cipher desCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); ////////////////////////////////////// //Put the cipher in encryption mode desCipher.init(Cipher.ENCRYPT_MODE, desKey); //Encrypt and output the base64 data byte[] clearText = message1.getBytes(); byte[] encryptedBytes = desCipher.doFinal(clearText); BASE64Encoder b64e = new sun.misc.BASE64Encoder(); String base64Encrypted = b64e.encode(encryptedBytes); Friday, January 15, 2010 System.out.println("Encrypted text: " + base64Encrypted); 66 ////////////////////////////////////// //Put the cipher in decryption mode desCipher.init(Cipher.DECRYPT_MODE, desKey); //Decrypt and output the original string byte[] decryptedBytes = desCipher.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Decrypted text: " + decryptedText); } }
  210. 210. { final String message1 = "Four score and seven years ago"; //Build a new encryption key final KeyGenerator keyGen = KeyGenerator.getInstance("DESede"); keyGen.init(168); final SecretKey desKey = keyGen.generateKey(); //Set up the cipher final Cipher desCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); ////////////////////////////////////// //Put the cipher in encryption mode desCipher.init(Cipher.ENCRYPT_MODE, desKey); //Encrypt and output the base64 data byte[] clearText = message1.getBytes(); byte[] encryptedBytes = desCipher.doFinal(clearText); BASE64Encoder b64e = new sun.misc.BASE64Encoder(); String base64Encrypted = b64e.encode(encryptedBytes); System.out.println("Encrypted text: " + base64Encrypted); ////////////////////////////////////// //Put the cipher in decryption mode desCipher.init(Cipher.DECRYPT_MODE, desKey); //Decrypt and output the original string byte[] decryptedBytes = desCipher.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Decrypted text: " + decryptedText); } } Friday, January 15, 2010 67
  211. 211. //Set up the cipher final Cipher desCipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); ////////////////////////////////////// //Put the cipher in encryption mode desCipher.init(Cipher.ENCRYPT_MODE, desKey); //Encrypt and output the base64 data byte[] clearText = message1.getBytes(); byte[] encryptedBytes = desCipher.doFinal(clearText); BASE64Encoder b64e = new sun.misc.BASE64Encoder(); String base64Encrypted = b64e.encode(encryptedBytes); System.out.println("Encrypted text: " + base64Encrypted); ////////////////////////////////////// //Put the cipher in decryption mode desCipher.init(Cipher.DECRYPT_MODE, desKey); //Decrypt and output the original string byte[] decryptedBytes = desCipher.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Decrypted text: " + decryptedText); } } Friday, January 15, 2010 68
  212. 212. Input String message1 = "Four score and seven years ago"; Result Encrypted text: P0FT6N3XXrohtsz7OLh3FGYY0wErkPIur1DP6Csbj4g= Decrypted text: Four score and seven years ago Friday, January 15, 2010 69
  213. 213. Encrypted isn’t enough? http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation Friday, January 15, 2010 70 http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation
  214. 214. ASYMMETRIC Throwing away keys faster than an intern locksmith Friday, January 15, 2010 71
  215. 215. Friday, January 15, 2010 72 http://www.isg.rhul.ac.uk/node/329 http://www.isg.rhul.ac.uk/files/IMG_9819.JPG http://en.wikipedia.org/wiki/Diffie
  216. 216. Diffie-Hellman ! Key Agreement Protocol ! Alice & Bob independently generate the shared (session) key ! asymmetric Key handshake ! 1970s ! Vulnerable to MITM attack ! Fixed by ! PKI ! signing the agreed key Friday, January 15, 2010 73 http://en.wikipedia.org/wiki/Diffie–Hellman_key_exchange
  217. 217. DH Diagrammed Friday, January 15, 2010 74 http://matdonline.free.fr/RSA-Diffie-Hellman-explained-in-5- minutes.htm
  218. 218. Friday, January 15, 2010 75 RSA http://www.usc.edu/dept/molecular-science/pictures/RSA-2003.jpg
  219. 219. RSA ! Ron Rivest, Adi Shamir, Leonard Adleman ! Published in 1978 ! M.I.T. Patented in 1983 ! Patent Expired in 2000 Friday, January 15, 2010 76 Not patented in many other countries due to paper published before patent. There was later found to be prior art might not have allowed this to get patented at all.
  220. 220. import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import sun.misc.BASE64Encoder; /** * Use the SecureRandom java security class to generate * a more expensive, but cryptographically secure random number. */ Friday,public class EncryptRSA January 15, 2010 77 { public static void main( String[] args ) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { final String message1 = "Four score and seven years ago"; // Generate the Key Pair final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(1024, random); KeyPair pair = keyGen.generateKeyPair(); final PrivateKey privKey = pair.getPrivate(); final PublicKey pubKey = pair.getPublic(); //Encrypt using the private key Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  221. 221. { public static void main( String[] args ) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { final String message1 = "Four score and seven years ago"; // Generate the Key Pair final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(1024, random); KeyPair pair = keyGen.generateKeyPair(); final PrivateKey privKey = pair.getPrivate(); final PublicKey pubKey = pair.getPublic(); //Encrypt using the private key Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsa.init(Cipher.ENCRYPT_MODE, privKey); byte[] encryptedBytes = rsa.doFinal(message1.getBytes()); BASE64Encoder b64e = new sun.misc.BASE64Encoder(); String base64Encrypted = b64e.encode(encryptedBytes); Friday, January 15, 2010 System.out.println("Encrypted text: " + base64Encrypted); 78 //Decrypt using the private key rsa.init(Cipher.DECRYPT_MODE, pubKey); byte[] decryptedBytes = rsa.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Decrypted text: " + decryptedText); } }
  222. 222. keyGen.initialize(1024, random); KeyPair pair = keyGen.generateKeyPair(); final PrivateKey privKey = pair.getPrivate(); final PublicKey pubKey = pair.getPublic(); //Encrypt using the private key Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsa.init(Cipher.ENCRYPT_MODE, privKey); byte[] encryptedBytes = rsa.doFinal(message1.getBytes()); BASE64Encoder b64e = new sun.misc.BASE64Encoder(); String base64Encrypted = b64e.encode(encryptedBytes); System.out.println("Encrypted text: " + base64Encrypted); //Decrypt using the private key rsa.init(Cipher.DECRYPT_MODE, pubKey); byte[] decryptedBytes = rsa.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Decrypted text: " + decryptedText); } } Friday, January 15, 2010 79
  223. 223. final PrivateKey privKey = pair.getPrivate(); final PublicKey pubKey = pair.getPublic(); //Encrypt using the private key Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsa.init(Cipher.ENCRYPT_MODE, privKey); byte[] encryptedBytes = rsa.doFinal(message1.getBytes()); BASE64Encoder b64e = new sun.misc.BASE64Encoder(); String base64Encrypted = b64e.encode(encryptedBytes); System.out.println("Encrypted text: " + base64Encrypted); //Decrypt using the private key rsa.init(Cipher.DECRYPT_MODE, pubKey); byte[] decryptedBytes = rsa.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Decrypted text: " + decryptedText); } } Friday, January 15, 2010 80
  224. 224. Input String message1 = "Four score and seven years ago"; Result Encrypted text: A8Is+4r7sDn28fD6IQvZiR5JxPs/vh7UnXrF38acJt6R/ ARisj/zLtC7Xn6iJgNQPhc16wkVZhCF em7oNoim+ooTUDDZQ+E3qP6y/ DZJGkLBoZuZVLeLAW1LUtHSzduRUOg1uMynJz14wxzwfV8wfRwf atpySkOhGqWS63bPNRs= Decrypted text: Four score and seven years ago Friday, January 15, 2010 81
  225. 225. OTHER FRAMEWORKS and alternative JCE providers Friday, January 15, 2010 82
  226. 226. Bouncy Castle ! JCE Provider ! Many more encryption and digest algorithms than the Sun provider (AES) Friday, January 15, 2010 83 http://www.mobilefish.com/developer/bouncycastle/ bouncycastle_quickguide_install.html
  227. 227. Jasypt Frictionless Java encryption Friday, January 15, 2010 84 Works beautifully with Hibernate and The Spring Framework
  228. 228. Gnu Open source library Friday, January 15, 2010 85 Hundreds of algorithms implemented http://www.gnu.org/software/gnu-crypto/
  229. 229. WIFI You are the weakest link Friday, January 15, 2010 86
  230. 230. WIFI Algorithms ! WEP ! WPA ! WPA2 TKIP AES Friday, January 15, 2010 87 WEP can be sniffed for keys WPA2 implements the mandatory elements of 802.11i
  231. 231. TJ Maxx Friday, January 15, 2010 88
  232. 232. TJ Maxx ! $1 billon USD final cost ! 45 million credit card numbers stolen Friday, January 15, 2010 89
  233. 233. the criticized rts have “ Ma s ny securit trength of cracked y expe tion. WEP w as initially WEP encryp recently broken by and most in 2001, last month ordinary searchers German re u s i n g a nunder three laptop in seconds et UK — Tom Esp iner, ZDN ” Friday, January 15, 2010 90 http://www.zdnetasia.com/news/security/ 0,39044215,62011583,00.htm
  234. 234. WIFI Interception ! Hey Look! A MyFreeWIFI SSID... ! Tempting ! Ridiculously unsafe Friday, January 15, 2010 91
  235. 235. Tools of the Trade ! AirCrack ! AirSnort ! WireShark ! Silent Proxies Friday, January 15, 2010 92
  236. 236. WEP Cracking ! Listen for packets ! Slow ! Untraceable ! Inject bad packets ! Listen for reply ! Faster ! leaves a footprint Friday, January 15, 2010 93
  237. 237. WireShark Demo Friday, January 15, 2010 94 http://www.wireshark.org/
  238. 238. Upside-Down-Ternet Demo Friday, January 15, 2010 95 http://www.ex-parrot.com/pete/upside-down-ternet.html
  239. 239. Friday, January 15, 2010 96
  240. 240. PRINTED MATERIALS Dead tree propagation of security Friday, January 15, 2010 97
  241. 241. 1997 Friday, January 15, 2010 98
  242. 242. 19981.2 Java 11& . Friday, January 15, 2010 99
  243. 243. 2004 Java 14 . Friday, January 15, 2010 100
  244. 244. 2005 Java 5 Friday, January 15, 2010 101
  245. 245. 2008 Friday, January 15, 2010 102
  246. 246. ENCRYPTION BOOmpleAedP TC M t n co security missio Friday, January 15, 2010 103
  247. 247. ENC RYPTION BOOmpleAedP TC M t n co security missio @matthewmccull #EncryptBC matthewm@ambientideas.com http://ambientideas.com/blog http://speakerrate.com/matthew.mccullough Friday, January 15, 2010 104
  248. 248. REFERENCES Friday, January 15, 2010 105
  249. 249. References ! Sun docs ! http://java.sun.com/javase/6/docs/technotes/ guides/security/crypto/CryptoSpec.html ! http://java.sun.com/javase/technologies/security/ ! http://java.sun.com/javase/6/docs/technotes/ guides/security/jsse/JSSERefGuide.html ! http://java.sun.com/javase/6/docs/api/java/ security/Security.html ! BouncyCastle JCE Provider ! http://www.bouncycastle.org/documentation.html Friday, January 15, 2010 106
  250. 250. References ! Sample Code !http://github.com/matthewmccullough/ encryption-jvm-bootcamp ! Miscellaneous ! http://www.ietf.org/rfc/rfc3852.txt ! http://en.wikipedia.org/wiki/ Abstract_Syntax_Notation_One Friday, January 15, 2010 107
  251. 251. Acronyms ! CMS ! Cryptographic Message Syntax (CMS) objects ! RFC 3852 ! PKCS#7 (formerly RFC 2630, 3369) ! http://www.ietf.org/rfc/rfc3852.txt ! ASN.1 ! Abstract Syntax Notation One ! 1984 X.409, 1988 X.208, 1995 X.680, 2002 ! http://www.asn1.org/ Friday, January 15, 2010 108
  252. 252. CREDITS Friday, January 15, 2010 109
  253. 253. ! http://www.ambientideasphotography.com ! http://stockfootageforfree.com/ ! http://xkcd.com/538/ ! http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation ! http://matdonline.free.fr/RSA-Diffie-Hellman-explained-in-5- minutes.htm ! http://www.isg.rhul.ac.uk/node/329 ! http://www.isg.rhul.ac.uk/files/IMG_9819.JPG ! http://www.usc.edu/dept/molecular-science/pictures/RSA-2003.jpg ! All others, iStockPhoto.com Friday, January 15, 2010 110
  254. 254. Outtakes Friday, January 15, 2010 111
  255. 255. Steganography ! Data in pictures ! Not necessarily encrypted ! Merely hidden in pedestrian files Friday, January 15, 2010 112
  256. 256. Steganography ! MP3 ! JPEG ! DIVX ! TCP Retry Packets ! Email Headers Friday, January 15, 2010 113
  257. 257. Steganography ! High signal to noise ratio ! Slow but ! Inconspicuous Friday, January 15, 2010 114
  258. 258. Cracks in the News ! Thomas Jefferson letter ! London Tube Oyster cards ! GSM ! Iraq drone video feeds ! Pacemakers ! Zune ! WPA ! Blue-ray ! DVD ! Skype ! Windows Vista BitLocker Friday, January 15, 2010 115 Jefferson: All your liberty are belong to us! GSM: Yet another reason to switch away from AT&T Zune: No one cared.
  259. 259. Encryption & The Law ! Encryption considered a munition under international law ! 1999 Relaxation of rules Friday, January 15, 2010 116
  260. 260. Digital Signatures ! Hash with Private Key ! Public Private Key Systems ! Public Key Infrastructure (PKI) Friday, January 15, 2010 117
  261. 261. Breakthroughs ! IBM ! Statistics on encrypted data ! No compromise on security or anonymity Friday, January 15, 2010 118 http://www.net-security.org/secworld.php?id=7690
  262. 262. Keys ! Clickers/Tokens ! One Time Pads (paper) Friday, January 15, 2010 119
  263. 263. Misc ! Message Digests == Hash? ! Certificates (x509 v3) ! Digital signatures ! Just means hashing a message, then signing the hash with the private key ! Later verified by decrypting the hash with the public key, then re-running the hash and comparing the two hashes. ! Block vs Stream ciphers Friday, January 15, 2010 120
  264. 264. Cryptographic Message Syntax Sign / Digest / Auth / Encrypt Friday, January 15, 2010 121
  265. 265. Session Keys ! symmetric key exchanged securely by a private/public key initial transaction Friday, January 15, 2010 122
  266. 266. Elliptic Curve ! Faster than standard public key encryption ! ECC ! Based on elliptic curve logarithm problem Friday, January 15, 2010 123

×