Olá Pessoal sou novo no guj
e aproveitando o tópico do guitarro17 eu tenho um projeto parecido com dele e gostaria que alguem me ajudasse tirando algumas dúvidas.
explicando meu projeto:
nesse meu projeto eu tenho duas parte:
Clinte - J2Me.
Servidor - J2SE.
na parte cliente eu tenho que montar uma midlet com um campo de entrada de dados e um menu com opção de criptografar os dados digitados.
e então ao criptografar ele me gera um list com os dados criptografados.
Detalhe: estou usando criptografia AES para gerar um par de chaves e preciso de uma chave pública para que ao criptografar os dados, ele envia até um servidor J2SE via bluetooth e descriptografa a mensagem com a chave privada RSA. a minha dúvida é simples, nessa primeira parte cliente eu só preciso criptografar e enviar a mensagem.
montei duas classes para isso:
Classe Principal (Midlet)
[code]package Principal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.;
import javax.microedition.lcdui.;
import javax.microedition.midlet.*;
import AES.Encryption;
import java.security.NoSuchAlgorithmException;
import java.security.spec.EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class Principal extends MIDlet implements CommandListener {
private Display display;
private Form frmPrincipal; // criação
private TextField tf_entrada, tf_senha;
private Command cm_criptografa, cm_descriptografa, cm_sair, cm_enviar, cm_voltar;
private List lista;
protected void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
cm_criptografa = new Command("Criptografa", Command.ITEM, 1);
cm_descriptografa = new Command("Descriptografa", Command.ITEM, 2);
cm_sair = new Command("Sair", Command.EXIT, 1);
cm_enviar = new Command("Enviar Dados", Command.ITEM, 3);
cm_voltar = new Command("Voltar", Command.BACK, 1);
lista = new List("Texto Descriptografado", List.TEXT_WRAP_DEFAULT);
lista.addCommand(cm_voltar);
lista.addCommand(cm_enviar);
lista.setCommandListener(this);
frmPrincipal = new Form("Criptografia RSA");
frmPrincipal.addCommand(cm_criptografa);
frmPrincipal.addCommand(cm_descriptografa);
frmPrincipal.addCommand(cm_sair);
frmPrincipal.setCommandListener(this);
tf_entrada = new TextField("Entrada:", null, 150, TextField.ANY);
tf_senha = new TextField("Senha:", null, 150, TextField.ANY);
frmPrincipal.append(tf_senha);
frmPrincipal.append(tf_entrada);
display.setCurrent(frmPrincipal);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d)
{
if ( c == cm_sair)
{
destroyApp(true);
notifyDestroyed();
}
if (c == cm_criptografa)
{
try {
Conversor();
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
} catch (InvalidKeyException ex) {
ex.printStackTrace();
} catch (IllegalBlockSizeException ex) {
ex.printStackTrace();
} catch (BadPaddingException ex) {
ex.printStackTrace();
} catch (NoSuchPaddingException ex) {
ex.printStackTrace();
}
display.setCurrent(lista);
}
}
public void Conversor() throws NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException{
// CONVERTER O TEXTO EM BYTES
byte texto[] = tf_entrada.getString().getBytes();
// CRIAR UM OBJETO AES PASSANDO A SEQUENCIA DE BYTES DO TEXTO DIGITADO
Encryption encryption = new Encryption();
// PEGANDO O RESULTADO AES GERADO
byte[]enc = encryption.encode(texto.toString().getBytes(),null);
// CONVERTENDO O CONJUNTO DE BYTES E APLICANDO NO OBJETO LISTA
lista.append(encryption.fromHex(enc),null);
}
}[/code]
e a classe Encryption
[code] package AES;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class Encryption {
private byte[] key;
public Encryption (){
}
/** Gera uma chave criptografica de 256 bits aleatória
-
@return byte[] key
*/
public byte[] key() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance(“AES”);
keyGen.init(256);
SecretKey key = keyGen.generateKey();
return key.getEncoded();
}
/**
-
Encripta uma mensagem usando AES para uma dada chave
-
@param byte[] input deve estar em um tamanho multiplo de 16 (nullPadString)
-
@param byte[] key
-
@return
*/
public byte[] encode(byte[] input, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException {
SecretKeySpec skeySpec = new SecretKeySpec(key, “AES”);
Cipher cipher = Cipher.getInstance(“AES/ECB/NoPadding”);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(input);
return encrypted;
}
/**
-
Retorna o valor original de uma mensagem criptgrafada em AES
-
@param byte[] input
-
@param byte[] key
-
@return
*/
public byte[] decode(byte[] input, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException {
SecretKeySpec skeySpec = new SecretKeySpec(key, “AES”);
Cipher cipher = Cipher.getInstance(“AES/ECB/NoPadding”);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(input);
return decrypted;
}
/**
-
Converte uma mensagem criptografada para uma string de sua representação hexadecimal.
-
@param byte[] hex
-
@return String str
*/
public String fromHex(byte[] hex) {
StringBuffer sb = new StringBuffer();
for (int i=0; i < hex.length; i++) {
sb.append( Integer.toString( ( hex[i] & 0xff ) + 0x100, 16).substring( 1 ) );
}
return sb.toString();
}
/**
-
Converte uma representação hexadecimal para seus bytes hexadecimal (valor encriptado)
-
@param String s
-
@return byte[] data
*/
public byte[] toHex(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
/**
-
Corrige o tamanho de uma String para multiplo de 16
-
@param String original
-
@return String final
*/
public String nullPadString(String original) {
StringBuffer output = new StringBuffer(original);
int remain = output.length() % 16;
if (remain != 0) {
remain = 16 - remain;
for (int i = 0; i < remain; i++)
output.append((char) 0);
}
return output.toString();
}
}[/code]
ao tentar rodar o projeto ele me gerar alguns erros:
Encryption.java:43: cannot find symbol
symbol : constructor SecretKeySpec(byte[],java.lang.String)
location: class javax.crypto.spec.SecretKeySpec
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Encryption.java:46: doFinal(byte[],int,int,byte[],int) in javax.crypto.Cipher cannot be applied to (byte[])
byte[] encrypted = cipher.doFinal(input);
estou tentando gerar um par de chaves para criptografar.
alguém sabe o motivo do erro?