SlideShare une entreprise Scribd logo
1  sur  98
TI
      YP P ON
   C R AM
EN T C
 B OOurity
           is th e mi ssion
 Sec



 @matthewmccull



               © Matthew McCullough, Ambient Ideas, LLC
G? ot
          TINare n
        YP 6%
    ENCR 7  say
statis tics
EA    ED t
                  C H us
  DA TA     BR      nies in j
         o f co mpa      ths
at 8 5%       t 12  Mon
     the  las
Stay out
  of My
Encryption!
Don’t
want my
 help?
  fine.
Final cost was   $1,000,000,000 USD
ANCIENT HISTORY
   Everything old is new again
Recipient
                                           or
                                           Storage

                       ht
                    Sig             r ed
                                  cu


              ain     ts
                           O
                            b   s




            Pl C
                on
                  te
                    n




Sensitive
Data
44 B.C.
 That’s 2,054 years ago...
Julius Caesar
Caesar Cipher
   a.k.a.
     ROT(2)
     Shift Cipher



     A B C D E F G


     A B C D E F G
BROKEN
Perfectly safe data is a myth
Compromised

  Every algorithm is vulnerable
  Crack by real-time brute force
  Crack by pre-computed tables
  Function of
    time + money + hardware
JCE PRIMER
 The world of Java crypto
Java Cryptography Extension


   Known as JCE
   Included in all JREs Since Java 1.2
   Pluggable provider architecture
   JCE extends Java Cryptography
   Architecture (JCA)
JCE Strength


★   Jurisdiction Policy Files
    ★   Two variants
    ★   Algorithm strength differences
JCE Strength

 Strong strength included in all JREs
 Unlimited strength is a separate download
 available based on US export rules
Strong
Unlimite
        d
Strong 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;
};
“Strong” Key Limits
    Algorithm   Max Key Size
      DES           64
     DESede         168
       3des

      RC2           128
      RC4           128
      RC5           128
      RSA          2048
     Others         128
“Unlimited” Key Limits

    Algorithm   Max Key Size
      DES            ∞
     DESede          ∞
       3des

      RC2            ∞
      RC4            ∞
      RC5            ∞
      RSA            ∞
     Others          ∞
Digests &
 Hashes
  One way functions
What is a Hash?

  Small set of bytes representing a large
  message
  Small change in message = large change in
  digest
  Digests also known as a hashes
    Same algorithms, different purposes
What is a Digest?


  Integrity check (MIC) for chunk of data
  or
  Password storage mechanism
MessageDigest

 ★  java.security.MessageDigest
 ★ Many algorithms available
   ★ MD2
   ★ MD5 (128 bit)
   ★ SHA-1 (160 bit)
   ★ SHA-256
   ★ SHA-384
   ★ SHA-512
MessageDigest

 U. S. Department of Homeland
 Security said MD5 is

 "considered cryptographically broken
 and unsuitable for further use"
download.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html
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);
    }
}
*
  * 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 {
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=
SYMMETRIC
 My key is your key
Why Symmetric?


 ★   Fast
 ★   Well suited for bulk data
Using Symmetric


  Secure network for passing keys
  or
  Never decrypted at remote end
Symmetric Problems

  Keys vulnerable to capture
  Eavesdropping on future communications
  after key compromise
  Key distribution challenges
   Triangular number key growth
Symmetric Problems
 ★   Triangular number key growth
Symmetric
                     Encrypted with
                256 bit symmetric key
        A’s
      256 bit
    symmetric
       key




A                 Message/File          B
we se curel y get
 How do                 Bob?
    key f rom A lice to
the
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
   {
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);
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);
}
//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);
    }
}
Input
String message1 = "Four score and seven years ago";




Result
Encrypted text: P0FT6N3XXrohtsz7OLh3FGYY0wErkPIur1DP6Csbj4g=
Decrypted text: Four score and seven years ago
SYMMETRIC
Block versus Stream Algorithms
Stream vs. Block



  Specific algorithms for each
SYMMETRIC (BLOCK)
Block


 Predefined content length
   Well-known end to the content
   Files on disk
   Inefficient when padding
DES

Data Encryption Standard
  Block cipher
  Banking industry
  DES is known to be broken
3DES

