Java security Tutorial

Home arrow Java Tutorials arrow Security arrow Java security Tutorial
Java security Tutorial Print E-mail
Contributed by Howell   
Saturday, 17 June 2006
Security and the Java Platform(Java security Tutorial)

Underlying the Java SE Platform is a dynamic, extensible security architecture, standards-based and interoperable. Security features -- cryptography, authentication and authorization, public key infrastructure, and more -- are built in. The Java security model is based on a customizable "sandbox" in which Java software programs can run safely, without potential risk to systems or users.

An example of how to generate a secure random number(Java security Tutorial)

 try {
    
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
   
        // Get 1024 random bits
        byte[] bytes = new byte[1024/8];
        sr.nextBytes(bytes);
   
   
        // Create two secure number generators with the same seed
        int seedByteCount = 10;
        byte[] seed = sr.generateSeed(seedByteCount);
   
        sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
        SecureRandom sr2 = SecureRandom.getInstance("SHA1PRNG");
        sr2.setSeed(seed);
    } catch (NoSuchAlgorithmException e) {
    }

java Signature (Java security Tutorial)

 Java Signature is used to provide applications the functionality of a digital signature algorithm. Digital signatures are used for authentication and integrity assurance of digital data.

The signature algorithm can be, among others, the NIST standard DSA, using DSA and SHA-1. The DSA algorithm using the SHA-1 message digest algorithm can be specified as SHA1withDSA. In the case of RSA, there are multiple choices for the message digest algorithm, so the signing algorithm could be specified as, for example, MD2withRSA, MD5withRSA, or SHA1withRSA. The algorithm name must be specified, as there is no default.

Like other algorithm-based classes in Java Security, Signature provides implementation-independent algorithms, whereby a caller (application code) requests a particular signature algorithm and is handed back a properly initialized Signature object. It is also possible, if desired, to request a particular algorithm from a particular provider. See the getInstance methods.

Thus, there are two ways to request a Signature algorithm object: by specifying either just an algorithm name, or both an algorithm name and a package provider.

  • If just an algorithm name is specified, the system will determine if there is an implementation of the algorithm requested available in the environment, and if there is more than one, if there is a preferred one.
  • If both an algorithm name and a package provider are specified, the system will determine if there is an implementation of the algorithm in the package requested, and throw an exception if there is not.

A Signature object can be used to generate and verify digital signatures.

There are three phases to the use of a Signature object for either signing data or verifying a signature:

  • Initialization, with either
    a public key, which initializes the signature for verification , or
    a private key , which initializes the signature for signing and initSign.
  • Updating
  • Depending on the type of initialization, this will update the bytes to be signed or verified. See the update methods.
  • Signing or Verifying a signature on all updated bytes. See the sign methods and the verify method.
An example of creating a signature  (Java security Tutorial)

 public static byte[] createSignature(PrivateKey key, byte[] buffer) {
        try {
            Signature sig = Signature.getInstance(key.getAlgorithm());
            sig.initSign(key);
            sig.update(buffer, 0, buffer.length);
            return sig.sign();
        } catch (SignatureException e) {
        } catch (InvalidKeyException e) {
        } catch (NoSuchAlgorithmException e) {
        }
        return null;
    }

An example of  verifying a signature (Java security Tutorial)

  public static boolean verifySignature(PublicKey key, byte[] buffer, byte[] signature) {
        try {
            Signature sig = Signature.getInstance(key.getAlgorithm());
            sig.initVerify(key);
            sig.update(buffer, 0, buffer.length);
            return sig.verify(signature);
        } catch (SignatureException e) {
        } catch (InvalidKeyException e) {
        } catch (NoSuchAlgorithmException e) {
        }
        return false;
    }

Java KeyStore tutorial (Java security Tutorial)

See API from jdk


This class represents an in-memory collection of keys and certificates. It manages two types of entries:

  • Key Entry

This type of keystore entry holds very sensitive cryptographic key information, which is stored in a protected format to prevent unauthorized access.

Typically, a key stored in this type of entry is a secret key, or a private key accompanied by the certificate chain for the corresponding public key.

Private keys and certificate chains are used by a given entity for self-authentication. Applications for this authentication include software distribution organizations which sign JAR files as part of releasing and/or licensing software.

  • Trusted Certificate Entry

This type of entry contains a single public key certificate belonging to another party. It is called a trusted certificate because the keystore owner trusts that the public key in the certificate indeed belongs to the identity identified by the subject (owner) of the certificate.

This type of entry can be used to authenticate other parties.

Each entry in a keystore is identified by an "alias" string. In the case of private keys and their associated certificate chains, these strings distinguish among the different ways in which the entity may authenticate itself. For example, the entity may authenticate itself using different certificate authorities, or using different public key algorithms.

Whether keystores are persistent, and the mechanisms used by the keystore if it is persistent, are not specified here. This allows use of a variety of techniques for protecting sensitive (e.g., private or secret) keys. Smart cards or other integrated cryptographic engines (SafeKeyper) are one option, and simpler mechanisms such as files may also be used (in a variety of formats).

There are two ways to request a KeyStore object: by specifying either just a keystore type, or both a keystore type and a package provider.

  • If just a keystore type is specified: 

      KeyStore ks = KeyStore.getInstance("JKS");
 the system will determine if there is an implementation of the keystore type requested available in the environment, and if there is more than one, if there is a preferred one.

  • If both a keystore type and a package provider are specified:

      KeyStore ks = KeyStore.getInstance("JKS", "SUN");
 the system will determine if there is an implementation of the keystore type in the package requested, and throw an exception if there is not.
Before a keystore can be accessed, it must be loaded. In order to create an empty keystore, you pass null as the InputStream argument to the load method.


An example of adding a certificate to a key store (Java security Tutorial)

 public static void addToKeyStore(File keystoreFile, char[] keystorePassword,
             String alias, java.security.cert.Certificate cert) {
        try {
            // Create an empty keystore object
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
   
            // Load the keystore contents
            FileInputStream in = new FileInputStream(keystoreFile);
            keystore.load(in, keystorePassword);
            in.close();
   
            // Add the certificate
            keystore.setCertificateEntry(alias, cert);
   
            // Save the new keystore contents
            FileOutputStream out = new FileOutputStream(keystoreFile);
            keystore.store(out, keystorePassword);
            out.close();
        } catch (java.security.cert.CertificateException e) {
        } catch (NoSuchAlgorithmException e) {
        } catch (FileNotFoundException e) {
            // Keystore does not exist
        } catch (KeyStoreException e) {
        } catch (IOException e) {
        }
    }


Java Security  book

Book description

This essential Java 2 book covers Java's security mechanisms and teaches you how to work with them. It discusses class loaders, security managers, access lists, digital signatures, and authentication and shows how to use these to create and enforce your own security policy.

Last Updated ( Saturday, 17 June 2006 )

  home              contact us

 

©2006-2008 DeveloperZone.biz   All rights reserved     powered by Mambo Designed by Siteground