br.com.ufjf.labredes.rest.ConectaResource.java Source code

Java tutorial

Introduction

Here is the source code for br.com.ufjf.labredes.rest.ConectaResource.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.ufjf.labredes.rest;

import br.com.ufjf.labredes.crypto.Cryptography;
import br.com.ufjf.labredes.servletUtil.Response;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.commons.lang.SerializationUtils;

/**
 *
 * @author leoja
 */
@Path("/conectar")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class ConectaResource {

    public static Cryptography rsa = new Cryptography();

    private static PublicKey sever_publicKey;
    private static PrivateKey sever_privateKey;
    public static byte[] client_aes;

    @POST
    //1. Solicita Conexo
    public PublicKey conect() throws Exception {
        sever_publicKey = Cryptography.getPublic();
        sever_privateKey = Cryptography.getPrivate();
        //1.1 Envia PK
        return sever_publicKey;
    }

    @POST
    @Path("/{client_pk}")
    //2.Envia PK Criptografada
    public String answer(@PathParam("client_pk") String client_pk) {
        Response ans = new Response();

        if (!client_pk.equals("")) {
            byte[] client = Base64.getDecoder().decode(client_pk);
            client_aes = rsa.decrypt(client, sever_privateKey);
            ans.Ok("Conexo aceita");
            //2.1 Responde
            byte[] data = SerializationUtils.serialize(rsa.encrypt(ans, client_aes));
            String aux = Base64.getEncoder().encodeToString(data);
            return aux;
        } else {
            ans.Error("Erro ao decriptar chave");
            //2.1 Responde
            byte[] data = SerializationUtils.serialize(rsa.encrypt(ans, client_aes));
            String aux = Base64.getEncoder().encodeToString(data);
            return aux;
        }
    }

}