Triple Data Encryption Standard
  Block cipher
  a.k.a DESede
  Basically three passes of DES
  Reasonably strong
Blowfish

  Block cipher
  Unpatented (intentionally)
  Secure replacement for DES
   Faster than DES
  32 to 448 bit keys
  Overshadowed by AES
AES

 Advanced Encryption Standard
   Block cipher
   Government standard
    Rijndael algorithm
    (Joan Daemen, Vincent Rijmen)
    4 years of evaluation
    Final in December 2000
   Very Secure
SYMMETRIC (STREAM)
Stream


 Unknown content length
   Streaming video
   Streaming voice
   But still can do files
RC4

 Rivest’s Code 4
   Stream cipher
   Trademarked (name, but not algorithm)
   Used by
     Browsers in SSL, TLS
     WiFi in WEP WPA
                ,
     BitTorrent
     ssh
     Microsoft RDP
     PDF
ENCRYPTED = SAFE,
     RIGHT?
 information leakage from encrypted data
Encrypted isn’t enough?




                http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation
SECURE KEY EXCHANGE
    securely swapping symmetric keys
Diffie-Hellman


 Key Agreement Protocol
  Alice & Bob independently generate the shared
  (session) key
  Published 1976, but invented earlier
DH Diagrammed
          predetermined and openly shared
                  g = random p = prime
                  g = 11     p = 23

    picks a = 6                          picks b = 4
A   A= ga mod p                     B    B= gb mod p
    9=116 mod 23                         13=114 mod 23
    A=9                                  B=13


    K= Ba mod p                          K= Ab mod p
    6= 136 mod 23                        6= 94 mod 23
                  Encryption can begin
What’s wrong
 with this?
RANDOM NUMBERS
    Seed the machine
SecureRandom

  java.security.SecureRandom
  Cryptographically strong pseudo-random
  number generator (PRNG)
  “Unable to distinguish from a true random
  source”
  Used in combination with many ciphers
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
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);
    }
}
* 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);
    }
}
Result



Random number: 1633471380
ASYMMETRIC
     Throwing away keys
faster than an intern locksmith
RSA

 Ron Rivest, Adi Shamir, Leonard Adleman
 Published in 1978
 M.I.T. Patented in 1983
 Patent Expired in 2000
RSA
                   Encrypted with
                 2048 bit RSA key
       B’s                              B’s
     2048 bit                        2048 bit
    public key                      private key




A                Message/File                     B
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
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/OFB/PKCS1Padding");
    rsa.init(Cipher.ENCRYPT_MODE, pubKey);
    byte[] encryptedBytes = rsa.doFinal(message1.getBytes());
    BASE64Encoder b64e = new sun.misc.BASE64Encoder();
KeyPair pair = keyGen.generateKeyPair();

        final PrivateKey privKey = pair.getPrivate();
        final PublicKey pubKey = pair.getPublic();


        //Encrypt using the private key
        Cipher rsa = Cipher.getInstance("RSA/OFB/PKCS1Padding");
        rsa.init(Cipher.ENCRYPT_MODE, pubKey);
        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, privKey);
        byte[] decryptedBytes = rsa.doFinal(encryptedBytes);
        String decryptedText = new String(decryptedBytes);
        System.out.println("Decrypted text: " + decryptedText);
    }
}
final PublicKey pubKey = pair.getPublic();


        //Encrypt using the private key
        Cipher rsa = Cipher.getInstance("RSA/OFB/PKCS1Padding");
        rsa.init(Cipher.ENCRYPT_MODE, pubKey);
        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, privKey);
        byte[] decryptedBytes = rsa.doFinal(encryptedBytes);
        String decryptedText = new String(decryptedBytes);
        System.out.println("Decrypted text: " + decryptedText);
    }
}
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
BLENDED
symmetric with a twist of asymmetric
Key Size & Security




                                      1024 bit RSA
                                                     Asymmetric
                                                      Key Size
 160 bit DES




               Symmetric
                Key Size
                           112 bits




                                                                  128 bits
               Security                               Security
Encryption Speed



  asymmetric can be 1000x slower
                      than symmetric
What do we do about that?
PGP
                    Encrypted with
                  2048 bit RSA key
       B’s                                   B’s
     2048 bit                             2048 bit
    public key     Random generated      private key
                 256 bit symmetric key

                     Encrypted with
                 256 bit symmetric key

