br.com.ufjf.labredes.crypto.Cryptography.java Source code

Java tutorial

Introduction

Here is the source code for br.com.ufjf.labredes.crypto.Cryptography.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.crypto;

import br.com.ufjf.labredes.model.Candidato;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import javax.crypto.SealedObject;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang.SerializationUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 *
 * @author leoja
 */
public class Cryptography {

    private static final String ALGORITHM_ASYM = "RSA";
    private static final String ALGORITHM_SYM = "AES";
    private static final String PATH_CHAVE_PRIVADA_SERVER = "private_server.key";
    private static final String PATH_CHAVE_PUBLICA_SERVER = "public_server.key";
    private static final String path = "C://Users/leoja/Documents/NetBeansProjects/ElectionServer/";

    public static void geraChave() {
        try {

            final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM_ASYM);
            keyGen.initialize(1024);
            final KeyPair key = keyGen.generateKeyPair();

            File chavePrivadaFileServer = new File(path, PATH_CHAVE_PRIVADA_SERVER);
            File chavePublicaFileServer = new File(path, PATH_CHAVE_PUBLICA_SERVER);

            // Cria os arquivos para armazenar a chave Privada e a chave Publica            
            if (chavePrivadaFileServer.getParentFile() != null) {
                chavePrivadaFileServer.getParentFile().mkdirs();
            }

            chavePrivadaFileServer.createNewFile();

            if (chavePublicaFileServer.getParentFile() != null) {
                chavePublicaFileServer.getParentFile().mkdirs();
            }

            chavePublicaFileServer.createNewFile();

            // Salva a Chave Pblica do servidor no arquivo
            ObjectOutputStream chavePublicaOSS = new ObjectOutputStream(
                    new FileOutputStream(chavePublicaFileServer));
            chavePublicaOSS.writeObject(key.getPublic());
            chavePublicaOSS.close();

            // Salva a Chave Privada do servidor no arquivo
            ObjectOutputStream chavePrivadaOSS = new ObjectOutputStream(
                    new FileOutputStream(chavePrivadaFileServer));
            chavePrivadaOSS.writeObject(key.getPrivate());
            chavePrivadaOSS.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static boolean verificaChave() {
        File chavePrivadaServer = new File(path, PATH_CHAVE_PRIVADA_SERVER);
        File chavePublicaServer = new File(path, PATH_CHAVE_PUBLICA_SERVER);

        if (chavePrivadaServer.exists() && chavePublicaServer.exists()) {
            return true;
        }

        return false;
    }

    /*
    *   Encripta um objeto serializable com uma chave AES
     */
    /*public static SealedObject encrypt(Serializable object, byte[] aesKey){
    SealedObject sealedObject = null;
    SecretKeySpec secretKey = new SecretKeySpec(aesKey, ALGORITHM_SYM);
    try {
        final Cipher cipher = Cipher.getInstance("ALGORITHM_SYM");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        sealedObject = new SealedObject(object, cipher);
        
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sealedObject;
    }*/

    /*
    *   Encripta um objeto serializable com uma chave AES
     */
    public static String encrypt(Serializable object, byte[] aesKey) {
        SecretKeySpec secretKey = new SecretKeySpec(aesKey, ALGORITHM_SYM);
        String object_encrypted = null;
        try {
            final Cipher cipher = Cipher.getInstance(ALGORITHM_SYM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] data = SerializationUtils.serialize(object);
            byte[] cipherText = cipher.doFinal(data);
            object_encrypted = new BASE64Encoder().encode(cipherText);
        } catch (Exception e) {
            e.printStackTrace();
            return "bbb";
        }
        return object_encrypted;
    }

    /*
     *   Decripta um objeto serializable com uma chave AES
     */
    /*public static Object decrypt(SealedObject sealedObj, byte[] aesKey){
    Object object = null;
    SecretKeySpec secretKey = new SecretKeySpec(aesKey, ALGORITHM_SYM);
    try {
        Cipher cipher = Cipher.getInstance(ALGORITHM_SYM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        sealedObj.getObject(cipher);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return object;
    }*/

    /*
     *   Decripta um objeto serializable com uma chave AES
     */
    public static Object decrypt(String encryptedObject, byte[] aesKey) {
        Object object = null;
        SecretKeySpec secretKey = new SecretKeySpec(aesKey, ALGORITHM_SYM);
        try {
            byte[] cipherText = new BASE64Decoder().decodeBuffer(encryptedObject);
            Cipher cipher = Cipher.getInstance(ALGORITHM_SYM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] serialized_obj = cipher.doFinal(cipherText);
            object = (Object) SerializationUtils.deserialize(serialized_obj);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return object;
    }

    /*
     *   Decripta mensagem criptografada com a chave pblcia do servidor
     */
    public static byte[] decrypt(byte[] aesKeyEncrypted, PrivateKey privKey) {
        byte[] aesKey = null;
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM_ASYM);
            cipher.init(Cipher.DECRYPT_MODE, privKey);
            aesKey = cipher.doFinal(aesKeyEncrypted);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return aesKey;
    }

    public static PublicKey getPublic() {
        if (!verificaChave()) {
            geraChave();
        }
        ObjectInputStream inputStream;
        try {
            inputStream = new ObjectInputStream(new FileInputStream(path + PATH_CHAVE_PUBLICA_SERVER));
            return (PublicKey) inputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static PrivateKey getPrivate() {
        if (!verificaChave()) {
            geraChave();
        }
        ObjectInputStream inputStream;
        try {
            inputStream = new ObjectInputStream(new FileInputStream(path + PATH_CHAVE_PRIVADA_SERVER));
            return (PrivateKey) inputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}