Buscar aquí

miércoles, 19 de septiembre de 2012

Encriptar y desencriptar entre java y php con AES

Para pode recuperar una contraseña haciendo cifrado simétrico entre java y php, encontré esta solución, pero se me perdió la fuente, tan pronto la sepa la pongo....

Java encriptación:


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cifrado;

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


/**
 *
 * @author thaednevol
 */
public class Crypto {
//iv length should be 16 bytes
private String iv = "fedcba9876543210";
private String key = null;
private Cipher cipher = null;
private SecretKeySpec keySpec = null;
private IvParameterSpec ivSpec = null;

/**
* Constructor
*
* @throws Exception
*/
public Crypto(String key) throws Exception {
this.key = key;

// Make sure the key length should be 16
int len = this.key.length();
if(len < 16) {
int addSpaces = 16 - len;
for (int i = 0; i < addSpaces; i++) {
this.key = this.key + " ";
}
} else {
this.key = this.key.substring(0, 16);
}
this.keySpec = new SecretKeySpec(this.key.getBytes(), "AES");
this.ivSpec = new IvParameterSpec(iv.getBytes());
this.cipher = Cipher.getInstance("AES/CBC/NoPadding");
}

/**
* Bytes to Hexa conversion
*
* @param data
* @return
*/
public String bytesToHex(byte[] data) {
if (data == null) {
return null;
} else {
int len = data.length;
String str = "";
for (int i = 0; i < len; i++) {
if ((data[i] & 0xFF) < 16)
str = str + "0" + java.lang.Integer.toHexString(data[i] & 0xFF);
else
str = str + java.lang.Integer.toHexString(data[i] & 0xFF);
}
return str;
}
}

/** Encrpt the goven string
*
* @param plainData
* @throws Exception
*/
public String encrypt(String plainData) throws Exception {

// Make sure the plainData length should be multiple with 16
int len = plainData.length();
int q = len / 16;
int addSpaces = ((q + 1) * 16) - len;
for (int i = 0; i < addSpaces; i++) {
plainData = plainData + " ";
}

this.cipher.init(Cipher.ENCRYPT_MODE, this.keySpec, this.ivSpec);
byte[] encrypted = cipher.doFinal(plainData.getBytes());

return bytesToHex(encrypted);
}

public static void main(String[] args) throws Exception {
Crypto c = new Crypto("D4:6E:AC:3F:F0:BE");
String encrStr = c.encrypt("Hello World");
System.out.println("Encrypted Str :" + encrStr);
}
}

Java desencriptación


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cifrado;

/**
 *
 * @author thaednevol
 */
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Decrypto {
//iv length should be 16 bytes
private String iv = "fedcba9876543210";
private String key = null;
private Cipher cipher = null;
private SecretKeySpec keySpec = null;
private IvParameterSpec ivSpec = null;

/**
* Constructor
*
* @throws Exception
*/
public Decrypto(String key) throws Exception {
this.key = key;

// Make sure the key length should be 16
int len = this.key.length();
if(len < 16) {
int addSpaces = 16 - len;
for (int i = 0; i < addSpaces; i++) {
this.key = this.key + " ";
}
} else {
this.key = this.key.substring(0, 16);
}
this.keySpec = new SecretKeySpec(this.key.getBytes(), "AES");
this.ivSpec = new IvParameterSpec(iv.getBytes());
this.cipher = Cipher.getInstance("AES/CBC/NoPadding");
}

/**
* Hexa to Bytes conversion
*
* @param str
* @return
*/
public byte[] hexToBytes(String str) {
if (str == null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i = 0; i < len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
}
return buffer;
}
}

/** Decrypt the given excrypted string
*
* @param encrStr
* @throws Exception
*/
public String decrypt(String encrData) throws Exception {
this.cipher.init(Cipher.DECRYPT_MODE, this.keySpec, this.ivSpec);
byte[] outText = this.cipher.doFinal(hexToBytes(encrData));

String decrData = new String(outText).trim();
return decrData;
}
public static void main(String[] args) throws Exception {
Decrypto c = new Decrypto("D4:6E:AC:3F:F0:BE");
String decrStr = c.decrypt("1f50a943601d8e29206c716f82e58b8d");
System.out.println("Decrypted Str :" + decrStr);
}
}