A                                                      B

                  Message/File
OTHER FRAMEWORKS
   and alternative JCE providers
Bouncy Castle
White box implementation of JCE & Emerging Algorithms
Gnu
Open source library
Jasypt
Frictionless Java encryption
ConfigurablePasswordEncryptor pe =
  new ConfigurablePasswordEncryptor();

pe.setAlgorithm("SHA-512");
pe.setPlainDigest(false);
pe.setStringOutputType("base64");

String encryptedPassword =
  pe.encryptPassword(TEXT_TO_ENCRYPT);
In Summary
  Hash vs. Encrypt
    Know when to apply each
  Know your algorithm
    Key strength
    Symmetric versus asymmetric
  Encrypted does not guarantee security
    ECB can be leaky
  High Level Libraries
    More productive than pure JCE
Don’t forget
 the humans
http://xkcd.com/538/
delicious.com/matthew.mccullough/encryption
OT CA MP
           TI ON BOission
   RYPrity is the M
ENC cu
     Se


            Matthew McCullough
    Email matthewm@ambientideas.com
    Twitter @matthewmccull
    Blog    http://ambientideas.com/blog

Contenu connexe

Tendances

Tendances (20)

Stateless Microservice Security via JWT and MicroProfile - ES
Stateless Microservice Security via JWT and MicroProfile - ES Stateless Microservice Security via JWT and MicroProfile - ES
Stateless Microservice Security via JWT and MicroProfile - ES
 
Seguridad en microservicios via micro profile jwt
Seguridad en microservicios via micro profile jwtSeguridad en microservicios via micro profile jwt
Seguridad en microservicios via micro profile jwt
 
DEF CON 27 - D4KRM4TTER MIKE SPICER - I know what you did last summer
DEF CON 27 - D4KRM4TTER MIKE SPICER - I know what you did last summerDEF CON 27 - D4KRM4TTER MIKE SPICER - I know what you did last summer
DEF CON 27 - D4KRM4TTER MIKE SPICER - I know what you did last summer
 
系統02_關鍵的「特權+資料安全」最後一哩防線 解忠翰
系統02_關鍵的「特權+資料安全」最後一哩防線 解忠翰系統02_關鍵的「特權+資料安全」最後一哩防線 解忠翰
系統02_關鍵的「特權+資料安全」最後一哩防線 解忠翰
 
Lost in the Ether: How Ethereum Hacks Are Shaping the Blockchain Future
Lost in the Ether: How Ethereum Hacks Are Shaping the Blockchain FutureLost in the Ether: How Ethereum Hacks Are Shaping the Blockchain Future
Lost in the Ether: How Ethereum Hacks Are Shaping the Blockchain Future
 
The Thing About Protecting Data Is, You Have To Protect Data
The Thing About Protecting Data Is, You Have To Protect DataThe Thing About Protecting Data Is, You Have To Protect Data
The Thing About Protecting Data Is, You Have To Protect Data
 
Protocol buffers and Microservices
Protocol buffers and MicroservicesProtocol buffers and Microservices
Protocol buffers and Microservices
 
Cryptography
CryptographyCryptography
Cryptography
 
Trustleap - Mathematically-Proven Unbreakable Security
Trustleap - Mathematically-Proven Unbreakable SecurityTrustleap - Mathematically-Proven Unbreakable Security
Trustleap - Mathematically-Proven Unbreakable Security
 
TrustLeap Multipass - Unbreakable Passwords For Cloud Services
TrustLeap Multipass - Unbreakable Passwords For Cloud ServicesTrustLeap Multipass - Unbreakable Passwords For Cloud Services
TrustLeap Multipass - Unbreakable Passwords For Cloud Services
 
Analysis of symmetric key cryptographic algorithms
Analysis of symmetric key cryptographic algorithmsAnalysis of symmetric key cryptographic algorithms
Analysis of symmetric key cryptographic algorithms
 
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
 
Go paranoid
Go paranoidGo paranoid
Go paranoid
 
SSL/TLS for Mortals (Devoxx FR 2018)
SSL/TLS for Mortals (Devoxx FR 2018)SSL/TLS for Mortals (Devoxx FR 2018)
SSL/TLS for Mortals (Devoxx FR 2018)
 
