Eje 3: Criptografia en Java

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

EJE 3: CRIPTOGRAFIA EN JAVA

ZARAZA TORO JESÚS DAVID

FUNDACIÓN UNIVERSITARIA DEL AREA ANDINA


FACULTAD DE INGENIERÍAS Y CIENCIAS BÁSICAS
INGENIERÍA DE SISTEMAS
BOGOTA D.C.
2020
Objetivo General

Elaborar un programa en java haciendo uso de clases criptográficas para cifrar contraseñas

a partir de diferentes protocolos.

Programa en Java

Imágenes

Clases creadas aes.java, Formulario_Login.java y rsa.java

Imágenes clase main Formulario_Login.java

Código

Formulario_Login.java

import javax.swing.JOptionPane;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/*
 
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Zaraza Toro
 */
public class Formulario_Login extends javax.swing.JFrame {

    /**
     * Creates new form Formulario_Login
     */
    public Formulario_Login() {
        initComponents();
    }

   
    @SuppressWarnings("unchecked")
    
    private void initComponents() {
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        TxUser = new javax.swing.JTextField();
        TxPass = new javax.swing.JPasswordField();
        btIngresar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N


        jLabel1.setText("LOGIN");

        jLabel2.setText("Usuario");

        jLabel3.setText("Contraseña");

        TxUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TxUserActionPerformed(evt);
            }
        });

        btIngresar.setText("Ingresar");
        btIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btIngresarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI
NG)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI
NG)
                    .addComponent(btIngresar)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEA
DING, false)
                        .addComponent(jLabel1)
                        .addComponent(TxPass, javax.swing.GroupLayout.DEFAULT_SIZE, 146,
Short.MAX_VALUE)
                        .addComponent(TxUser)))
                .addContainerGap(115, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jLabel1)
                .addGap(57, 57, 57)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASE
LINE)
                    .addComponent(jLabel2)
                    .addComponent(TxUser, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASE
LINE)
                    .addComponent(jLabel3)
                    .addComponent(TxPass, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(38, 38, 38)
                .addComponent(btIngresar)
                .addContainerGap(77, Short.MAX_VALUE))
        );

        pack();
    }

    private void TxUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-


FIRST:event_TxUserActionPerformed
        
    }

    private void btIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-


FIRST:event_btIngresarActionPerformed
                            
         rsa asimetrico = new rsa ();
         aes simetrico = new aes();
         String Usuario = TxUser.getText();
         String Clave = TxPass.getText();
             
         asimetrico.metodoAsimetrico(Clave);
         
         String Mensaje = "Su clave cifrada es: " +Clave +" con cifrado "
+asimetrico.getClaveCifrada();
         String Separador = "------------------------------------------------";

         try {
         String encriptador = simetrico.encriptar(Usuario, ("Encriptado"));
         String Result = ("\n Su Usuario cifrado es : " +Usuario +" con cifrado simetrico "
+encriptador)+ "\n"+Separador+ 
         "\n" +Mensaje  ;
         JOptionPane.showMessageDialog(null,Result);
        } catch(UnsupportedEncodingException | NoSuchAlgorithmException |
InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException |
BadPaddingException ex) {
            Logger.getLogger(aes.class.getName()).log(Level.SEVERE, null, ex);
       
        }
                        
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
      
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Formulario_Login.class.getName()).log(java.util.lo
gging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Formulario_Login.class.getName()).log(java.util.lo
gging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Formulario_Login.class.getName()).log(java.util.lo
gging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Formulario_Login.class.getName()).log(java.util.lo
gging.Level.SEVERE, null, ex);
        }
       
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Formulario_Login().setVisible(true);
            }
        });
    }

    private javax.swing.JPasswordField TxPass;


    private javax.swing.JTextField TxUser;
    private javax.swing.JButton btIngresar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;

}
Class rsa.java

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;

public class rsa {

  
    public static void main(String[] args) {
        // TODO code application logic here
    }
    
    private byte[] claveCifrada = null;
    private byte[] claveDesCifrada = null;

    public byte[] getClaveCifrada() {


        return claveCifrada;
    }

    public void setClaveCifrada(byte[] claveCifrada) {


        this.claveCifrada = claveCifrada;
    }

    public byte[] getClaveDesCifrada() {


        return claveDesCifrada;
    }

