0% encontró este documento útil (0 votos)
144 vistas9 páginas

Aporte 2 Trabajo Colaborativo 2

El documento presenta tres puntos sobre programación en Java. El primer punto explica cómo realizar una conexión a una base de datos desde Java. El segundo punto muestra cómo implementar un chat cliente-servidor en Java. El tercer punto explica cómo implementar un algoritmo RSA para encriptar y desencriptar texto en Java.
Derechos de autor
© Attribution Non-Commercial (BY-NC)
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
144 vistas9 páginas

Aporte 2 Trabajo Colaborativo 2

El documento presenta tres puntos sobre programación en Java. El primer punto explica cómo realizar una conexión a una base de datos desde Java. El segundo punto muestra cómo implementar un chat cliente-servidor en Java. El tercer punto explica cómo implementar un algoritmo RSA para encriptar y desencriptar texto en Java.
Derechos de autor
© Attribution Non-Commercial (BY-NC)
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 9

PUNTO 1/ Trabajar un programa en JAVA (JCreatorV3 LE) con Una base de Datos teniendo en cuenta que tenga entidad

relacin

package ConexionBd;

import java.sql.*; import javax.swing.*; public class Conexion { private Connection con=null;//variable para realizar la conexion con la bd JPanel panel;//panel para poder recibir en dnde mostrar los errores

//constructor que se encarga de obtener el panel public Conexion(JPanel vent) { this.panel=vent; }

//este metodo devuelve la conexion realizada con la base de datos public Connection getCon() { return con; }

//este metodo se encarga de realizar la conexion public void setCon(String name, String user, String psw) { //cargar el driver

try { Class.forName("com.mysql.jdbc.Driver");

//si el driver carga correctamente intento conectarme con la bd try { con=DriverManager.getConnection("jdbc:mysql://localhost:3306/"+name, user,psw); }//fin del segundo try catch (Exception e) { JOptionPane.showMessageDialog(panel, "Error 002 ==> No se realiz la conexion"+

"\n"+e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE); }

}//fin del primero try catch (Exception e) { JOptionPane.showMessageDialog(panel, "Error 001 ==> No se cargo el driver"+

"\n"+e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE); } }//fin del metodo de conexion //todo get deben retornar (return) con un tipo de variable, no tiene parmetros

//ejemplo: return con

//set no retornan y son vacios, tiene parmetros

}//fin de la clase

PUNTO2/ Trabajar un programa en JAVA (JCreatorV3 LE) que genere un chat entre Cliente Servidor R// /** * ChatClient.java

* * Basado en ChatApplet de Merlin Hughes */ import java.net.*; import java.io.*; import java.awt.*; public class ChatClient extends Frame implements Runnable { protected DataInputStream i; protected DataOutputStream o; protected TextArea output; protected TextField input; protected Thread listener; public ChatClient (String title, InputStream i, OutputStream o) { super (title); this.i = new DataInputStream (new BufferedInputStream (i)); this.o = new DataOutputStream (new BufferedOutputStream (o));

setLayout (new BorderLayout ()); add ("Center", output = new TextArea ()); output.setEditable (false); add ("South", input = new TextField ()); pack (); show (); input.requestFocus (); listener = new Thread (this); listener.start (); } public void run () { try { while (true) { String line = i.readUTF (); output.appendText (line + "\n"); } } catch (IOException ex) { ex.printStackTrace (); } finally { listener = null; input.hide (); validate (); try { o.close (); } catch (IOException ex) { ex.printStackTrace (); } }

} public boolean handleEvent (Event e) { if ((e.target == input) && (e.id == Event.ACTION_EVENT)) { try { o.writeUTF ((String) e.arg); o.flush (); } catch (IOException ex) { ex.printStackTrace(); listener.stop (); } input.setText (""); return true; } else if ((e.target == this) && (e.id == Event.WINDOW_DESTROY)) { if (listener != null) listener.stop (); hide (); return true; } return super.handleEvent (e); } public static void main (String args[]) throws IOException { if (args.length != 2) throw new RuntimeException ("Syntax: ChatClient "); Socket s = new Socket (args[0], Integer.parseInt (args[1])); new ChatClient ("Chat " + args[0] + ":" + args[1], s.getInputStream (), s.getOutputStream ()); }

PUNTO 3/ Trabajar un programa en JAVA (JCreatorV3 LE) que encripte y desencripte un texto numrico o alfabtico R// /* * RSA.java * * */ import java.math.BigInteger; import java.util.*; import java.io.*;

/** * * @author Algunas personas */ public class RSA {

int tamPrimo; BigInteger n, q, p; BigInteger totient; BigInteger e, d;

/** Constructor de la clase RSA */ public RSA(int tamPrimo) { this.tamPrimo = tamPrimo; generaPrimos(); //Genera p y q

generaClaves(); }

//Genera e y d

public void generaPrimos() { p = new BigInteger(tamPrimo, 10, new Random()); do q = new BigInteger(tamPrimo, 10, new Random()); while(q.compareTo(p)==0); }

public void generaClaves() { // n = p * q n = p.multiply(q); // toltient = (p-1)*(q-1) totient = p.subtract(BigInteger.valueOf(1)); totient = totient.multiply(q.subtract(BigInteger.valueOf(1))); // Elegimos un e coprimo de y menor que n do e = new BigInteger(2 * tamPrimo, new Random()); while((e.compareTo(totient) != -1) || (e.gcd(totient).compareTo(BigInteger.valueOf(1)) != 0)); // d = e^1 mod totient d = e.modInverse(totient); }

/** * Encripta el texto usando la clave pblica *

* @param mensaje

Ristra que contiene el mensaje a encriptar

* @return El mensaje cifrado como un vector de BigIntegers */ public BigInteger[] encripta(String mensaje) { int i; byte[] temp = new byte[1]; byte[] digitos = mensaje.getBytes(); BigInteger[] bigdigitos = new BigInteger[digitos.length];

for(i=0; i<bigdigitos.length;i++){ temp[0] = digitos[i]; bigdigitos[i] = new BigInteger(temp); }

BigInteger[] encriptado = new BigInteger[bigdigitos.length];

for(i=0; i<bigdigitos.length; i++) encriptado[i] = bigdigitos[i].modPow(e,n);

return(encriptado); }

/** * Desencripta el texto cifrado usando la clave privada * * @param encriptado Array de objetos BigInteger que contiene el texto

cifrado * que ser desencriptado

* @return The decrypted plaintext */ public String desencripta(BigInteger[] encriptado) { BigInteger[] desencriptado = new BigInteger[encriptado.length];

for(int i=0; i<desencriptado.length; i++) desencriptado[i] = encriptado[i].modPow(d,n);

char[] charArray = new char[desencriptado.length];

for(int i=0; i<charArray.length; i++) charArray[i] = (char) (desencriptado[i].intValue());

return(new String(charArray)); }

public BigInteger damep() {return(p);} public BigInteger dameq() {return(q);} public BigInteger dametotient() {return(totient);} public BigInteger damen() {return(n);} public BigInteger damee() {return(e);} public BigInteger damed() {return(d);}

También podría gustarte