Martin Novotny and Timo Kasper
Martin Novotny and Timo KasperMartin Novotny and Timo Kasper
Martin Novotny and Timo Kasper
 
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)
Blockchain Cryptography for Developers (Nakov @ BlockWorld 2018, San Jose)
 
Global-WAN - The Swiss Neutral Data Haven
Global-WAN - The Swiss Neutral Data HavenGlobal-WAN - The Swiss Neutral Data Haven
Global-WAN - The Swiss Neutral Data Haven
 
DEF CON 27- JISKA FABIAN - vacuum cleaning security
DEF CON 27- JISKA FABIAN - vacuum cleaning securityDEF CON 27- JISKA FABIAN - vacuum cleaning security
DEF CON 27- JISKA FABIAN - vacuum cleaning security
 
J. Daniel Martínez - IoP: The Internet of Planes / Hacking millionaires jet c...
J. Daniel Martínez - IoP: The Internet of Planes / Hacking millionaires jet c...J. Daniel Martínez - IoP: The Internet of Planes / Hacking millionaires jet c...
J. Daniel Martínez - IoP: The Internet of Planes / Hacking millionaires jet c...
 
Ángel Palomo Cisneros - Programming and playing a MITM attack [rooted2018]
Ángel Palomo Cisneros - Programming and playing a MITM attack [rooted2018]Ángel Palomo Cisneros - Programming and playing a MITM attack [rooted2018]
Ángel Palomo Cisneros - Programming and playing a MITM attack [rooted2018]
 

Similaire à Encryption Boot Camp at JavaZone 2010

Java Symmetric
Java SymmetricJava Symmetric
Java Symmetric
phanleson
 
Tutorial s crypto api session keys
Tutorial   s crypto api session keysTutorial   s crypto api session keys
Tutorial s crypto api session keys
Dr. Edwin Hernandez
 
12 symmetric key cryptography
12   symmetric key cryptography12   symmetric key cryptography
12 symmetric key cryptography
drewz lin
 
Cryptography and encryption and security network
Cryptography and encryption and security networkCryptography and encryption and security network
Cryptography and encryption and security network
NirajKumar620142
 

Similaire à Encryption Boot Camp at JavaZone 2010 (20)

Encryption Boot Camp at Øredev
Encryption Boot Camp at ØredevEncryption Boot Camp at Øredev
Encryption Boot Camp at Øredev
 
Cryptography 101 for Java developers
Cryptography 101 for Java developersCryptography 101 for Java developers
Cryptography 101 for Java developers
 
Cryptography 101 for Java developers
Cryptography 101 for Java developersCryptography 101 for Java developers
Cryptography 101 for Java developers
 
Java Symmetric
Java SymmetricJava Symmetric
Java Symmetric
 
Implement symmetric key algorithms.pptx
Implement symmetric key algorithms.pptxImplement symmetric key algorithms.pptx
Implement symmetric key algorithms.pptx
 
Django cryptography
Django cryptographyDjango cryptography
Django cryptography
 
Cryptography 101 for Java Developers - JavaZone2019
Cryptography 101 for Java Developers - JavaZone2019Cryptography 101 for Java Developers - JavaZone2019
Cryptography 101 for Java Developers - JavaZone2019
 
Encryption Boot Camp on the JVM
Encryption Boot Camp on the JVMEncryption Boot Camp on the JVM
Encryption Boot Camp on the JVM
 
Cryptography In Silverlight
Cryptography In SilverlightCryptography In Silverlight
Cryptography In Silverlight
 
Tutorial s crypto api session keys
Tutorial   s crypto api session keysTutorial   s crypto api session keys
Tutorial s crypto api session keys
 
Password (in)security
Password (in)securityPassword (in)security
Password (in)security
 
Cryptography 101 for_java_developers, Fall 2019
Cryptography 101 for_java_developers, Fall 2019Cryptography 101 for_java_developers, Fall 2019
Cryptography 101 for_java_developers, Fall 2019
 
Gimme Caching - The JCache Way
Gimme Caching - The JCache WayGimme Caching - The JCache Way
Gimme Caching - The JCache Way
 
