Está en la página 1de 22

Instituto Tecnologico de Cd. Juarez, Chih.

METODOLOGIA: 1-Analisis de los mdulos 2-creacion del espacio de trabajo 3-carga de los mdulos java ,compilacin ,ejecucin. 1.- Anlisis de los modulos. Basados en el articulo Original escrito por @Giulio , para wikijava , se hara un anlisis extensivo y traduccin del articulo originalmente escrito en ingles, para que sea lo mas sencillo de comprender y de fcil implementacin. La extensin criptogrfica de Java. Es un ejemplo sencillo de cmo se puede cifrar y descifrar un mensaje de cadena utilizando una clave privada. Vista rpida. Se puede separar el proceso en pocos pasos: 1-Generar la llave privada 2- Cifrar el mensaje usando la llave privada 3- Descifrar el mensaje comenzando desde el mensaje cifrado y la llave privada. En este ejemplo se utiliza un algoritmo de llave privada para cifrado y descifrado. Generar la llave privada El siguiente cdigo genera la la llave de seguridad en Java, que es un algoritmo valido de encriptacin .

private Key key; private void generateKey() throws NoSuchAlgorithmException { KeyGenerator generator; generator = KeyGenerator.getInstance("DES"); generator.init(new SecureRandom()); key = generator.generateKey(); } El mtodo getinstance (Algoritmo para cadenas ) de la clase javax.crypto.KeyGenerator regresa objetos de la clase para el algoritmo. El objeto generador debera ser inicializado con java.securiry.SecureRandom que autoriza una generacin segura de nmeros aleatorios. De esta manera necesitamos que el numero aleatorio sea criptogrficamente fuerte. Finalmente nosotros podemos generar la llave secreta de cifrado, esto se hace usando el mtodo generateKey() que regresa java.security.Key que necesitamos Encriptar el mensaje Ahora entramos en la parte interesante del juego, el cifrado de un mensaje. Hay tres pasos a seguir en esto:

-1 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih.

