Alguém sabe como posso fazer um metodo para encriptar e desencriptar uma string em MD5?
md5
12 Respostas
O que seria esse MD5, desculpe por não ter respondido, mas é mais por curiosidade mesmo, se alguém pudesse só me dar uma breve descrição do que é MD5
Muito basicamente, MD5 é um algoritmo usado para criptografia de dados. No mais: http://www.google.com/search?q=MD5 
[]'s
Muito basicamente, MD5 é um algoritmo usado para criptografia de dados. No mais: http://www.google.com/search?q=MD5 
[]'s
Vivendo e aprendendo, eu não sabia que existia essas coisas em Java, brigado cara…
Tenta usar essa classe.
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
public class Encrypter {
Cipher ecipher;
Cipher dcipher;
byte[] salt = {
(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
(byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
};
int iterationCount = 30;
public Encrypter() {
}
public void inicializa(String passPhrase){
try {
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (InvalidAlgorithmParameterException e) {
} catch (InvalidKeySpecException e) {
} catch (NoSuchPaddingException e) {
} catch (NoSuchAlgorithmException e) {
} catch (InvalidKeyException e) {
}
}
public String encrypt(String str) {
try {
inicializa(str);
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
}
return null;
}
public String decrypt(String str) {
try {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
public static void main(String[] args) throws Exception{
Encrypter en = new Encrypter();
System.out.println(en.encrypt("String"));
}
}
Peraí peraí peraí…MD5 é só sumário da mensagem, não? Pra garantir integridade dos dados: você calcula um string a partir de uma mensagem que é único e a partir do qual a mensagem não pode ser obtida…
Não tenho certeza, mas acho que não é possível “descriptografar” um string MD5, ele só vai te garantir que você não use dados alterados (porque se forem alterados o string será completamente diferente e você poderá saber). Tô errado?
Você está certo cara, não tem como descriptografar uma string MD5
Cara eu usei ela da seguinte maneira só para testar diferentes strings
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.swing.*;
import java.awt.*;
public class Encrypter {
Cipher ecipher;
Cipher dcipher;
byte[] salt = {
(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
(byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
};
int iterationCount = 30;
public Encrypter() {
}
public void inicializa(String passPhrase){
try {
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (InvalidAlgorithmParameterException e) {
} catch (InvalidKeySpecException e) {
} catch (NoSuchPaddingException e) {
} catch (NoSuchAlgorithmException e) {
} catch (InvalidKeyException e) {
}
}
public String encrypt(String str) {
try {
inicializa(str);
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
}
return null;
}
public String decrypt(String str) {
try {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
public static void main(String[] args) throws Exception{
Encrypter en = new Encrypter();
String entrada="", saida="";
entrada=JOptionPane.showInputDialog("Digita a frase: ");
saida=en.encrypt(entrada);
JOptionPane.showMessageDialog(null,"A Frase Encriptada: "+saida);
JOptionPane.showMessageDialog(null,"Desencriptada: "+en.decrypt(saida));
}
}
MAs como faço para quando houver espaço ??
já tentou dar um trim em todas as Strings que entrarem ?
Blz…
Deu certo, mas agora seu ao invés de eu usar um JOptionPane, eu utilizar um JTextArea da um erro de NullPOinter Exception
Como você está usando ?
posta o fonte aqui…
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
public class Encrypter {
Cipher ecipher;
Cipher dcipher;
byte[] salt = {
(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
(byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
};
int iterationCount = 30;
public void inicializa(String passPhrase){
try {
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (InvalidAlgorithmParameterException e) {
} catch (InvalidKeySpecException e) {
} catch (NoSuchPaddingException e) {
} catch (NoSuchAlgorithmException e) {
} catch (InvalidKeyException e) {
}
}
public String encrypt(String str) {
try {
inicializa(str);
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
}
return null;
}
public String decrypt(String str) {
try {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Encry extends JFrame{
JTextArea text, texto;
JPanel p, p1, p2;
JButton encryb, decry;
Encrypter obj;
String recebe, testee, tested;
public Encry(){
super( "Encriptar Texto !" );
p = new JPanel();p1 = new JPanel();p2 = new JPanel();
p1.setLayout( new FlowLayout() );
Container c = getContentPane();
c.setLayout ( new BorderLayout() );
JLabel titulo=new JLabel("Digite o texto: ");
p.add(titulo);
p.add(text = new JTextArea(4,25));
p1.add(decry=new JButton("<<< Desencryptar"));
p1.add(encryb=new JButton("Encryptar >>>"));
p2.add(texto=new JTextArea(4,25));
encryb.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e )
{
/*
recebe=text.getText().trim();
testee = obj.encrypt(recebe);
texto.setText(testee);*/
recebe=JOptionPane.showInputDialog("Digite a frase: ");
testee = obj.encrypt(recebe.toString());
texto.setText(testee);
}
}
);
decry.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e )
{
// Decrypt
tested = obj.decrypt(texto.getText());
text.setText(tested);
}
}
);
c.add( p, BorderLayout.NORTH );
c.add( p1, BorderLayout.CENTER );
c.add( p2, BorderLayout.SOUTH );
}
public static void main( String x[] )
{
Encry tela = new Encry();
tela.setSize( 280, 220 );
tela.show();
tela.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}