12 symmetric key cryptography
12   symmetric key cryptography12   symmetric key cryptography
12 symmetric key cryptography
 
Python Cryptography & Security
Python Cryptography & SecurityPython Cryptography & Security
Python Cryptography & Security
 
Strong cryptography in PHP
Strong cryptography in PHPStrong cryptography in PHP
Strong cryptography in PHP
 
Cryptography and encryption and security network
Cryptography and encryption and security networkCryptography and encryption and security network
Cryptography and encryption and security network
 
Slide cipher based encryption
Slide cipher based encryptionSlide cipher based encryption
Slide cipher based encryption
 
Dodging WebCrypto API Landmines
Dodging WebCrypto API LandminesDodging WebCrypto API Landmines
Dodging WebCrypto API Landmines
 
Cryptography 101 for Java Developers - Devoxx 2019
Cryptography 101 for Java Developers - Devoxx 2019Cryptography 101 for Java Developers - Devoxx 2019
Cryptography 101 for Java Developers - Devoxx 2019
 

Plus de Matthew McCullough

Plus de Matthew McCullough (20)

Using Git and GitHub Effectively at Emerge Interactive
Using Git and GitHub Effectively at Emerge InteractiveUsing Git and GitHub Effectively at Emerge Interactive
Using Git and GitHub Effectively at Emerge Interactive
 
All About GitHub Pull Requests
All About GitHub Pull RequestsAll About GitHub Pull Requests
All About GitHub Pull Requests
 
Adam Smith Builds an App
Adam Smith Builds an AppAdam Smith Builds an App
Adam Smith Builds an App
 
Git's Filter Branch Command
Git's Filter Branch CommandGit's Filter Branch Command
Git's Filter Branch Command
 
Git Graphs, Hashes, and Compression, Oh My
Git Graphs, Hashes, and Compression, Oh MyGit Graphs, Hashes, and Compression, Oh My
Git Graphs, Hashes, and Compression, Oh My
 
Git and GitHub at the San Francisco JUG
 Git and GitHub at the San Francisco JUG Git and GitHub at the San Francisco JUG
Git and GitHub at the San Francisco JUG
 
Finding Things in Git
Finding Things in GitFinding Things in Git
Finding Things in Git
 
Git and GitHub for RallyOn
Git and GitHub for RallyOnGit and GitHub for RallyOn
Git and GitHub for RallyOn
 
Migrating from Subversion to Git and GitHub
Migrating from Subversion to Git and GitHubMigrating from Subversion to Git and GitHub
Migrating from Subversion to Git and GitHub
 
Git Notes and GitHub
Git Notes and GitHubGit Notes and GitHub
Git Notes and GitHub
 
Intro to Git and GitHub
Intro to Git and GitHubIntro to Git and GitHub
Intro to Git and GitHub
 
Build Lifecycle Craftsmanship for the Transylvania JUG
Build Lifecycle Craftsmanship for the Transylvania JUGBuild Lifecycle Craftsmanship for the Transylvania JUG
Build Lifecycle Craftsmanship for the Transylvania JUG
 
Git Going for the Transylvania JUG
Git Going for the Transylvania JUGGit Going for the Transylvania JUG
Git Going for the Transylvania JUG
 
Transylvania JUG Pre-Meeting Announcements
Transylvania JUG Pre-Meeting AnnouncementsTransylvania JUG Pre-Meeting Announcements
Transylvania JUG Pre-Meeting Announcements
 
Game Theory for Software Developers at the Boulder JUG
Game Theory for Software Developers at the Boulder JUGGame Theory for Software Developers at the Boulder JUG
Game Theory for Software Developers at the Boulder JUG
 
Cascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGCascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUG
 
JQuery Mobile
JQuery MobileJQuery Mobile
JQuery Mobile
 
R Data Analysis Software
R Data Analysis SoftwareR Data Analysis Software
R Data Analysis Software
 
Please, Stop Using Git
Please, Stop Using GitPlease, Stop Using Git
Please, Stop Using Git
 
Dr. Strangedev
Dr. StrangedevDr. Strangedev
Dr. Strangedev
 

Dernier

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Dernier (20)

fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 

