Criptografia AES

4 respostas
H

Olá, eu estou refazendo um sistema em java (atualmente ele está em php). O sistema em PHP guardava as senhas usando o seguinte algoritmo AES para criptografia:

public function encrypt($senha) {
		/* gera o MCRYPT_RAND */
		srand((double) microtime() * 1000000);
		
		/* Abre o módulo para início de criptografia */
		$td = mcrypt_module_open('rijndael-128', '','cfb', '');
		$this->chave = substr($this->chave, 0, mcrypt_enc_get_key_size($td));
		$ivSize = mcrypt_enc_get_iv_size($td);
		$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
		
		/* Inicialização da criptografia */
		if (mcrypt_generic_init($td, $this->chave, $iv) != -1) {	
			
			/* Encriptação de dados */
			$this->senhaCript = mcrypt_generic($td, $senha);
			mcrypt_generic_deinit($td);
			mcrypt_module_close($td);
			$this->senhaCript = $iv.$this->senhaCript;
			return $this->senhaCript;
		}
	}

Como sei pouco sobre php está muito dificil entender como fazer algo equivalente em java. Não achei nenhum material muito didático sobre Java + AES. Alguém poderia indicar um bom material que me ajude a entender como implementar isso ou ao menos dar algum direcionamento?

4 Respostas

E

Olá!

veja se isso ajuda: http://www.guj.com.br/articles/32

try { MessageDigest md5 = MessageDigest.getInstance("AES"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); }

espero ter ajudado

H

eliangela:
Olá!

veja se isso ajuda: http://www.guj.com.br/articles/32

try { MessageDigest md5 = MessageDigest.getInstance("AES"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); }

espero ter ajudado

Então aliangela, na vdd essa foi a primeira forma q pensei em fazer. Porém o messagedigest é apenas uma função hash (que suporta somente MD5 e SHA), e nesse caso não é possível descobrir qual era a senha original com a hash gerada. No caso do AES, ele é um algoritmo de criptografia que com base em uma palavra chave, a senha criptografada é gerada, e com essa palavra-chave é possível realizar a descriptografia.

Infelizmente o MessageDigest não suporta AES. =(

C

http://www.bouncycastle.org/

De nada :wink:

A

serve ?

package br.com...;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class EncrypterBC {

    private static final String METODO_ENCRIPTACAO = "AES";
    public static final byte[] CHAVE = {-117, -11, -123, -9, -4, 78, -45, -121, 92, -22, -111, -82, -88, 72, 21, 95, };

    public static String encriptar(byte[] key, String value) throws Throwable {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key, METODO_ENCRIPTACAO);
            Cipher cipher = Cipher.getInstance(METODO_ENCRIPTACAO);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(value.getBytes());

            return new BASE64Encoder().encode(encrypted);
        } catch (Exception e) {
            throw new Throwable("Erro ao criptografar informações " + e.getMessage());
        }
    }

    public static String decriptar(byte[] key, String encrypted) throws Throwable {
        byte[] decrypted = null;
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key, METODO_ENCRIPTACAO);
            byte[] decoded = new BASE64Decoder().decodeBuffer(encrypted);
            Cipher cipher = Cipher.getInstance(METODO_ENCRIPTACAO);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            decrypted = cipher.doFinal(decoded);
        } catch (Exception e) {
            throw new Throwable("Erro ao descriptografar informações " + e.getMessage());
        }
        return new String(decrypted);
    }

    public static void main(String[] args) {

        String informacao = "123 ";
        String informacaoCriptografada = null;
        String informacaoDescriptografada = null;

        try {
            informacaoCriptografada = EncrypterBC.encriptar(EncrypterBC.CHAVE, informacao);
            System.out.println("Informação criptografada: " + informacaoCriptografada);

            informacaoDescriptografada = EncrypterBC.decriptar(EncrypterBC.CHAVE, informacaoCriptografada);
            System.out.println("Informação descriptografada: " + informacaoDescriptografada);
        } catch (Throwable e) {
            e.getMessage();
        }
    }

    public static void geradorDeChaveCripto() {
        try {
            KeyGenerator keyGen = KeyGenerator.getInstance(METODO_ENCRIPTACAO);
            System.out.println("Chave AES:");
            byte[] chave = keyGen.generateKey().getEncoded();
            System.out.print("{");
            for (byte b : chave) {
                System.out.print("" + b + ", ");
            }
            System.out.println("}");
        } catch (Exception e) {
            e.getMessage();
        }
    }
}
Criado 6 de setembro de 2011
Ultima resposta 6 de set. de 2011
Respostas 4
Participantes 4