    public void setClaveDesCifrada(byte[] claveDesCifrada) {


        this.claveDesCifrada = claveDesCifrada;
    }
    
    public void  metodoAsimetrico(String msjManager){
            
      try {
           
            System.out.println("Crear clave pública y privada");
            
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(512);//tamaño de la clave
            KeyPair clavesRSA = keyGen.generateKeyPair();

            //Clave privada

            PrivateKey clavePrivada = clavesRSA.getPrivate();

            //Clave pública
            PublicKey clavePublica = clavesRSA.getPublic();

            

            //Texto plano
            byte[] bufferClaro = msjManager.getBytes();
            //Ciframos con clave pública el texto plano utilizando RSA
            Cipher cifrador = Cipher.getInstance("RSA");
            cifrador.init(Cipher.ENCRYPT_MODE, clavePublica);
           // System.out.println("Cifrar con clave pública el Texto:");
            mostrarBytes(bufferClaro);

           
            //Realización del cifrado del texto plano
            byte[] bufferCifrado = cifrador.doFinal(bufferClaro);
           // System.out.println("Texto CIFRADO");
            setClaveCifrada(mostrarBytes(bufferCifrado));
            
            //System.out.println("\n_______________________________");

            //Desencriptación utilizando la clave privada


            cifrador.init(Cipher.DECRYPT_MODE, clavePrivada);
            //System.out.println("Descifrar con clave privada");

            //Obtener y mostrar texto descifrado


            bufferClaro = cifrador.doFinal(bufferCifrado);
            //System.out.println("Texto DESCIFRADO");
            setClaveDesCifrada(mostrarBytes(bufferClaro));
           
            //System.out.println("\n_______________________________");
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Formulario_Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(Formulario_Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(Formulario_Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalBlockSizeException ex) {
            Logger.getLogger(Formulario_Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BadPaddingException ex) {
            Logger.getLogger(Formulario_Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(rsa.class.getName()).log(Level.SEVERE, null, ex);
        }
   
    }

    public byte[]  mostrarBytes(byte[] buffer) throws IOException {


         return buffer;
    }   
    
}
Class aes.java

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class aes {


    
     private SecretKeySpec crearClave(String clave) throws UnsupportedEncodingException,
NoSuchAlgorithmException {
        byte[] claveEncriptacion = clave.getBytes("UTF-8");
         
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
         
        claveEncriptacion = sha.digest(claveEncriptacion);
        claveEncriptacion = Arrays.copyOf(claveEncriptacion, 16);
         
        SecretKeySpec secretKey = new SecretKeySpec(claveEncriptacion, "AES");
 
        return secretKey;
    }
 
    /**
     * Aplica la encriptacion AES a la cadena de texto usando la clave indicada
     * @param datos Cadena a encriptar
     * @param claveSecreta Clave para encriptar
     * @return Información encriptada
     */
    public String encriptar(String datos, String claveSecreta) throws
UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException,
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        SecretKeySpec secretKey = this.crearClave(claveSecreta);
         
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");        
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
 
        byte[] datosEncriptar = datos.getBytes("UTF-8");
        byte[] bytesEncriptados = cipher.doFinal(datosEncriptar);
        String encriptado = Base64.getEncoder().encodeToString(bytesEncriptados);
 
        return encriptado;
    }
 
    
    public String desencriptar(String datosEncriptados, String claveSecreta) throws
UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException,
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        SecretKeySpec secretKey = this.crearClave(claveSecreta);
 
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
         
        byte[] bytesEncriptados = Base64.getDecoder().decode(datosEncriptados);
        byte[] datosDesencriptados = cipher.doFinal(bytesEncriptados);
        String datos = new String(datosDesencriptados);
         
        return datos;
    }
    
}
Programa ejecutándose:

Al abrir el archivo Cifrado_Descifrado_Eje3


Usuario y clave encriptados
Se ejecuta un nuevo usuario
Se adjunta el proyecto el cual contiene el archivo .jar

Conclusiones

 Se aplicó los algoritmos de encriptación RSA y AES uno siendo asimétrico para la

clave y otro Simétrico para el usuario y es aquí donde se evidencia la importancia de

la programación y conocer con sumo detalle la composición de los algoritmos. La

seguridad parte fundamental, desde el inicio del programa siendo el login de acceso

hasta su transacción final, debe brindar los protocolos necesarios para cumplir con la

seguridad del software.

You might also like