Encryption Boot Camp at JavaZone 2010

  • 1. TI YP P ON C R AM EN T C B OOurity is th e mi ssion Sec @matthewmccull © Matthew McCullough, Ambient Ideas, LLC
  • 2. G? ot TINare n YP 6% ENCR 7 say statis tics
  • 3. EA ED t C H us DA TA BR nies in j o f co mpa ths at 8 5% t 12 Mon the las
  • 4. Stay out of My Encryption!
  • 6.
  • 7.
  • 8. Final cost was $1,000,000,000 USD
  • 9. ANCIENT HISTORY Everything old is new again
  • 10. Recipient or Storage ht Sig r ed cu ain ts O b s Pl C on te n Sensitive Data
  • 11. 44 B.C. That’s 2,054 years ago...
  • 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.
  • 16. Compromised Every algorithm is vulnerable Crack by real-time brute force Crack by pre-computed tables Function of time + money + hardware
  • 17. JCE PRIMER The world of Java crypto
  • 18. Java Cryptography Extension Known as JCE Included in all JREs Since Java 1.2 Pluggable provider architecture JCE extends Java Cryptography Architecture (JCA)
  • 19. JCE Strength ★ Jurisdiction Policy Files ★ Two variants ★ Algorithm strength differences
  • 20. JCE Strength Strong strength included in all JREs Unlimited strength is a separate download available based on US export rules
  • 21.
  • 22.
  • 24. Unlimite d
  • 25. Strong 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; };
  • 26. “Strong” Key Limits Algorithm Max Key Size DES 64 DESede 168 3des RC2 128 RC4 128 RC5 128 RSA 2048 Others 128
  • 27. “Unlimited” Key Limits Algorithm Max Key Size DES ∞ DESede ∞ 3des RC2 ∞ RC4 ∞ RC5 ∞ RSA ∞ Others ∞
  • 28. Digests & Hashes One way functions
  • 29. What is a Hash? Small set of bytes representing a large message Small change in message = large change in digest Digests also known as a hashes Same algorithms, different purposes
  • 30. What is a Digest? Integrity check (MIC) for chunk of data or Password storage mechanism
  • 31. MessageDigest ★ java.security.MessageDigest ★ Many algorithms available ★ MD2 ★ MD5 (128 bit) ★ SHA-1 (160 bit) ★ SHA-256 ★ SHA-384 ★ SHA-512
  • 32. MessageDigest U. S. Department of Homeland Security said MD5 is "considered cryptographically broken and unsuitable for further use"
  • 34. 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); } }
  • 35. * * 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 {
  • 36. 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=
  • 37. SYMMETRIC My key is your key
  • 38. Why Symmetric? ★ Fast ★ Well suited for bulk data
  • 39. Using Symmetric Secure network for passing keys or Never decrypted at remote end
  • 40. Symmetric Problems Keys vulnerable to capture Eavesdropping on future communications after key compromise Key distribution challenges Triangular number key growth
  • 41. Symmetric Problems ★ Triangular number key growth
  • 42. Symmetric Encrypted with 256 bit symmetric key A’s 256 bit symmetric key A Message/File B
  • 43. we se curel y get How do Bob? key f rom A lice to the
  • 44.
  • 45. 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 {
  • 46. 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);
  • 47. 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); }
  • 48. //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); } }
  • 49. Input String message1 = "Four score and seven years ago"; Result Encrypted text: P0FT6N3XXrohtsz7OLh3FGYY0wErkPIur1DP6Csbj4g= Decrypted text: Four score and seven years ago
  • 51. Stream vs. Block Specific algorithms for each
  • 53. Block Predefined content length Well-known end to the content Files on disk Inefficient when padding
  • 54. DES Data Encryption Standard Block cipher Banking industry DES is known to be broken
  • 55. 3DES Triple Data Encryption Standard Block cipher a.k.a DESede Basically three passes of DES Reasonably strong
  • 56. Blowfish Block cipher Unpatented (intentionally) Secure replacement for DES Faster than DES 32 to 448 bit keys Overshadowed by AES
  • 57. AES Advanced Encryption Standard Block cipher Government standard Rijndael algorithm (Joan Daemen, Vincent Rijmen) 4 years of evaluation Final in December 2000 Very Secure
  • 59. Stream Unknown content length Streaming video Streaming voice But still can do files
  • 60. RC4 Rivest’s Code 4 Stream cipher Trademarked (name, but not algorithm) Used by Browsers in SSL, TLS WiFi in WEP WPA , BitTorrent ssh Microsoft RDP PDF
  • 61. ENCRYPTED = SAFE, RIGHT? information leakage from encrypted data
  • 62. Encrypted isn’t enough? http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation
  • 63. SECURE KEY EXCHANGE securely swapping symmetric keys
  • 64.
  • 65. Diffie-Hellman Key Agreement Protocol Alice & Bob independently generate the shared (session) key Published 1976, but invented earlier
  • 66. DH Diagrammed predetermined and openly shared g = random p = prime g = 11 p = 23 picks a = 6 picks b = 4 A A= ga mod p B B= gb mod p 9=116 mod 23 13=114 mod 23 A=9 B=13 K= Ba mod p K= Ab mod p 6= 136 mod 23 6= 94 mod 23 Encryption can begin
  • 68. RANDOM NUMBERS Seed the machine
  • 69. SecureRandom java.security.SecureRandom Cryptographically strong pseudo-random number generator (PRNG) “Unable to distinguish from a true random source” Used in combination with many ciphers
  • 70. 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
  • 71. 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); } }
  • 72. * 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); } }
  • 74. ASYMMETRIC Throwing away keys faster than an intern locksmith
  • 75.
  • 76. RSA Ron Rivest, Adi Shamir, Leonard Adleman Published in 1978 M.I.T. Patented in 1983 Patent Expired in 2000
  • 77. RSA Encrypted with 2048 bit RSA key B’s B’s 2048 bit 2048 bit public key private key A Message/File B
  • 78. 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
  • 79. 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/OFB/PKCS1Padding"); rsa.init(Cipher.ENCRYPT_MODE, pubKey); byte[] encryptedBytes = rsa.doFinal(message1.getBytes()); BASE64Encoder b64e = new sun.misc.BASE64Encoder();
  • 80. KeyPair pair = keyGen.generateKeyPair(); final PrivateKey privKey = pair.getPrivate(); final PublicKey pubKey = pair.getPublic(); //Encrypt using the private key Cipher rsa = Cipher.getInstance("RSA/OFB/PKCS1Padding"); rsa.init(Cipher.ENCRYPT_MODE, pubKey); 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, privKey); byte[] decryptedBytes = rsa.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Decrypted text: " + decryptedText); } }
  • 81. final PublicKey pubKey = pair.getPublic(); //Encrypt using the private key Cipher rsa = Cipher.getInstance("RSA/OFB/PKCS1Padding"); rsa.init(Cipher.ENCRYPT_MODE, pubKey); 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, privKey); byte[] decryptedBytes = rsa.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Decrypted text: " + decryptedText); } }
  • 82. 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
  • 83. BLENDED symmetric with a twist of asymmetric
  • 84. Key Size & Security 1024 bit RSA Asymmetric Key Size 160 bit DES Symmetric Key Size 112 bits 128 bits Security Security
  • 85. Encryption Speed asymmetric can be 1000x slower than symmetric
  • 86. What do we do about that?
  • 87. PGP Encrypted with 2048 bit RSA key B’s B’s 2048 bit 2048 bit public key Random generated private key 256 bit symmetric key Encrypted with 256 bit symmetric key A B Message/File
  • 88. OTHER FRAMEWORKS and alternative JCE providers
  • 89. Bouncy Castle White box implementation of JCE & Emerging Algorithms
  • 92. ConfigurablePasswordEncryptor pe = new ConfigurablePasswordEncryptor(); pe.setAlgorithm("SHA-512"); pe.setPlainDigest(false); pe.setStringOutputType("base64"); String encryptedPassword = pe.encryptPassword(TEXT_TO_ENCRYPT);
  • 93.
  • 94. In Summary Hash vs. Encrypt Know when to apply each Know your algorithm Key strength Symmetric versus asymmetric Encrypted does not guarantee security ECB can be leaky High Level Libraries More productive than pure JCE
  • 98. OT CA MP TI ON BOission RYPrity is the M ENC cu Se Matthew McCullough Email matthewm@ambientideas.com Twitter @matthewmccull Blog http://ambientideas.com/blog