Encripción en PHP


$cipher = "rijndael-128"; 
$mode = "cbc"; 
$secret_key = "D4:6E:AC:3F:F0:BE"; 
//iv length should be 16 bytes 
$iv = "fedcba9876543210"; 

// Make sure the key length should be 16 bytes 
$key_len = strlen($secret_key); 
if($key_len < 16 ){ 
$addS = 16 - $key_len; 
for($i =0 ;$i < $addS; $i++){ 
$secret_key.=" "; 

}else{ 
$secret_key = substr($secret_key, 0, 16); 


$td = mcrypt_module_open($cipher, "", $mode, $iv); 
mcrypt_generic_init($td, $secret_key, $iv); 
$cyper_text = mcrypt_generic($td, "Hello World"); 
mcrypt_generic_deinit($td); 
mcrypt_module_close($td); 
echo bin2hex($cyper_text); 
?> 


Desencriptar en PHP


$cipher = "rijndael-128"; 
$mode = "cbc"; 
$secret_key = "D4:6E:AC:3F:F0:BE"; 
//iv length should be 16 bytes 
$iv = "fedcba9876543210"; 

// Make sure the key length should be 16 bytes 
$key_len = strlen($secret_key); 
if($key_len < 16 ){ 
$addS = 16 - $key_len; 
for($i =0 ;$i < $addS; $i++){ 
$secret_key.=" "; 

}else{ 
$secret_key = substr($secret_key, 0, 16); 


$td = mcrypt_module_open($cipher, "", $mode, $iv); 
mcrypt_generic_init($td, $secret_key, $iv); 
$decrypted_text = mdecrypt_generic($td, hex2bin("444e6969a269829a3e59a86300614fc5")); 
mcrypt_generic_deinit($td); 
mcrypt_module_close($td); 
echo trim($decrypted_text); 

function hex2bin($data){
$bin = "";
$i = 0;
do {
$bin .= chr(hexdec($data{$i}.$data{($i + 1)}));
$i += 2;
} while ($i < strlen($data));

return $bin;
}
?> 


Quitar una pestaña (o tab) de un tabhost en android

Para quitar una pestaña en un tabhost en android, se situa el widget en la pestaña cero, y luego se borra la que queremos borrar, eso si, sabiendo el id, así:


tabhost.setCurrentTab(0);
 tabHost.getTabWidget().removeView(tabHost.getTabWidget().getChildTabViewAt(ID));
Donde ID es el id de la pestaña que queremos borrar

Android “Only the original thread that created a view hierarchy can touch its views.”

Si les sale esto en android, significa que se ha  creado o se han creado elementos en un hilo y se trata de modificar en otro. Para resolverlo haz:


runOnUiThread(new Runnable() {
     public void run() {
//El código que hace lo que vos querás....

    }
});

domingo, 8 de enero de 2012

CRON en Ubuntu: Tareas autómaticas scripst (PHP, Bash) y lanzar programas con interfaz gráfica

Si necesitas que una tarea se ejecute a intervalos regulares o en determinado momento en el futuro CRON es lo que buscas.
CRON es un demonio, un proceso que se ejecuta permanentemente en segundo plano y que ejecuta una tarea en un determinado momento que ha sido previamente programado.

Para instalarlo puedes ir a Synaptic y para comprobar si esta corriendo escribes en la consola:

     service cron status


(Si tienes instalado service), Si se esta ejecutando retorna algo como:




     cron start/running, process 1581



Si no tambien puedes arrancarlo con:



     sudo service cron start


Ahora, para entrar en materia escribimos en la consola:

    sudo crontab -e

Que te da la opción de editar el archivo donde CRON busca las tareas que va a ejecutar, al final de los comentarios debes poner las tareas así:

15 23 * * *

donde el orden es minutos, horas, día del mes, mes, día de la semana y el comando a ejecutar, antes es bueno agregar:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

Que configura las variables de entorno, como el shell que se va a usar, el home, donde están los ejecutables.

Puedes probar con esto:

15 23 * * * halt

ATENCIÓN!!!!! esto va  a apagar tu compu todos los días a las 11:15 pm, pero es una buena prueba.

Ahora puedes querer ejecutar un programa que tiene interfaz gráfica, esto va a ser un poco mas complicado por que CRON ejecuta como root y no puedes ejecutar un programa gráfico en algunos entornos como root, para esto usamos:

su -c vlc usuario

que permite ejecutar vlc como usuario ahi donde se esta ejecutando CRON como root.

15 23 * * * su -c vlc usuario

Guardamos esto al final del archivo poniendo la hora a la que queremos que se ejecute. Esto igual no va a funcionar :), pero podemos aprender algo útil y es a generar un log de errores para CRON, para esto, primero guardamos la instrucción en un script de bash en un archivo con extensión sh y al que daremos permisos de ejecución, la instruccion es (su -c vlc usuario), y escribimos esto en el archivo de CRON:


46 00 * * * sh /donde esta el script/script.sh 2>~/var/log/crontab.err

Si revisamos  /var/log/crontab.err hay cosas como [0x94dd994] main interface error: no suitable interface module y mas cosas con interface, resulta que tenemos que aclar en que pantalla se va a mostar, para saber que pantallas hay disponibles imprimos esta variable:


echo $DISPLAY



lo que me imprime :0.0, así que aclaramos que se va a mostar ahi:



46 00 * * * DISPLAY=:0.0 sh /donde esta el script/script.sh 2>~/var/log/crontab.err

Entonces en resumen, para ejecutar programas que tienen interfaz gráfica es importante no hacerlo como root y decir en que pantalla se va a mostar.

Ahora para ejecutar scripts de PHP, primero hay que averiguar donde esta el ejecutable de PHP del servicio que usamos.
Esto por que como yo, se puede tener instalado Apache 2 y al mismo tiempo Lampp y pues ambos no se ejecutan al tiempo, entonces, sabiendo cual es el que usamos la cosa es así:

25 18 * * * /opt/lampp/bin/php /opt/lampp/htdocs/htdocs/cron.php  2>~/var/log/crontab.err

donde /opt/lampp/bin/php es donde yo tengo mi ejecutable de PHP y el resto donde tengo mi script de php y pues lo que ya vimos del log.

Gracias, y me cuentan como les resulta

Luisa

miércoles, 4 de enero de 2012

Nombres de indices de arreglos en PHP


En PHP podemos tener arreglo como el siguiente:

$nombres=array('perro'=>'tintin','gato'=>'tom','raton'=>'jerry');

Y podemos obtener el contenido del arreglo, por ejemplo así:

foreach($nombres as $n){
   echo $n."/n";
}



lo cual dará por resultado algo asi:

tintin
tom
jerry

pero por algún motivo podríamos querer saber los nombres de los indices del arreglo, para esto podemos usar la función key, así:

while ($animal = current($nombres)) {//es un puntero interno que apunta al primer elemento //del array
     echo key($nombres)." ". $animal.'/n'; //key devuelve el nombre del indice
  next($nombres); //Avanza el puntero interno del array al siguiente elemento
}

lo que da por resultado:

perro tintin
gato tom
raton jerry

Gracias

martes, 3 de enero de 2012

Etiqueta select con optgroup HTML en Cakephp

La etiqueta optgroup  ofrece la posibilidad de agrupar los option de un select (Las opciones de un drop-down agrupadas con etiquetas). Así:

<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>


 Dado que en Cakephp tenemos métodos para darle formato a estos elementos, la forma de optener dichos optgroups es la siguiente:

Se usan arreglos de 2 dimensiones -> $opt=array('Swedish Cars'=>array('volvo'=>'Volvo','saab'=>'Saab'),'German Cars'=>array('mercedes'=>'Mercedes','audi'=>'Audi'));

y el elemento como siempre:

echo $this->Form->select('carros',$opt);

Gracias