1.construir el objeto de cifrado que se encargar de realizar el cifrado. 2.convertir el mensaje a un formato adecuado para el cifrado 3.convertir el mensaje cifrado a un formato que va a ser fcil para leer en la pantalla (este paso no es realmente necesario, pero lo hacemos Vea los comentarios en el cdigo para ms detalles: private String encrypt(String message) throws IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException { // Get a cipher object. Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); // Gets the raw bytes to encrypt, UTF8 is needed for // having a standard character set byte[] stringBytes = message.getBytes("UTF8"); // encrypt using the cypher byte[] raw = cipher.doFinal(stringBytes); // converts to base64 for easier display. BASE64Encoder encoder = new BASE64Encoder(); String base64 = encoder.encode(raw); return base64; }

Descifrar el mensaje
Los pasos para descifrar el mensaje son, bsicamente, hacer los pasos atrs en el orden inverso, como el cifrado: 1.Obtener un sistema de cifrado, lo mismo que para el cifrado, slo ahora est en DECRYPT_MODE 2. decodificar el mensaje codificado BASE64, tenemos que pasar al desencriptador exactamente la misma cadena que obtuvimos del encriptador. 3. Desencriptar el mensaje mediante el cifrado 4. Convertir el arreglo de bytes para descifrar la secuencia de modo que se pueden imprimir fcilmente

-2 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih.

Nota: el nico dato en comn entre el cifrado y descifrado de los mtodos es la clave. private String decrypt(String encrypted) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException { // Get a cipher object. Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key); //decode the BASE64 coded message BASE64Decoder decoder = new BASE64Decoder(); byte[] raw = decoder.decodeBuffer(encrypted); //decode the message byte[] stringBytes = cipher.doFinal(raw); //converts the decoded message to a String String clear = new String(stringBytes, "UTF8"); return clear; }

2. Creacin del espacio de trabajo y carga de mdulos para la compilacin y ejecucin de el programa criptografa.
Abrir java Netbeans IDE 7.0

-3 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih.

Verificar que no existe algn espacio de trabajo abierto, de algn proyecto anterior en ,en caso de existir procedemos a cerrarlo. En el men File -> Close Project.

-4 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih.

Procedemos a la creacin de un nuevo proyecto para cargar el archivo StringEncrypter.java el cual contiene varios mtodos de encriptacin como DES Blowfish y DESede. En el men File -> New Project

3.-Carga de los modulos Java Compilacin y Ejecucin . Al seleccionar New Project aparecer la ventana en la cual se debe seleccionar el tipo de aplicacin JAVA, para este caso se selecciona JAVA y Java Application.

-5 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih.

Una vez seleccionada la aplicacin , se debe asignar el nombre al proyecto, en este caso el nombre que se utilizo fue cryptomensaje, es importante quitar la seleccin de la casilla Create Main Class.

-6 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih.

Como se observa en la figura ,se ha creado un proyecto vacio al cual se le adicionara un modulo , que es el modulo StringEncrypter.java

el directorio raz para los proyectos es NetBeansProjects , en esta carpeta se encuentran todos los proyectos creados.

-7 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih.

En este caso el nombre que se le asigno al proyecto fue cryptomensaje , se puede observar claramente la existencia de la carpeta que contiene, todos los archivos,fuentes del proyecto.

-8 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih. Una vez abierto el directorio los modulos del proyecto se cargan en la carpeta src

Aqu pegaremos el modulo StringEncrypter.java

-9 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih.

Una vez que se copio al directorio src el modulo StringEncryper.java automticamente el compilador NetBeans 7.0 detectara los nuevos modulos y los aadir al proyecto.

Como en la figura anterior , se puede observar que el modulo ya fue agregado ,el siguiente paso en el proceso, abrimos el men Run despus en Build Main Project

- 10 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih.

Cuando se cre el proyecto principal , le especificamos que no creara ninguna clase principal, esto debido a que el modulo que deseamos compilar ,ya contiene la clase principal, el nombre de la clase principal: es el nombre de la direccin donde podr investigar ms acerca de la creacin de este programa de forma extensiva a la que puede encontrar en este manual .

- 11 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih.

Si el programa no detecto errores se podr ejecutar sin ningn problema. Para esto en el men Run despus en Run Main Project.

La salida del programa se muestra en la figura. Se utiizan dos cadenas para alimentar al programa sistemas operativos e. cervantes

- 12 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih. Instituto tecnolgico de ciudad Jurez

Practicas.
Describa el programa: 1. Escriba el nombre de las funciones o mtodos para los distitntos algoritmos de encryptacion: DES, blowfish, y DESede dentro del programa. 2. Investigue y elabore un resumen de las las libreras que utiliza java para encriptacin 3. Describa porque es importante el cifrado en los sistemas operativos y haga la descripcin de las caractersticas de seguridad de LINUX UBUNTU LUCID LYNX. 4. Compile y ejecute el programa ,que deber entregar en en formato .jar, 5. Describa la salida del programa.

- 13 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih.

Sugerencias Didcticas.
Se sugiere que la practica sea realizada de manera individual en la computadora del alumno de manera que cada estudiante realice los ejercicios especificados. Fomentar la bsqueda la informacin en diversas fuentes (Libros, Revistas; Internet)

Reportar.
Las practicas o ejercicios que se piden y estas podrn ser enviadas al correo del maestro, para una evaluacin rpida, pero se recomienda elaborar reportes que se piden en las practicas que debern ser entregadas al maestro para la firma correspondiente y evaluacin definitiva de la practica y poder compartirlas con los compaeros en el aula..

Evaluacin:
Firmara y calificara las practicas entregadas, podr y pedir al azar que alumno que realice determinada practica. Para que la pueda compartir con la clase. Revision de cuestionarios. Fuentes http://www.wikijava.org/wiki/Secret_Key_Cryptography_Tutorial#Generate_th e_encryption_key Jess Carretero Perez, Felix Garcia Caballeira, Fernandp Perez costolla. Practicas de sistemas operativos (de la base al diseo) Guia del lenguaje en programacin C. Editorial: Mc Graw Hill interamericana de Espaa S.A.U. Andrew S. Tanenbaun. Sistemas Operativos Modernos. Segunda Edicin. Editorial: Pearson Education Mexico 2003. Abraham Silberschats, Peter Baer Galvin, Greg Gagne. Fundamentos de sistemas operativos. Septima Edicion. Editorial: Mc graw Hill/Interamericana de Espaa S.A.U. 2006.

- 14 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih.

ANEXO A: package org.wikijava.cryptography.generalExamples; //----------------------------------------------------------------------------//StringEncrypter.java //----------------------------------------------------------------------------/* * ================================================================= ============ * Copyright (c) 1998-2007 Jeffrey M. Hunter. All rights reserved. * * All source code and material located at the Internet address of * http://www.idevelopment.info is the copyright of Jeffrey M. Hunter and * is protected under copyright laws of the United States. This source code may * not be hosted on any other site without my express, prior, written * permission. Application to host any of the material elsewhere can be made by * contacting me at jhunter@idevelopment.info. * * I have made every effort and taken great care in making sure that the source * code and other content included on my web site is technically accurate, but I * disclaim any and all responsibility for any loss, damage or destruction of * data or any other property which may arise from relying on it. I will in no * case be liable for any monetary damages arising from such loss, damage or * destruction. * * As with any code, ensure to test this code in a development environment * before attempting to run it in production. * ================================================================= ============ */ //CIPHER / GENERATORS import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.KeyGenerator; //KEY SPECIFICATIONS import java.security.spec.KeySpec; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.spec.PBEKeySpec;

- 15 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih. import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEParameterSpec; //EXCEPTIONS import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; import java.security.spec.InvalidKeySpecException; import javax.crypto.NoSuchPaddingException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import java.io.UnsupportedEncodingException; import java.io.IOException; /** * ----------------------------------------------------------------------------* The following example implements a class for encrypting and decrypting * strings using several Cipher algorithms. The class is created with a key and * can be used repeatedly to encrypt and decrypt strings using that key. Some of * the more popular algorithms are: Blowfish DES DESede PBEWithMD5AndDES * PBEWithMD5AndTripleDES TripleDES * * @version 1.0 * @author Jeffrey M. Hunter (jhunter@idevelopment.info) * @author http://www.idevelopment.info * ----------------------------------------------------------------------------*/ public class StringEncrypter { Cipher ecipher; Cipher dcipher; /** * Constructor used to create this object. Responsible for setting and * initializing this object's encrypter and decrypter Chipher instances * given a Secret Key and algorithm. * * @param key * Secret Key used to initialize both the encrypter and * decrypter instances. * @param algorithm * Which algorithm to use for creating the encrypter and * decrypter instances.

- 16 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih. */ StringEncrypter(SecretKey key, String algorithm) { try { ecipher = Cipher.getInstance(algorithm); dcipher = Cipher.getInstance(algorithm); ecipher.init(Cipher.ENCRYPT_MODE, key); dcipher.init(Cipher.DECRYPT_MODE, key); } catch (NoSuchPaddingException e) { System.out.println("EXCEPTION: NoSuchPaddingException"); } catch (NoSuchAlgorithmException e) { System.out.println("EXCEPTION: NoSuchAlgorithmException"); } catch (InvalidKeyException e) { System.out.println("EXCEPTION: InvalidKeyException"); } } /** * Constructor used to create this object. Responsible for setting and * initializing this object's encrypter and decrypter Chipher instances * given a Pass Phrase and algorithm. * * @param passPhrase * Pass Phrase used to initialize both the encrypter and * decrypter instances. */ StringEncrypter(String passPhrase) { // 8-bytes Salt byte[] salt = { (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32, (byte) 0x56, (byte) 0x34, (byte) 0xE3, (byte) 0x03 }; // Iteration count int iterationCount = 19; try { KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES") .generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm());

- 17 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih. // Prepare the parameters to the cipthers AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount); ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec); } catch (InvalidAlgorithmParameterException e) { System.out.println("EXCEPTION: InvalidAlgorithmParameterException"); } catch (InvalidKeySpecException e) { System.out.println("EXCEPTION: InvalidKeySpecException"); } catch (NoSuchPaddingException e) { System.out.println("EXCEPTION: NoSuchPaddingException"); } catch (NoSuchAlgorithmException e) { System.out.println("EXCEPTION: NoSuchAlgorithmException"); } catch (InvalidKeyException e) { System.out.println("EXCEPTION: InvalidKeyException"); } } /** * Takes a single String as an argument and returns an Encrypted version of * that String. * * @param str * String to be encrypted * @return <code>String</code> Encrypted version of the provided String */ public String encrypt(String str) { try { // Encode the string into bytes using utf-8 byte[] utf8 = str.getBytes("UTF8"); // Encrypt byte[] enc = ecipher.doFinal(utf8); // Encode bytes to base64 to get a string return new sun.misc.BASE64Encoder().encode(enc); } catch (BadPaddingException e) { } catch (IllegalBlockSizeException e) { } catch (UnsupportedEncodingException e) { } catch (IOException e) { }

- 18 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih. return null; } /** * Takes a encrypted String as an argument, decrypts and returns the * decrypted String. * * @param str * Encrypted String to be decrypted * @return <code>String</code> Decrypted version of the provided String */ public String decrypt(String str) { try { // Decode base64 to get bytes byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str); // Decrypt byte[] utf8 = dcipher.doFinal(dec); // Decode using utf-8 return new String(utf8, "UTF8"); } catch (BadPaddingException e) { } catch (IllegalBlockSizeException e) { } catch (UnsupportedEncodingException e) { } catch (IOException e) { } return null; } /** * The following method is used for testing the String Encrypter class. This * method is responsible for encrypting and decrypting a sample String using * several symmetric temporary Secret Keys. */ public static void testUsingSecretKey() { try { System.out.println(); System.out.println("+----------------------------------------+"); System.out.println("| -- Test Using Secret Key Method -- |"); System.out.println("+----------------------------------------+");

- 19 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih. System.out.println(); String secretString = "Attack at dawn!"; // Generate a temporary key for this example. In practice, you would // save this key somewhere. Keep in mind that you can also use a // Pass Phrase. SecretKey desKey = KeyGenerator.getInstance("DES").generateKey(); SecretKey blowfishKey = KeyGenerator.getInstance("Blowfish") .generateKey(); SecretKey desedeKey = KeyGenerator.getInstance("DESede") .generateKey(); // Create encrypter/decrypter class StringEncrypter desEncrypter = new StringEncrypter(desKey, desKey .getAlgorithm()); StringEncrypter blowfishEncrypter = new StringEncrypter( blowfishKey, blowfishKey.getAlgorithm()); StringEncrypter desedeEncrypter = new StringEncrypter(desedeKey, desedeKey.getAlgorithm()); // Encrypt the string String desEncrypted = desEncrypter.encrypt(secretString); String blowfishEncrypted = blowfishEncrypter.encrypt(secretString); String desedeEncrypted = desedeEncrypter.encrypt(secretString); // Decrypt the string String desDecrypted = desEncrypter.decrypt(desEncrypted); String blowfishDecrypted = blowfishEncrypter .decrypt(blowfishEncrypted); String desedeDecrypted = desedeEncrypter.decrypt(desedeEncrypted); // Print out values System.out.println(desKey.getAlgorithm() + " Encryption algorithm"); System.out.println(" Original String : " + secretString); System.out.println(" Encrypted String : " + desEncrypted); System.out.println(" Decrypted String : " + desDecrypted); System.out.println(); System.out.println(blowfishKey.getAlgorithm() + " Encryption algorithm"); System.out.println(" Original String : " + secretString); System.out.println(" Encrypted String : " + blowfishEncrypted); System.out.println(" Decrypted String : " + blowfishDecrypted);

- 20 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih. System.out.println(); System.out.println(desedeKey.getAlgorithm() + " Encryption algorithm"); System.out.println(" Original String : " + secretString); System.out.println(" Encrypted String : " + desedeEncrypted); System.out.println(" Decrypted String : " + desedeDecrypted); System.out.println(); } catch (NoSuchAlgorithmException e) { } } /** * The following method is used for testing the String Encrypter class. This * method is responsible for encrypting and decrypting a sample String using * using a Pass Phrase. */ public static void testUsingPassPhrase() { System.out.println(); System.out.println("+----------------------------------------+"); System.out.println("| -- Test Using Pass Phrase Method -- |"); System.out.println("+----------------------------------------+"); System.out.println(); String secretString = "Attack at dawn!"; String passPhrase = "My Pass Phrase"; // Create encrypter/decrypter class StringEncrypter desEncrypter = new StringEncrypter(passPhrase); // Encrypt the string String desEncrypted = desEncrypter.encrypt(secretString); // Decrypt the string String desDecrypted = desEncrypter.decrypt(desEncrypted); // Print out values System.out.println("PBEWithMD5AndDES Encryption algorithm"); System.out.println(" Original String : " + secretString); System.out.println(" Encrypted String : " + desEncrypted); System.out.println(" Decrypted String : " + desDecrypted); System.out.println();

- 21 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

Instituto Tecnologico de Cd. Juarez, Chih.

} /** * Sole entry point to the class and application used for testing the String * Encrypter class. * * @param args * Array of String arguments. */ public static void main(String[] args) { testUsingSecretKey(); testUsingPassPhrase(); } }

- 22 Practicas de Sistemas operativos M.A. Edgardo Cervantes Manzano Febrero 2011

También podría gustarte