Cryptography and encryption and security network

[ad_1]

Cryptography and encryption and security network | PPT

 2002 Prentice Hall. All rights reserved.
Chapter 7 Security
7.13 Authentication
7.13.1 Kerberos
7.13.2 Single Sign-On
7.13.3 Java Authentication and Authorization Service (JAAS)
7.14 Secure Sockets Layer (SSL)
7.14.1 Java Secure Socket Extension (JSSE)
7.15 Java Language Security and Secure Coding
7.16 Internet and World Wide Web Resources

Cryptography and encryption and security network

  • 1.  2002 Prentice Hall. All rights reserved.
    Chapter 7: Security
    Outline
    7.1 Introduction
    7.2 Ancient Ciphers to Modern Cryptosystems
    7.3 Secret-key Cryptography
    7.4 Public-key Cryptography
    7.5 Cryptanalysis
    7.6 Key Agreement Protocols
    7.7 Key Management
    7.8 Java Cryptography Extension (JCE)
    7.8.1 Password-Based Encoding with JCE|
    7.8.2 Decorator Design Pattern
    7.9 Digital Signatures
    7.10 Public-key Infrastructure, Certificates and Certification
    Authorities
    7.10.1 Java Keystores and keytool
    7.11 Java Policy Files
    7.12 Digital Signatures for Java Code
  • 2.  2002 Prentice Hall. All rights reserved.
    Chapter 7 Security
    7.13 Authentication
    7.13.1 Kerberos
    7.13.2 Single Sign-On
    7.13.3 Java Authentication and Authorization Service (JAAS)
    7.14 Secure Sockets Layer (SSL)
    7.14.1 Java Secure Socket Extension (JSSE)
    7.15 Java Language Security and Secure Coding
    7.16 Internet and World Wide Web Resources
  • 3.  2002 Prentice Hall. All rights reserved.
    7.1 Introduction
    • Need for Internet security
    – Consumers buying products, trading stocks and banking
    online
    – Credit-card, social security and confidential business
    information exchanged
    – Security attacks
    • Data theft and hacker attacks
    • Wireless transmissions easier to intercept
    • Secure transaction fundamentals
    – Privacy: no third party
    – Integrity: information unaltered
    – Authentication: proving identities
    – Non-repudiation: legal proof of message received
  • 4.  2002 Prentice Hall. All rights reserved.
    7.1 Introduction (cont.)
    • Availability
    – Network stays in operation continuously and are becoming
    wireless
    • 4 main security issues
    – Privacy
    – Integrity
    – Authentication
    – Non-repudiation
  • 5.  2002 Prentice Hall. All rights reserved.
    7.2 Ancient Ciphers to Modern
    Cryptosystems
    • Cryptography
    – Cipher/cryptosystem (algorithm) encrypts message
    • Plaintext: unencrypted data
    • Ciphertext: encrypted data
    – Key: used by sender and receiver to encrypt and decrypt
    message
    • Ancient Ciphers
    – Substitution ciphers: given letter replaced by different letter
    – Transposition ciphers: letter ordering shifted
    – Restricted algorithms: security relies on keeping encryption
    algorithm secret
  • 6.  2002 Prentice Hall. All rights reserved.
    7.2 Ancient Ciphers to Modern
    Cryptosystems (cont.)
    • Digital cryptosystems
    – Algorithms based on bits/blocks of binary string (computer
    data)
    – Key length: stronger encryption for longer keys
    – US government used to limit key length of exported
    cryptosystems
    • Regulations now less stringent
  • 7.  2002 Prentice Hall. All rights reserved.
    7.3 Secret-key Cryptography
    • Symmetric/secret-key cryptography
    – Same key encrypts and decrypts message
    – Disadvantages
    • Need secure method to transfer key
    • No authentication because same key used on both ends
    • Sender needs separate secret key for each receiver
    – Key distribution center (KDC)
    • Shares secret key with users in network
    • Encrypts session key with secret keys to sender and receiver
    • Session key used for transaction
    • New keys and less couriers for transactions, but security
    depends on security on KDC
  • 8.  2002 Prentice Hall. All rights reserved.
    7.3 Secret-key Cryptography (cont.)
    • Data Encryption Standard (DES)
    – Uses block cipher: creates bit groups from message and
    applies algorithm to whole block
    – DES standard set by American National Standards Institute
    (ANSI) for years, no loner considered secure
    • DES Cracker Machines developed to crack DES code
    • Triple DES (3DES) replaced DES
    – Three DES systems in row with unique secret key
    • Advanced Encryption Standard (AES) is new
    standard
    – Nation Institute of Standards and Technology (NIST)
    currently evaluating Rijndael for AES
  • 9.  2002 Prentice Hall. All rights reserved.
    7.3 Secret-key Cryptography (cont.)
    Fig. 7.1 Encrypting and decrypting a message using a symmetric secret key.
  • 10.  2002 Prentice Hall. All rights reserved.
    7.3 Secret-key Cryptography (cont.)
    Fig. 7.2 Distributing a session key with a key distribution center.
  • 11.  2002 Prentice Hall. All rights reserved.
    7.4 Public-key Cryptography
    • Public-key Cryptography
    – Uses public-key (distributed) and private-key (kept secret)
    – Public-key decrypts private-key and vice-versa
    – Computationally infeasible to deduce private-key from
    public-key
    – Authentication
    • If receiver’s public-key and sender’s private key are both used,
    both parties are authenticated
    • RSA: most common public-key algorithm
    – Used by most Fortune 1000 and e-commerce businesses
    • Pretty Good Privacy (PGP)
    – Encrypts e-mails and files using “web of trust”
  • 12.  2002 Prentice Hall. All rights reserved.
    7.4 Public-key Cryptography (cont.)
    Fig. 7.3 Encrypting and decrypting a message using public-key cryptography.
  • 13.  2002 Prentice Hall. All rights reserved.
    7.4 Public-key Cryptography (cont.)
    Fig. 7.4 Authentication with a public-key algorithm
  • 14.  2002 Prentice Hall. All rights reserved.
    7.5 Cryptanalysis
    • Even if keys are secret, it is possible to
    compromise the security of a system
    • Cryptanalysis: trying to decrypt ciphertext without
    knowledge of the decryption key
    – Cryptanalytic attacks
    • Attacks can be reduced if proper key management
    structures are in place and keys use expiration
    dates
  • 15.  2002 Prentice Hall. All rights reserved.
    7.6 Key Agreement Protocols
    • Public-key algorithms not efficient for large
    amounts of data
    – Large computing power requirements slow communication
    • Key Agreement Protocol
    – Two parties exchange keys over unsecure medium
    – Digital envelope: symmetric secret key encrypted using
    public-key encryption
  • 16.  2002 Prentice Hall. All rights reserved.
    7.6 Key Agreement Protocols (cont.)
    Fig. 7.5 Creating a digital envelope.
  • 17.  2002 Prentice Hall. All rights reserved.
    7.7 Key Management
    • Secrecy of private keys crucial to system security
    – Poor key management: mishandling of private keys
    – Key generation: process by which keys created
    • Should be as random as possible
    – Brute-force cracking: decrypting message using every
    possible decryption key
  • 18.  2002 Prentice Hall. All rights reserved.
    7.8 Java Cryptography Extension (JCE)
    • Java Cryptography Extension (JCE)
    – provides Java applications with various security facilities
    – supports
    • secret-key encryption
    – 3DES
    • public-key algorithms
    – Diffie-Hellman
    – RSA
    – customizable levels of encryption through
    • multiple encryption algorithms
    • various key sizes
    – architecture is provider-based
    • developers add algorithms by adding providers’ algorithms
  • 19.  2002 Prentice Hall. All rights reserved.
    7.8.1 Password-Based Encoding with JCE
    • Class EncipherDecipher
    – demonstrates Password-Based Encryption (PBE)
    – to randomize sets of generated keys, uses
    • array of bytes called salt
    • integer
  • 20.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.6
    EnciphyerDeciphe
    r application for
    demonstrating
    Password-Based
    Encryption.
    Lines 28-31
    Line 34
    Lines 28-34
    1 // EncipherDecipher.java
    2 // Displays a frame that allows users to specify
    3 // a password and a file name. Contents written
    4 // to an Editor Pane can be encrypted and written
    5 // to a file, or encrypted contents can be read from
    6 // a file and decrypted
    7 package com.deitel.advjhtp1.security.jce;
    8
    9 // Java core package
    10 import java.awt.*;
    11 import java.awt.event.*;
    12 import java.io.*;
    13 import java.util.*;
    14 import java.security.*;
    15 import java.security.spec.*;
    16
    17 // third-party packages
    18 import com.sun.crypto.provider.SunJCE;
    19
    20 // Java extension package
    21 import javax.swing.*;
    22 import javax.crypto.*;
    23 import javax.crypto.spec.*;
    24
    25 public class EncipherDecipher extends JFrame {
    26
    27 // salt for password-based encryption-decryption algorithm
    28 private static final byte[] salt = {
    29 ( byte )0xf5, ( byte )0x33, ( byte )0x01, ( byte )0x2a,
    30 ( byte )0xb2, ( byte )0xcc, ( byte )0xe4, ( byte )0x7f
    31 };
    32
    33 // iteration count
    34 private int iterationCount = 100;
    35
    salt
    iteration counter
    randomize sets of
    generated keys
  • 21.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.6
    EnciphyerDeciphe
    r application for
    demonstrating
    Password-Based
    Encryption.
    Line 45
    36 // user input components.
    37 private JTextField passwordTextField;
    38 private JTextField fileNameTextField;
    39 private JEditorPane fileContentsEditorPane;
    40
    41 // frame constructor
    42 public EncipherDecipher() {
    43
    44 // set security provider
    45 Security.addProvider( new SunJCE() );
    46
    47 // initialize main frame
    48 setSize( new Dimension( 400, 400 ) );
    49 setTitle( “Encryption and Decryption Example” );
    50
    51 // construct top panel
    52 JPanel topPanel = new JPanel();
    53 topPanel.setBorder( BorderFactory.createLineBorder(
    54 Color.black ) );
    55 topPanel.setLayout( new BorderLayout() );
    56
    57 // panel where password and file name labels will be placed
    58 JPanel labelsPanel = new JPanel();
    59 labelsPanel.setLayout( new GridLayout( 2, 1 ) );
    60 JLabel passwordLabel = new JLabel( ” Password: ” );
    61 JLabel fileNameLabel = new JLabel( ” File Name: ” );
    62 labelsPanel.add( fileNameLabel );
    63 labelsPanel.add( passwordLabel );
    64 topPanel.add( labelsPanel, BorderLayout.WEST );
    65
    add security provider
    implementation.
    Provides system with
    various algorithm
    implementations.
  • 22.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.6
    EnciphyerDeciphe
    r application for
    demonstrating
    Password-Based
    Encryption.
    66 // panel where password and file name textfields placed
    67 JPanel textFieldsPanel = new JPanel();
    68 textFieldsPanel.setLayout( new GridLayout( 2, 1 ) );
    69 passwordTextField = new JPasswordField();
    70 fileNameTextField = new JTextField();
    71 textFieldsPanel.add( fileNameTextField );
    72 textFieldsPanel.add( passwordTextField );
    73 topPanel.add( textFieldsPanel, BorderLayout.CENTER );
    74
    75 // construct middle panel
    76 JPanel middlePanel = new JPanel();
    77 middlePanel.setLayout( new BorderLayout() );
    78
    79 // construct and place title label for contents pane
    80 JLabel fileContentsLabel = new JLabel();
    81 fileContentsLabel.setText( ” File Contents” );
    82 middlePanel.add( fileContentsLabel, BorderLayout.NORTH );
    83
    84 // initialize and place editor pane within scroll panel
    85 fileContentsEditorPane = new JEditorPane();
    86 middlePanel.add(
    87 new JScrollPane( fileContentsEditorPane ),
    88 BorderLayout.CENTER );
    89
    90 // construct bottom panel
    91 JPanel bottomPanel = new JPanel();
    92
    93 // create encrypt button
    94 JButton encryptButton =
    95 new JButton( “Encrypt and Write to File” );
    96 encryptButton.addActionListener(
    97
    98 new ActionListener() {
    99
  • 23.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.6
    EnciphyerDeciphe
    r application for
    demonstrating
    Password-Based
    Encryption.
    100 public void actionPerformed( ActionEvent event )
    101 {
    102 encryptAndWriteToFile();
    103 }
    104 }
    105 );
    106 bottomPanel.add( encryptButton );
    107
    108 // create decrypt button
    109 JButton decryptButton =
    110 new JButton( “Read from File and Decrypt” );
    111 decryptButton.addActionListener(
    112
    113 new ActionListener() {
    114
    115 public void actionPerformed( ActionEvent event )
    116 {
    117 readFromFileAndDecrypt();
    118 }
    119 }
    120 );
    121 bottomPanel.add( decryptButton );
    122
    123 // initialize main frame window
    124 JPanel contentPane = ( JPanel ) this.getContentPane();
    125 contentPane.setLayout( new BorderLayout() );
    126 contentPane.add( topPanel, BorderLayout.NORTH );
    127 contentPane.add( middlePanel, BorderLayout.CENTER );
    128 contentPane.add( bottomPanel, BorderLayout.SOUTH );
    129
    130 } // end constructor
    131
  • 24.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.6
    EnciphyerDeciphe
    r application for
    demonstrating
    Password-Based
    Encryption.
    Lines 147-148
    Lines 151-152
    Line 155
    Lines 158-159
    Line 162
    Lines 165-166
    132 // obtain contents from editor pane and encrypt
    133 private void encryptAndWriteToFile()
    134 {
    135
    136 // obtain user input
    137 String originalText = fileContentsEditorPane.getText();
    138 String password = passwordTextField.getText();
    139 String fileName = fileNameTextField.getText();
    140
    141 // create secret key and get cipher instance
    142 Cipher cipher = null;
    143
    144 try {
    145
    146 // create password based encryption key object
    147 PBEKeySpec keySpec =
    148 new PBEKeySpec( password.toCharArray() );
    149
    150 // obtain instance for secret key factory
    151 SecretKeyFactory keyFactory =
    152 SecretKeyFactory.getInstance( “PBEWithMD5AndDES” );
    153
    154 // generate secret key for encryption
    155 SecretKey secretKey = keyFactory.generateSecret( keySpec );
    156
    157 // specifies parameters used with password based encryption
    158 PBEParameterSpec parameterSpec =
    159 new PBEParameterSpec( salt, iterationCount );
    160
    161 // obtain cipher instance reference
    162 cipher = Cipher.getInstance( “PBEWithMD5AndDES” );
    163
    164 // initialize cipher in encrypt mode
    165 cipher.init( Cipher.ENCRYPT_MODE, secretKey,
    166 parameterSpec );
    PBEKeySpec instance acts
    as wrapper for array of
    characters that represents
    password for encrypting and
    decrypting array of bytes
    obtain reference to
    SecretKeyFactory,
    which generates secret keys
    generate secret key from
    password byte array
    contains randomization
    information (salt, iteration count)
    obtain
    PBEWithMD5AndDES
    algorithm
    initialize Cipher instance
  • 25.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.6
    EnciphyerDeciphe
    r application for
    demonstrating
    Password-Based
    Encryption.
    Lines 170-173
    Lines 176-179
    Lines 182-185
    Lines 188-191
    Lines 194-197
    167 }
    168
    169 // handle NoSuchAlgorithmException
    170 catch ( NoSuchAlgorithmException exception ) {
    171 exception.printStackTrace();
    172 System.exit( 1 );
    173 }
    174
    175 // handle InvalidKeySpecException
    176 catch ( InvalidKeySpecException exception ) {
    177 exception.printStackTrace();
    178 System.exit( 1 );
    179 }
    180
    181 // handle InvalidKeyException
    182 catch ( InvalidKeyException exception ) {
    183 exception.printStackTrace();
    184 System.exit( 1 );
    185 }
    186
    187 // handle NoSuchPaddingException
    188 catch ( NoSuchPaddingException exception ) {
    189 exception.printStackTrace();
    190 System.exit( 1 );
    191 }
    192
    193 // handle InvalidAlgorithmParameterException
    194 catch ( InvalidAlgorithmParameterException exception ) {
    195 exception.printStackTrace();
    196 System.exit( 1 );
    197 }
    198
    199 // create array of bytes
    200 byte[] outputArray = null;
    201
    algorithm does not exist
    invalid key specification
    is sent to method
    generateSecret
    from class
    SecretKeyFactory
    invalid key handed to
    method init from
    class Cipher
    invalid padding scheme specified
    invalid algorithm parameters handed
    to method init of class Cipher
  • 26.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.6
    EnciphyerDeciphe
    r application for
    demonstrating
    Password-Based
    Encryption.
    Line 203
    Line 217
    Lines 227-228
    Line 228
    Line 228
    Lines 232-234
    202 try {
    203 outputArray = originalText.getBytes( “ISO-8859-1” );
    204 }
    205
    206 // handle UnsupportedEncodingException
    207 catch ( UnsupportedEncodingException exception ) {
    208 exception.printStackTrace();
    209 System.exit( 1 );
    210 }
    211
    212 // create FileOutputStream
    213 File file = new File( fileName );
    214 FileOutputStream fileOutputStream = null;
    215
    216 try {
    217 fileOutputStream = new FileOutputStream( file );
    218 }
    219
    220 // handle IOException
    221 catch ( IOException exception ) {
    222 exception.printStackTrace();
    223 System.exit( 1 );
    224 }
    225
    226 // create CipherOutputStream
    227 CipherOutputStream out =
    228 new CipherOutputStream( fileOutputStream, cipher );
    229
    230 // write contents to file and close
    231 try {
    232 out.write( outputArray );
    233 out.flush();
    234 out.close();
    235 }
    236
    convert user input into array of bytes
    conforming to ISO-8859-1 standard
    instantiate output stream to selected file
    instantiate decorator
    ChipherOutputStream
    decorates output stream
    Cipher object to encode bytes
    write to file and close
  • 27.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.6
    EnciphyerDeciphe
    r application for
    demonstrating
    Password-Based
    Encryption.
    237 // handle IOException
    238 catch ( IOException exception ) {
    239 exception.printStackTrace();
    240 System.exit( 1 );
    241 }
    242
    243 // contain bytes read from file
    244 Vector fileBytes = new Vector();
    245
    246 // read contents from file to show user encrypted text
    247 try {
    248 FileInputStream in = new FileInputStream( file );
    249
    250 // read bytes from stream.
    251 byte contents;
    252
    253 while ( in.available() > 0 ) {
    254 contents = ( byte )in.read();
    255 fileBytes.add( new Byte( contents ) );
    256 }
    257
    258 in.close();
    259 }
    260
    261 // handle IOException
    262 catch ( IOException exception ) {
    263 exception.printStackTrace();
    264 System.exit( 1 );
    265 }
    266
  • 28.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.6
    EnciphyerDeciphe
    r application for
    demonstrating
    Password-Based
    Encryption.
    267 // create byte array from contents in Vector fileBytes
    268 byte[] encryptedText = new byte[ fileBytes.size() ];
    269
    270 for ( int i = 0; i < fileBytes.size(); i++ ) {
    271 encryptedText[ i ] =
    272 ( ( Byte ) fileBytes.elementAt( i ) ).byteValue();
    273 }
    274
    275 // update Editor Pane contents
    276 fileContentsEditorPane.setText( new String( encryptedText ) );
    277 }
    278
    279 // obtain contents from file and decrypt
    280 private void readFromFileAndDecrypt()
    281 {
    282
    283 // used to rebuild byte list
    284 Vector fileBytes = new Vector();
    285
    286 // obtain user input
    287 String password = passwordTextField.getText();
    288 String fileName = fileNameTextField.getText();
    289
    290 // create secret key
    291 Cipher cipher = null;
    292
    293 try {
    294 // create password based encryption key object
    295 PBEKeySpec keySpec =
    296 new PBEKeySpec( password.toCharArray() );
    297
    298 // obtain instance for secret key factory
    299 SecretKeyFactory keyFactory =
    300 SecretKeyFactory.getInstance( “PBEWithMD5AndDES” );
    301
  • 29.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.6
    EnciphyerDeciphe
    r application for
    demonstrating
    Password-Based
    Encryption.
    Line 310
    Lines 313-134
    302 // generate secret key for encryption
    303 SecretKey secretKey = keyFactory.generateSecret( keySpec );
    304
    305 // specifies parameters used with password based encryption
    306 PBEParameterSpec parameterSpec =
    307 new PBEParameterSpec( salt, iterationCount );
    308
    309 // obtain cipher instance reference.
    310 cipher = Cipher.getInstance( “PBEWithMD5AndDES” );
    311
    312 // initialize cipher in decrypt mode
    313 cipher.init( Cipher.DECRYPT_MODE, secretKey,
    314 parameterSpec );
    315 }
    316
    317 // handle NoSuchAlgorithmException
    318 catch ( NoSuchAlgorithmException exception ) {
    319 exception.printStackTrace();
    320 System.exit( 1 );
    321 }
    322
    323 // handle InvalidKeySpecException
    324 catch ( InvalidKeySpecException exception ) {
    325 exception.printStackTrace();
    326 System.exit( 1 );
    327 }
    328
    329 // handle InvalidKeyException
    330 catch ( InvalidKeyException exception ) {
    331 exception.printStackTrace();
    332 System.exit( 1 );
    333 }
    334
    create instance of Cipher
    initialize to decrypt data
  • 30.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.6
    EnciphyerDeciphe
    r application for
    demonstrating
    Password-Based
    Encryption.
    Lines 351-352
    Lines 354-355
    Line 362
    335 // handle NoSuchPaddingException
    336 catch ( NoSuchPaddingException exception ) {
    337 exception.printStackTrace();
    338 System.exit( 1 );
    339 }
    340
    341 // handle InvalidAlgorithmParameterException
    342 catch ( InvalidAlgorithmParameterException exception ) {
    343 exception.printStackTrace();
    344 System.exit( 1 );
    345 }
    346
    347
    348 // read and decrypt contents from file
    349 try {
    350 File file = new File( fileName );
    351 FileInputStream fileInputStream =
    352 new FileInputStream( file );
    353
    354 CipherInputStream in =
    355 new CipherInputStream( fileInputStream, cipher );
    356
    357 // read bytes from stream.
    358 byte contents = ( byte ) in.read();
    359
    360 while ( contents != -1 ) {
    361 fileBytes.add( new Byte( contents ) );
    362 contents = ( byte ) in.read();
    363 }
    364 in.close();
    365
    366 }
    367
    create input stream
    create input stream decorator
    read decrypted content
  • 31.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.6
    EnciphyerDeciphe
    r application for
    demonstrating
    Password-Based
    Encryption.
    368 // handle IOException
    369 catch ( IOException exception ) {
    370 exception.printStackTrace();
    371 System.exit( 1 );
    372 }
    373
    374 // create byte array from contents in Vector fileBytes
    375 byte[] decryptedText = new byte[ fileBytes.size() ];
    376
    377 for ( int i = 0; i < fileBytes.size(); i++ ) {
    378 decryptedText[ i ] =
    379 ( ( Byte )fileBytes.elementAt( i ) ).byteValue();
    380 }
    381
    382 // update Editor Pane contents.
    383 fileContentsEditorPane.setText( new String( decryptedText ) );
    384 }
    385
    386 // create frame and display
    387 public static void main( String[] args )
    388 {
    389 EncipherDecipher crypto =
    390 new EncipherDecipher();
    391 crypto.validate();
    392 crypto.setVisible( true );
    393 }
    394 }
  • 32.  2002 Prentice Hall. All rights reserved.
    7.8.1 Password-Based Encoding with JCE
    (cont.)
    Fig. 7.7 EncipherDecipher before and after encrypting contents.
  • 33.  2002 Prentice Hall. All rights reserved.
    7.8.2 Decorator Design Pattern
    • EncypherDecipher
    – uses Decorator design pattern
    • Decorator design pattern is “chaining” two elements
    – no need create additional classes to extend functionality
    • ChipherOutputStream decorates FileOutputStream
    – ChipherOutputStream takes reference to OutputStream
    • can decorate any OutputStream
    • ChipherInputStream decorates FileInputStream
    – ChipherInputStream takes reference to InputStream
    • can decorate any InputStream
  • 34.  2002 Prentice Hall. All rights reserved.
    7.9 Digital Signatures
    • Digital signatures: provide authentication and
    integrity in public-key cryptography
    – Hash function: calculation assigns hash value to message
    – Chance of collision: two messages with same hash value is
    statistically insignificant
    – Digital signature, hash function and encrypted message sent
    to receiver
    • Message integrity: recalculated message hash value matches
    that sent in signature, verifies integrity
    – Timestamping: solves non-repudiation problem
    • Executed by timestamping agency who only sees encrypted
    message
    – Digital Signature Algorithm: standard for digital signatures
  • 35.  2002 Prentice Hall. All rights reserved.
    7.10 Public-key Infrastructure, Certificates and
    Certification Authorities
    • Public-key Infrastructure
    – Integrates public-key cryptography with digital certificates
    and certification authorities (CA’s)
    • Digital certificate: identifies user, issued by certification
    authority (such as VeriSign)
    • Digital certificates stored in certificate repositories
    – Certificate authority hierarchy
    • Root certification authority, the Internet Policy Registration
    Authority (IPRA), signs certificates for policy creation
    authorities who set policies for obtaining digital certificates
    • Policy creation authorities sign for CA’s who sign for
    individuals and organizations
    • Signings use public-key cryptography
  • 36.  2002 Prentice Hall. All rights reserved.
    7.10 Public-key Infrastructure, Certificates and
    Certification Authorities (cont.)
    • Changing keys necessary for maintaining security
    – Digital certificates have expiration dates
    – Canceled and revoked certificates placed on certificate
    revocation list (CRL)
    • Ensuring authenticity
    – Check certificate with CRL (inconvenient)
    – Online Certificate Status Protocol (OCSP) validates
    certificates in real-time
    • PKI and digital certificate transactions are more
    secure than phone line, mail or even credit-card
    transactions
  • 37.  2002 Prentice Hall. All rights reserved.
    7.10 Public-key Infrastructure, Certificates and
    Certification Authorities (cont.)
    Fig. 7.8 A portion of the VeriSign digital certificate. (Courtesy of VeriSign, Inc.)
  • 38.  2002 Prentice Hall. All rights reserved.
    7.10.1 Java Keystores and keytool
    • Java provides keytool utility for
    – managing keys
    – generating keys
    • Keystore
    – repository for storing public and private keys
    – modifying stored keys requires use of password
    – default keystore located in home/user/.keystore
    – command line arguments
    • -genkey
    – produces private and public key pair
    • -export
    – export a certificate
    • -import
    – import certificate from trusted source
    • -list
    – list all contents of keystore
    • -alias <alias_name>
    – identify public and private pair for later use
  • 39.  2002 Prentice Hall. All rights reserved.
    7.10.1 Java Keystores and keytool (cont.)
    • keytool-generated certificates identified through
    – commonName (CN)
    – organizationUnit (OU)
    – organizationName (O)
    – localityName (L)
    – stateName (S)
    – country (C)
  • 40.  2002 Prentice Hall. All rights reserved.
    7.10.1 Java Keystores and keytool (cont.)
    • To generate a public and private key pair
    keytool –genkey –alias MyCertificate
    • Obtain digital certificate from certificate authority
    keytool –certreq –alias MyCertificate –file myRequest.cer
    • Submit certificate file to authority
    – follow authority’s steps on Web site
    • To generate certificate other users may use
    keytool –export –alias MyCertificate –file myCertificate.cer
  • 41.  2002 Prentice Hall. All rights reserved.
    7.11 Java Policy Files
    • Basis for Java security is Java Sandbox
    – protected environment in which Java applications run
    • User must grant application resource permissions
    • Java Sandbox security model comprised of
    – bytecode verifier
    – class loader
    – security manager
    • Permissions
    – granted on basis of security policy
    – comprised of varying levels of access to system resources
    • common examples:
    – writing to files
    – connecting to identified port on host machine
  • 42.  2002 Prentice Hall. All rights reserved.
    7.11 Java Policy Files (cont.)
    – policy files declare permissions explicitly
    • permission not declared explicitly, permission not granted
    • system-wide policy loaded automatically by JVM
    – java.policy located in lib/security folder
    • particular applications can specify custom security policy files
    – do not compromise original system-wide configuration
  • 43.  2002 Prentice Hall. All rights reserved.
    7.11 Java Policy Files (cont.)
    Permission Desc rip tion
    java.security.AllPermission
    Grants all possible permissions. Developers
    should use this permission only for testing
    purposes as this permission disables all security
    checks.
    java.io.FilePermission
    Grants access to particular sets of files for
    reading, writing and deleting those files.
    java.lang.RuntimePermission
    Grants permissions for modifying runtime
    behavior, such as the allowing a program to exit
    the virtual machine, change the source of
    System.in and queue print jobs.
    java.net.SocketPermission
    Grants permission to create socket connections
    for connecting to other computers over the
    network. This permission allows fine-grained
    control over particular ports, host names and
    connection types.
    java.net.NetPermission
    Grants permission to modify to network
    properties, such as the host with which to validate
    usernames and passwords.
    Fig. 7.9 S
    ome p ermissions a va ila b le in the Ja va 2 sec urity mod el.
  • 44.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.10
    AuthorizedFileWr
    iter writes to file
    using a security
    manager.
    Line 15
    Lines 26-39
    1 // AuthorizedFileWriter.java
    2 // AuthorizedFileWriter writes to file using a security manager.
    3 // Permissions must be given via policy files.
    4 package com.deitel.advjhtp1.security.policyfile;
    5
    6 // Java core package
    7 import java.io.*;
    8
    9 public class AuthorizedFileWriter {
    10
    11 // launch application
    12 public static void main( String[] args )
    13 {
    14 // create and set security manager
    15 System.setSecurityManager( new SecurityManager() );
    16
    17 // check command-line arguments for proper usage
    18 if ( args.length != 2 )
    19 System.err.println( “Usage: java com.deitel.advjhtp1.” +
    20 “security.policyfile.AuthorizedFileWriter file ” +
    21 “filebody” );
    22
    23 // write fileBody to file
    24 else {
    25
    26 String file = args[ 0 ];
    27 String fileBody = args[ 1 ];
    28
    29 // write fileBody to file
    30 try {
    31
    32 // create FileWriter
    33 FileWriter fileWriter = new FileWriter( file );
    34
    35 fileWriter.write( fileBody );
    SecurityManager
    protects against
    unauthorized access
    write to file
  • 45.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.10
    AuthorizedFileWr
    iter writes to file
    using a security
    manager.
    36
    37 fileWriter.close();
    38
    39 System.exit( 0 );
    40 }
    41
    42 // handle IO exception
    43 catch ( IOException ioException ) {
    44 ioException.printStackTrace();
    45 System.exit( 1 );
    46 }
    47 }
    48 }
    49 }
  • 46.  2002 Prentice Hall. All rights reserved.
    7.11 Java Policy Files
    • authorized.policy
    – grants write FilePermission for file authorized.txt
    – commandline
    • java –Djava.security.policy=authorized.policy
    com.deitel.advjhtp1.security.policyfile.AuthorizedFi
    leWriter “authorized.txt” “Policy file
    authorized.policy granted file write permission for
    file authorized.txt.”
    – if command line specifies different file, permission is denied
  • 47.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.11 Policy file
    grants permission
    to write to file
    authorized.txt
    Line 7
    1 // authorized.policy
    2 // Policy file that grants file write permission
    3 // only to file “authorized.txt”
    4
    5 grant {
    6 permission java.io.FilePermission
    7 “authorized.txt”, “write”;
    8 };
    authorize write
    permission to file
    authorized.txt
  • 48.  2002 Prentice Hall. All rights reserved.
    7.11 Java Policy Files (cont.)
    • codebase_authorized.policy
    – grants c:/myclasses codebase write
    FilePermission for file
    codebase_authorized.txt
    – commandline
    • java –Djava.security.policy=codebase_authorized.policy
    com.deitel.advjhtp1.security.policyfile.AuthorizedFileWr
    iter “codebase_authorized.txt” “Policy file
    codebase_authorized.policy granted file write permission
    for file codebase_authorized.txt to codebase
    c:/myclasses.”
    – if code executing from different codebase, permission denied
  • 49.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.12 Policy file
    grants permission
    to the specified
    codebase.
    Line 7
    1 // codebase_authorized.policy
    2 // Policy file that grants write permission to
    3 // file “codebase_authorized.txt” for codebase “C:/myclasses”
    4
    5 grant codebase “file:/C:/myclasses” {
    6 permission java.io.FilePermission
    7 “codebase_authorized.txt”, “write”;
    8 };
    authorizes write
    permission to codebase
    c:/myclasses
  • 50.  2002 Prentice Hall. All rights reserved.
    7.12 Digital Signatures for Java Code
    • Distributing applets with special permissions
    – must sign applets with digital signatures
    • enables users to verify applet originated from trusted company
    • FileTreePanel displays tree of user’s files
    – Java sandbox does not allow default file access from applets
    • must sign applet
    – Java Plug-in prompts user of digital signature
    – user grants permission
    • must store applet in JAR file
  • 51.  2002 Prentice Hall. All rights reserved.
    7.12 Digital Signatures for Java Code
    (cont.)
    Directory Name File Name
    comdeiteladvjhtp1securitysignatures
    FileTreeApplet.class
    FileTreePanel.class
    FileTreePanel$1.class
    comdeiteladvjhtp1mvctreefilesystem
    FileSystemModel.class
    FileSystemModel$TreeFile.class
    Fig. 7.14 File listing for FileTreeApplet.jar.
  • 52.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.13 Applet that
    browses a user’s
    local filesystem.
    1 // FileTreeApplet.java
    2 // A JApplet that browses files on the local file system
    3 // using a FileTreePanel.
    4 package com.deitel.advjhtp1.security.signatures;
    5
    6 // Java extension packages
    7 import javax.swing.*;
    8
    9 // Deitel packages
    10 import com.deitel.advjhtp1.security.signatures.FileTreePanel;
    11
    12 public class FileTreeApplet extends JApplet {
    13
    14 // initialize JApplet
    15 public void init()
    16 {
    17 // get rootDirectory from user
    18 String rootDirectory = JOptionPane.showInputDialog( this,
    19 “Please enter a directory name:” );
    20
    21 // create FileTreePanel for browsing user’s hard drive
    22 FileTreePanel panel = new FileTreePanel( rootDirectory );
    23
    24 getContentPane().add( panel );
    25 }
    26 }
  • 53.  2002 Prentice Hall. All rights reserved.
    7.12 Digital Signatures for Java Code
    (cont.)
    • Java Plug-in supports RSA-signed applets
    • Steps
    – generate RSA keypair
    keytool –genkey –keyalg RSA –alias MyCertificate
    – export digital signature to file
    keytool –export –alias MyCertificate –file myCertificate.cer
    – add to keystore
    keytool –import –alias MyTrustedCertificate –keystore cacerts
    –file myCertificate.cer
    • cacerts is complete path to keystore
    – sign applet’s JAR file with digital signature
    jarsigner FileTreeApplet.jar MyCertificate
    – enable Java Plug-in instead of Web browser’s JVM
    htmlconverter signedApplet.html
  • 54.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.15 HTML file
    for
    FileTreeApplet.
    Line 13
    1 <html>
    2
    3 <head>
    4 <title>FileTreeApplet Signed Applet</title>
    5 </head>
    6
    7 <body>
    8
    9 <h1>File Browser</h1>
    10
    11 <applet
    12 code = “com.deitel.advjhtp1.security.signatures.FileTreeApplet”
    13 archive = “FileTreeApplet.jar” width = “400” height = “200”>
    14 </applet>
    15
    16 </body>
    17
    18 </html>
    signed applet jar file
  • 55.  2002 Prentice Hall. All rights reserved.
    7.12 Digital Signatures for Java Code
    (cont.)
    Fig. 7.16 Java Plug-in security warning when loading a signed applet.
  • 56.  2002 Prentice Hall. All rights reserved.
    7.12 Digital Signatures for Java Code
    (cont.)
    Fig. 7.17 FileTreeApplet browsing the D:jdk1.3.1 directory.
  • 57.  2002 Prentice Hall. All rights reserved.
    7.13 Authentication
    • Current authentication models
    – restrict access to certain aspects of a program
    – allow users to connect to a network
    – regulate resources available to users on network
    • Java Authentication and Authorization Service
    (JAAS)
    – based on plug-in framework
    – allows Kerberos and single sign-on implementations
  • 58.  2002 Prentice Hall. All rights reserved.
    7.13.1 Kerberos
    • Employs secret key cryptography
    • Authentication handled by
    – Kerberos system
    • authenticates client’s identity
    – secondary Ticket Granting Service (TGS)
    • similar to key distribution centers
    • authenticates client’s rights to access services
    • Authentication cycle
    1. client submits user name and password to Kerberos server
    2. server returns Ticket-Granting Ticket (TGT)
    • encrypted with client’s key
    3. client decrypts TGT
    4. client requests service ticket by sending decrypted TGT to TGS
    5. server authorizes client with renewable service ticket
  • 59.  2002 Prentice Hall. All rights reserved.
    7.13.2 Single Sign-On
    • Single sign-on allows users to log into different
    servers once with single password.
    • three types:
    1. workstation login scripts
    • login script sends password to each application
    – stores password on workstation
    2. authentication server scripts
    • authenticate users with central server
    3. tokens
    • once authenticated, non-reusable token identifies user
  • 60.  2002 Prentice Hall. All rights reserved.
    7.13.3 Java Authentication and
    Authorization Service (JAAS)
    • Protects applications from unauthorized users.
    • Based on Pluggable Authentication Module (PAM)
    – supports multiple authentication systems
    – different authentication systems may be combined
    • Can control access by
    – user
    • governs access to resources on user policies
    – group
    • associates user to group, bases policies on group privileges
    – role-based security policies
    • similar to group policies
    • unlike group policies, no default policies exist
    – users obtain privileges to needed applications based on
    intended task
  • 61.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.18
    AuthenticateNT
    uses the
    NTLoginModule to
    authenticate a user
    and invoke a
    PrivilegedAction
    .
    Lines 20-21
    Line 24
    Line 31
    Line 34
    1 // AuthenticateNT.java
    2 // Authenticates a user using the NTLoginModule and performs
    3 // a WriteFileAction PrivilegedAction.
    4 package com.deitel.advjhtp1.security.jaas;
    5
    6 // Java extension packages
    7 import javax.swing.*;
    8 import javax.security.auth.*;
    9 import javax.security.auth.login.*;
    10
    11 public class AuthenticateNT {
    12
    13 // launch application
    14 public static void main( String[] args )
    15 {
    16 // authenticate user and perform PrivilegedAction
    17 try {
    18
    19 // create LoginContext for AuthenticateNT context
    20 LoginContext loginContext =
    21 new LoginContext( “AuthenticateNT” );
    22
    23 // perform login
    24 loginContext.login();
    25
    26 // if login executes without exceptions, login
    27 // was successful
    28 System.out.println( “Login Successful” );
    29
    30 // get Subject now associated with LoginContext
    31 Subject subject = loginContext.getSubject();
    32
    33 // display Subject details
    34 System.out.println( subject );
    35
    create new
    LoginContext
    with name
    AuthenticateNT
    begin authentication process
    obtains Subject, which
    represents particular user or
    entity (this particular case,
    user currently logged in)
    prints Subject’s
    information including
    Principals
    (represent different
    role or identities a user
    assumes during
    particular log session)
  • 62.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.18
    AuthenticateNT
    uses the
    NTLoginModule to
    authenticate a user
    and invoke a
    PrivilegedAction
    .
    Line 37
    Line 40
    36 // perform the WriteFileAction as current Subject
    37 Subject.doAs( subject, new WriteFileAction() );
    38
    39 // log out current Subject
    40 loginContext.logout();
    41
    42 System.exit( 0 );
    43
    44 } // end try
    45
    46 // handle exception loggin in
    47 catch ( LoginException loginException ) {
    48 loginException.printStackTrace();
    49 System.exit( -1 );
    50 }
    51
    52 } // end method main
    53 }
    Login Successful
    Subject:
    Principal: NTUserPrincipal:
    userName: santry
    Principal: NTDomainPrincipal:
    domainName DEITEL
    Principal: NTSidUserPrincipal:
    NTSid: S-1-5-21-1275210071-1682526488-1343024091-1000
    Principal: NTSidPrimaryGroupPrincipal:
    NTSid: S-1-5-21-1275210071-1682526488-1343024091-513
    Principal: NTSidGroupPrincipal:
    NTSid: S-1-5-21-1275210071-1682526488-1343024091-513
    make request using given Subject and
    priviledgedAction instance
    log out from current
    LoginContext
  • 63.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.18
    AuthenticateNT
    uses the
    NTLoginModule to
    authenticate a user
    and invoke a
    PrivilegedAction
    .
    Principal: NTSidGroupPrincipal:
    NTSid: S-1-1-0
    Principal: NTSidGroupPrincipal:
    NTSid: S-1-5-32-544
    Principal: NTSidGroupPrincipal:
    NTSid: S-1-5-32-545
    Principal: NTSidGroupPrincipal:
    NTSid: S-1-5-5-0-39645
    Principal: NTSidGroupPrincipal:
    NTSid: S-1-2-0
    Principal: NTSidGroupPrincipal:
    NTSid: S-1-5-4
    Principal: NTSidGroupPrincipal:
    NTSid: S-1-5-11
    Public Credential: NTNumericCredential:
    value: 896
  • 64.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.19
    WriteFileAction
    is a
    PrivilegedAction
    for writing a simple
    text file.
    Line 10
    1 // WriteFileAction.java
    2 // WriteFileAction is a PrivilegedAction implementation that
    3 // simply writes a file to the local file system.
    4 package com.deitel.advjhtp1.security.jaas;
    5
    6 // Java core packages
    7 import java.io.*;
    8 import java.security.PrivilegedAction;
    9
    10 public class WriteFileAction implements PrivilegedAction {
    11
    12 // perform the PrivilegedAction
    13 public Object run()
    14 {
    15 // attempt to write a message to the specified file
    16 try {
    17 File file = new File( “D:/”, “privilegedFile.txt” );
    18 FileWriter fileWriter = new FileWriter( file );
    19
    20 // write message to File and close FileWriter
    21 fileWriter.write( “Welcome to JAAS!” );
    22 fileWriter.close();
    23 }
    24
    25 // handle exception writing file
    26 catch ( IOException ioException ) {
    27 ioException.printStackTrace();
    28 }
    29
    30 return null;
    31
    32 } // end method run
    33 }
    implements interface
    PrivilegedAction
  • 65.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.20
    Configuration file
    for authentication
    using
    NTLoginModule.
    Line 5
    1 // jaas.config
    2 // Configures JAAS to use NTLoginModule
    3 // for authentication.
    4 AuthenticateNT {
    5 com.sun.security.auth.module.NTLoginModule required debug=false;
    6 };
    subject must
    authenticate with
    NTLoginModule
  • 66.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.21 JAAS
    policy file for
    granting
    permissions to a
    Principal and
    codebase.
    Line 4
    Line 3
    Lines 6-7
    Lines 9-10
    1 // jaas.policy
    2 // Policy file defining the permissions for the named Principal
    3 grant codeBase “file:D:/JavaProjects/advjhtp1/src/-“,
    4 Principal com.sun.security.auth.NTUserPrincipal “santry” {
    5
    6 permission java.io.FilePermission “D:/privilegedFile.txt”,
    7 “write”;
    8
    9 permission java.io.FilePermission “D:/privilegedFile.txt”,
    10 “read”;
    11 };
    target subject
    grant write permissions to
    D:/privilegedFile.txt
    grant read permissions to
    D:/privilegedFile.txt
    codebase to which
    apply permissions
  • 67.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.22 Policy file
    for JAAS
    application.
    Line 6
    Line 13
    Lines 15-19
    1 // java.policy
    2 // Policy file that grants AllPermission
    3 // to JAAS modules and specific permissions
    4 // to the D:ProjectsJava codebase.
    5 grant codebase “file:/D:/jdk1.3.1/jre/lib/ext/jaas.jar” {
    6 permission java.security.AllPermission;
    7 };
    8
    9 grant codebase “file:/D:/JavaProjects/advjhtp1/src/-” {
    10 permission javax.security.auth.AuthPermission
    11 “createLoginContext”;
    12
    13 permission javax.security.auth.AuthPermission “doAs”;
    14
    15 permission java.io.FilePermission “D:/privilegedFile.txt”,
    16 “write”;
    17
    18 permission java.io.FilePermission “D:/privilegedFile.txt”,
    19 “read”;
    20 };
    enables JAAS to perform
    authentication on behalf of application
    grants permission to
    execute
    PrivilegedActions
    using method doAs
    permission to read and write file
    D:/privilegedFile.txt
  • 68.  2002 Prentice Hall. All rights reserved.
    7.13.3 Java Authentication and
    Authorization Service (JAAS) (cont.)
    • To execute AuthenticateNT:
    java –Djava.security.policy==java.policy
    -Djava.security.auth.policy==jaas.policy
    -Djava.security.auth.login.config==jaas.config
    com.deitel.advjhtp1.security.jaas.AuthenticateNT
  • 69.  2002 Prentice Hall. All rights reserved.
    7.14 Secure Sockets Layer (SSL)
    • Nonproprietary protocol
    • Used to secure communications between computers
    • Implements
    – public-key technology using RSA algorithm
    – digital certificates
    • to authenticate server
    • to protect private information
    • Does not require user authentication
  • 70.  2002 Prentice Hall. All rights reserved.
    7.14 Secure Sockets Layer (SSL) (cont.)
    • Process:
    1. client sends message to server
    2. server responds with digital certificate
    3. client and server negotiate session keys
    • use public key cryptography for negotiation
    4. once keys established, communication proceeds
    • information encrypted
    • information transmitted
    • information decrypted at receiving end
    • Primarily secure point-to-point connections
  • 71.  2002 Prentice Hall. All rights reserved.
    7.14.1 Java Secure Socket Extension
    (JSSE)
    • SSL encryption integrated into Java through Java
    Secure Socket Extension (JSEE).
    • Secures passage of information between two clients.
    • Use of SSL connections transparent to user.
  • 72.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.23
    LoginServer uses
    an
    SSLServerSocket
    for secure
    communication.
    Line 25
    Line 29
    1 // LoginServer.java
    2 // LoginServer uses an SSLServerSocket to demonstrate JSSE’s
    3 // SSL implementation.
    4 package com.deitel.advjhtp1.security.jsse;
    5
    6 // Java core packages
    7 import java.io.*;
    8
    9 // Java extension packages
    10 import javax.net.ssl.*;
    11
    12 public class LoginServer {
    13
    14 private static final String CORRECT_USER_NAME = “Java”;
    15 private static final String CORRECT_PASSWORD = “HowToProgram”;
    16
    17 private SSLServerSocket serverSocket;
    18
    19 // LoginServer constructor
    20 public LoginServer() throws Exception
    21 {
    22 // SSLServerSocketFactory for building SSLServerSockets
    23 SSLServerSocketFactory socketFactory =
    24 ( SSLServerSocketFactory )
    25 SSLServerSocketFactory.getDefault();
    26
    27 // create SSLServerSocket on specified port
    28 serverSocket = ( SSLServerSocket )
    29 socketFactory.createServerSocket( 7070 );
    30
    31 } // end LoginServer constructor
    32
    obtains factory object
    create SSL socket
  • 73.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.23
    LoginServer uses
    an
    SSLServerSocket
    for secure
    communication.
    Line 46
    Lines 49-55
    Lines 57-58
    Lines 60-61
    33 // start server and listen for clients
    34 private void runServer()
    35 {
    36 // perpetually listen for clients
    37 while ( true ) {
    38
    39 // wait for client connection and check login information
    40 try {
    41
    42 System.err.println( “Waiting for connection…” );
    43
    44 // create new SSLSocket for client
    45 SSLSocket socket =
    46 ( SSLSocket ) serverSocket.accept();
    47
    48 // open BufferedReader for reading data from client
    49 BufferedReader input = new BufferedReader(
    50 new InputStreamReader( socket.getInputStream() ) );
    51
    52 // open PrintWriter for writing data to client
    53 PrintWriter output = new PrintWriter(
    54 new OutputStreamWriter(
    55 socket.getOutputStream() ) );
    56
    57 String userName = input.readLine();
    58 String password = input.readLine();
    59
    60 if ( userName.equals( CORRECT_USER_NAME ) &&
    61 password.equals( CORRECT_PASSWORD ) ) {
    62
    63 output.println( “Welcome, ” + userName );
    64 }
    65
    66 else {
    67 output.println( “Login Failed.” );
    accepts new client connection
    obtain input and
    output streams
    read first two lines of text.
    Details of encryption hidden
    from developer.
    verify user name and
    password
  • 74.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.23
    LoginServer uses
    an
    SSLServerSocket
    for secure
    communication.
    Lines 71-73
    68 }
    69
    70 // clean up streams and SSLSocket
    71 output.close();
    72 input.close();
    73 socket.close();
    74
    75 } // end try
    76
    77 // handle exception communicating with client
    78 catch ( IOException ioException ) {
    79 ioException.printStackTrace();
    80 }
    81
    82 } // end while
    83
    84 } // end method runServer
    85
    86 // execute application
    87 public static void main( String args[] ) throws Exception
    88 {
    89 LoginServer server = new LoginServer();
    90 server.runServer();
    91 }
    92 }
    close all streams
  • 75.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.24
    LoginClient
    communicates with
    LoginServer via
    SSL.
    Lines 22-23
    Lines 26-28
    Lines 31-32
    1 // LoginClient.java
    2 // LoginClient uses an SSLSocket to transmit fake login
    3 // information to LoginServer.
    4 package com.deitel.advjhtp1.security.jsse;
    5
    6 // Java core packages
    7 import java.io.*;
    8
    9 // Java extension packages
    10 import javax.swing.*;
    11 import javax.net.ssl.*;
    12
    13 public class LoginClient {
    14
    15 // LoginClient constructor
    16 public LoginClient()
    17 {
    18 // open SSLSocket connection to server and send login
    19 try {
    20
    21 // obtain SSLSocketFactory for creating SSLSockets
    22 SSLSocketFactory socketFactory =
    23 ( SSLSocketFactory ) SSLSocketFactory.getDefault();
    24
    25 // create SSLSocket from factory
    26 SSLSocket socket =
    27 ( SSLSocket ) socketFactory.createSocket(
    28 “localhost”, 7070 );
    29
    30 // create PrintWriter for sending login to server
    31 PrintWriter output = new PrintWriter(
    32 new OutputStreamWriter( socket.getOutputStream() ) );
    33
    create SSL socket
    factory
    create SSL socket
    create output stream
  • 76.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.24
    LoginClient
    communicates with
    LoginServer via
    SSL.
    Line 39
    Line 46
    Lines 51-52
    Line 55
    Lines 61-63
    34 // prompt user for user name
    35 String userName = JOptionPane.showInputDialog( null,
    36 “Enter User Name:” );
    37
    38 // send user name to server
    39 output.println( userName );
    40
    41 // prompt user for password
    42 String password = JOptionPane.showInputDialog( null,
    43 “Enter Password:” );
    44
    45 // send password to server
    46 output.println( password );
    47
    48 output.flush();
    49
    50 // create BufferedReader for reading server response
    51 BufferedReader input = new BufferedReader(
    52 new InputStreamReader( socket.getInputStream () ) );
    53
    54 // read response from server
    55 String response = input.readLine();
    56
    57 // display response to user
    58 JOptionPane.showMessageDialog( null, response );
    59
    60 // clean up streams and SSLSocket
    61 output.close();
    62 input.close();
    63 socket.close();
    64
    65 } // end try
    66
    send password to server
    create input stream
    obtain server response
    send user name to server
    close all streams
  • 77.  2002 Prentice Hall.
    All rights reserved.
    Outline
    Fig. 7.24
    LoginClient
    communicates with
    LoginServer via
    SSL.
    67 // handle exception communicating with server
    68 catch ( IOException ioException ) {
    69 ioException.printStackTrace();
    70 }
    71
    72 // exit application
    73 finally {
    74 System.exit( 0 );
    75 }
    76
    77 } // end LoginClient constructor
    78
    79 // execute application
    80 public static void main( String args[] )
    81 {
    82 new LoginClient();
    83 }
    84 }
  • 78.  2002 Prentice Hall. All rights reserved.
    7.14.1 Java Secure Socket Extension
    (JSSE) (cont.)
    Fig. 7.25 Two sample executions of class LoginClient.
  • 79.  2002 Prentice Hall. All rights reserved.
    7.14.1 Java Secure Socket Extension
    (JSSE) (cont.)
    • SSL requires LoginServer use certificate.
    – using keytool
    keytool –genkey –keystore SSLStore –alias SSLCertificate
    • To execute LoginServer
    – specify keystore contining LoginServer’s certificate
    java –Djavax.net.ssl.keyStore=SSLStore
    -Djavax.net.ssl.keyStorePassword=password
    com.deitel.advjhtp1.security.jsse.LoginServer
    where password is keystore password
    • To execute LoginClient
    – specify keystore contining LoginClient’s certificate
    java –Djavax.net.ssl.trustStore=SSLStore
    -Djavax.net.ssl.trustStorePassword=password
    com.deitel.advjhtp1.security.jsse.LoginClient
    where password is truststore password
  • 80.  2002 Prentice Hall. All rights reserved.
    7.15 Java Language Security and Secure
    Coding
    • Java language provides security other languages
    lack.
    – e.g., JVM ensures memory beyond end of array not read
    • Java compiler performs security checks compiling
    – classes do not read from uninitialized variables
    – access modifiers ensure method access rights
    • private
    • public
    • protected
    – detects illegal casts between data types
    • Bytecode verifier
    – ensures that byte codes do not perform illegal operations
  • 81.  2002 Prentice Hall. All rights reserved.
    7.15 Java Language Security and Secure
    Coding (cont.)
    • JVM performs remaining integrity checks
    – checks remaining cast operations
    – array-bounds checking
    – class loaders use separate namespaces
    • prevents malicious code from interacting with safe code
    – Java security manager
    • performs access permission checks while code is running

[ad_2]

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More