Foros del Web » Programando para Internet » PHP »

Steganografia de php a java

Estas en el tema de Steganografia de php a java en el foro de PHP en Foros del Web. como va? estoy trabajando en dos scripts, uno en java y otro en php. el de php debe escribir una clave, mediante steganografria en una ...
  #1 (permalink)  
Antiguo 12/12/2014, 12:52
 
Fecha de Ingreso: enero-2007
Mensajes: 285
Antigüedad: 17 años, 3 meses
Puntos: 21
Steganografia de php a java

como va? estoy trabajando en dos scripts, uno en java y otro en php. el de php debe escribir una clave, mediante steganografria en una imagen . y el java debe leerla. asi de sencillo.. pero no lo es tanto (al menos para mi). si bien entiendo los conceptos de esta practica, no es algo que maneje.. por lo tanto procedi a buscar en google y encontre mil cosas.. que funcionan en php o en java pero ninguna puede generar una imagen que pueda ser leida por el otro lenguaje.

de todas decidi quedarme con estas

JAVA
Código:
public class Steganography {

    public Steganography() {
    }


    public boolean encode(String path, String original, String ext1, String stegan, String message) {
        String file_name = image_path(path, original, ext1);
        BufferedImage image_orig = getImage(file_name);

       
        BufferedImage image = user_space(image_orig);
        image = add_text(image, message);

        return (setImage(image, new File(image_path(path, stegan, "png")), "png"));
    }


    public String decode(String path, String name) {
        byte[] decode;
        try {
            //user space is necessary for decrypting
            BufferedImage image = user_space(getImage(image_path(path, name, "png")));
            decode = decode_text(get_byte_data(image));
            return (new String(decode));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                    "There is no hidden message in this image!", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return "";
        }
    }


    private String image_path(String path, String name, String ext) {
        return path + "/" + name + "." + ext;
    }


    private BufferedImage getImage(String f) {
        BufferedImage image = null;
        File file = new File(f);

        try {
            image = ImageIO.read(file);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "Image could not be read!", "Error", JOptionPane.ERROR_MESSAGE);
        }
        return image;
    }


    private boolean setImage(BufferedImage image, File file, String ext) {
        try {
            file.delete(); //delete resources used by the File
            ImageIO.write(image, ext, file);
            return true;
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                    "File could not be saved!", "Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }


    private BufferedImage add_text(BufferedImage image, String text) {
        //convert all items to byte arrays: image, message, message length
        byte img[] = get_byte_data(image);
        byte msg[] = text.getBytes();
        byte len[] = bit_conversion(msg.length);
        try {
            encode_text(img, len, 0); //0 first positiong
            encode_text(img, msg, 32); //4 bytes of space for length: 4bytes*8bit = 32 bits
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                    "Target File cannot hold message!", "Error", JOptionPane.ERROR_MESSAGE);
        }
        return image;
    }

  
    private BufferedImage user_space(BufferedImage image) {
      
        BufferedImage new_img = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D graphics = new_img.createGraphics();
        graphics.drawRenderedImage(image, null);
        graphics.dispose(); //release all allocated memory for this image
        return new_img;
    }


    private byte[] get_byte_data(BufferedImage image) {
        WritableRaster raster = image.getRaster();
        DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();
        return buffer.getData();
    }


    private byte[] bit_conversion(int i) {
        //only using 4 bytes
        byte byte3 = (byte) ((i & 0xFF000000) >>> 24); //0
        byte byte2 = (byte) ((i & 0x00FF0000) >>> 16); //0
        byte byte1 = (byte) ((i & 0x0000FF00) >>> 8); //0
        byte byte0 = (byte) ((i & 0x000000FF));
        //{0,0,0,byte0} is equivalent, since all shifts >=8 will be 0
        return (new byte[]{byte3, byte2, byte1, byte0});
    }


    private byte[] encode_text(byte[] image, byte[] addition, int offset) {
        //check that the data + offset will fit in the image
        if (addition.length + offset > image.length) {
            throw new IllegalArgumentException("File not long enough!");
        }
        //loop through each addition byte
        for (int i = 0; i < addition.length; ++i) {
            //loop through the 8 bits of each byte
            int add = addition[i];
            for (int bit = 7; bit >= 0; --bit, ++offset) //ensure the new offset value carries on through both loops
            {
               
                int b = (add >>> bit) & 1;
               
                image[offset] = (byte) ((image[offset] & 0xFE) | b);
            }
        }
        return image;
    }


    private byte[] decode_text(byte[] image) {
        int length = 0;
        int offset = 32;
        
        for (int i = 0; i < 32; ++i) //i=24 will also work, as only the 4th byte contains real data
        {
            length = (length << 1) | (image[i] & 1);
        }

        byte[] result = new byte[length];

        
     
        for (int b = 0; b < result.length; ++b) {
         
            for (int i = 0; i < 8; ++i, ++offset) {
              
                result[b] = (byte) ((result[b] << 1) | (image[offset] & 1));

            }
        }
        return result;
    }
    
    
       public static void main(String[] args) {
       Steganography st = new Steganography();
        st.encode("C:\\java\\netbeans\\steganografia\\","kk","png","aaa","la policia esta loca loca");
        
        String salida=st.decode("C:\\java\\netbeans\\steganografia\\", "aaa");
        System.out.println(salida);
    }
}
PHP
Código PHP:
<?php
function encode(){
$img=imagecreatefromjpeg("kk.jpg");
$message='Hello World'.chr(0);
$x=imagesx($img);
$y=imagesy($img);
$px=0;
$py=23;
$h=23;
for(
$i=0;$i<strlen($message);$i++) {
    
$px+=$h;
    if(
$px>$x) {
        
$px=$px%$x;
        
$py+=$h;
    }
    
$rgb=imagecolorat($img,$px,$py);
    
$R=($rgb >> 16) & 0xFF;
    
$G=($rgb >> 8) & 0xFF;
    
$B=$rgb 0xFF;

    
$m=ord($message{$i});
    
$R=($R&0xf8)| ($m&0x07);
    
$G=($B&0xf8)|(($m>>3)&0x07);
    
$B=($B&0xf8)| (($m>>6)&0x03);

    
$t=imagecolorallocate($img,$R,$G,$B);
    
imagesetpixel($img ,$px,$py,$t);
}
imagepng($img,'deadsea2.png');
imagedestroy($img);
}

function 
decode(){
$img imagecreatefrompng("deadsea2.png");
$message='';
$x=imagesx($img);
$y=imagesy($img);
$px=0;
$py=23;
$h 23;
while( 
TRUE ){
    
$px += $h;
    if( 
$px $x ) {
        
$px $px%$x;
        
$py += $h;
    }
    
$rgb imagecolorat($img$px$py);
    
$R = ($rgb >> 16) & 0x7;
    
$G = ($rgb >> 8) & 0x7;
    
$B $rgb 0x3;
    
$m $R + ($G<<3) + ($B<<6);
    
$g=dechex($G<<3);
    
$b=dechex($B<<6);

    if( 
$m==) break;
    
$message .= chr($m);
}
return 
$message;
}
encode();
echo 
decode();
?>
Estos son los codigos tal cual los baje. he modificado mucho los dos.. pero sin resultados porsitivos. por lo cual decidi postear estos. como dije antes no entiendo mucho de esto pero sospecho que la cosa debe andar por la escritura en 0xFE y 0xFF .. lo cual probe pero nada, tambien probe cabiar los parametros $px y $py de 32 a 23 para ponerlos en los dos lenguajes.. tambien veo que puede hacer alguna cosa en que uno trabaja con imagenes 24 bites y el otro con 16.. tambien trate de acomodarlo.. pero no tuve suerte..

lo que pido no es que me lo hagan.. (para que nadie se enoje..) pero si alguien pudiera guiarme para encontrar el kid de la cuestion .. estaria muy agradecido.
  #2 (permalink)  
Antiguo 13/12/2014, 13:40
Avatar de NSD
NSD
Colaborador
 
Fecha de Ingreso: mayo-2012
Ubicación: Somewhere
Mensajes: 1.332
Antigüedad: 11 años, 11 meses
Puntos: 320
Respuesta: Steganografia de php a java

Lo que debes hacer que ambos scripts hagan lo mismo.

Al parecer recolectaste scripts de internet y pretendes que funcionen pero ambos son diferentes.

Te pongo los metodos encode de php y decode de java funcionando, te toca a ti escribir el encode en java y el decode en php, aunque simplemente tienes que transcribir y hacer cambios mínimos de sintaxis.

Código PHP:
Ver original
  1. <?php
  2.     class S12y
  3.     {
  4.         private $source = "";
  5.         private $target = "";
  6.         private $img = null;
  7.         private $size = [];
  8.  
  9.         public function __construct($source, $target = "")
  10.         {
  11.             $this->source = $source;
  12.             $this->target = $target;
  13.         $this->img = imagecreatefrompng($this->source);
  14.             $this->size = getimagesize($this->source);
  15.         }
  16.  
  17.         public function encode($message)
  18.         {
  19.             $message = str_split($message);
  20.             for($pxy=2; $pxy<$this->size[1]; $pxy+=2)
  21.             {
  22.                 for($pxx=1; $pxx<$this->size[0]; $pxx++)
  23.                 {                
  24.                     extract(imagecolorsforindex($this->img, imagecolorat($this->img, $pxx, $pxy-1)));
  25.                    
  26.                     if($message)
  27.                     {
  28.                         $ord = str_split(str_pad(ord(array_shift($message)), 3, "0", STR_PAD_LEFT));
  29.                        
  30.                         $red += $ord[0]; if($red > 255) $red -= 255;
  31.                         $green += $ord[1]; if($green > 255) $green -= 255;
  32.                         $blue += $ord[2]; if($blue > 255) $blue -= 255;
  33.                        
  34.                         imagesetpixel($this->img, $pxx, $pxy, imagecolorallocate($this->img, $red, $green, $blue));
  35.                     }
  36.                     else
  37.                     {
  38.                         imagesetpixel($this->img, $pxx, $pxy, imagecolorallocate($this->img, $red, $green, $blue));
  39.                         break 2;
  40.                     }
  41.                 }
  42.             }
  43.  
  44.             imagepng($this->img, ($this->target ? $this->target : $this->source));
  45.         }
  46.  
  47.         public function decode()
  48.         {
  49.             // TO-DO
  50.             $message = "";
  51.             return $message;
  52.         }
  53.     }
  54.  
  55.     $s12y = new S12y("imgen.png", "imagen-con-mensaje.png");
  56.     $s12y->encode("Hola!, mi nombre es NSD.");

Código Java:
Ver original
  1. package steganography;
  2.  
  3. import java.awt.Color;
  4. import java.awt.image.BufferedImage;
  5. import java.io.File;
  6. import java.io.IOException;
  7. import javax.imageio.ImageIO;
  8.  
  9. public class S12y {
  10.    
  11.     private BufferedImage img;
  12.     private String source = "";
  13.     private String target = "";
  14.     private int[] size;
  15.    
  16.     public S12y(String source)
  17.     {
  18.         this(source, "");
  19.     }
  20.    
  21.     public S12y(String source, String target)
  22.     {
  23.         this.source = source;
  24.         this.target = target;
  25.         try {
  26.             this.img = ImageIO.read(new File(this.source));
  27.         } catch (IOException e) {
  28.             e.printStackTrace();
  29.         }  
  30.         this.size = new int[2];
  31.         this.size[0] = this.img.getWidth();
  32.         this.size[1] = this.img.getHeight();
  33.     }
  34.    
  35.     public void encode()
  36.     {      
  37.         // TO-DO
  38.     }
  39.    
  40.     public String decode()
  41.     {
  42.         String message = "";
  43.        
  44.         outerloop:
  45.         for(int pxy=2; pxy<this.size[1]; pxy+=2)
  46.         {
  47.             for(int pxx=1; pxx<this.size[0]; pxx++)
  48.             {
  49.                 int old_rgb = this.img.getRGB(pxx, pxy-1);
  50.                 int new_rgb = this.img.getRGB(pxx, pxy);
  51.  
  52.                 if(old_rgb != new_rgb)
  53.                 {
  54.                     Color oldc = new Color(old_rgb);
  55.                     int old_red = oldc.getRed();
  56.                     int old_green = oldc.getGreen();
  57.                     int old_blue = oldc.getBlue();
  58.                     Color newc = new Color(new_rgb);
  59.                     int new_red = newc.getRed();
  60.                     int new_green = newc.getGreen();
  61.                     int new_blue = newc.getBlue();
  62.                                        
  63.                     String ord = (old_red <= new_red ? new_red - old_red : new_red + 255 - old_red)+"";
  64.                     ord += (old_green <= new_green ? new_green - old_green : new_green + 255 - old_green);
  65.                     ord += (old_blue <= new_blue ? new_blue - old_blue : new_blue + 255 - old_blue);
  66.                    
  67.                     message += Character.toString((char) Integer.parseInt(ord));
  68.                 }
  69.                 else
  70.                     break outerloop;
  71.             }
  72.         }
  73.  
  74.         return message;
  75.     }
  76.  
  77.     public static void main(String[] args) {
  78.         S12y img = new S12y("[path-to]/imagen-con-mensaje.png");
  79.  
  80.         System.out.println(img.decode());  
  81.     }
  82. }

La tecnica que se hace uso aca es muy simple, para cada letra se obtiene su valor ascii y luego los 3 digitos de dicho valor.
Luego, se recorre la imagen leyendo de a dos filas de pixeles, en la primera, se guarda el color de la segunda sumandole a cada canal de RGB un digito del valor ascii de la letra.

Cuando se acaba el mensaje, osea que se grabaron todas las letras, se guarda un pixel repetido en ambas lineas.

La funcion que lo decodifica hace lo mismo, va leyendo de a dos lineas y comparando los valores, rearma el codigo ascii y obtiene el caracter.

Una imagen puede contener ancho*alto/2 caracteres encubiertos.
__________________
Maratón de desafíos PHP Junio - Agosto 2015 en FDW | Reglamento - Desafios
  #3 (permalink)  
Antiguo 13/12/2014, 15:01
 
Fecha de Ingreso: enero-2007
Mensajes: 285
Antigüedad: 17 años, 3 meses
Puntos: 21
Respuesta: Steganografia de php a java

muchas gracias NSD... pero muchas de verdad... aun no lo probe.. pero ya me pongo con esto.. me gustaria explicarte.. que no pretendia que los dos scripts anduvieran de una. solo busque una base para arrancar.. ya que no conocia el tema como para hacerlo de cero. y de hecho.. trabaje mucho intentando modificarlos para que funcionen pero no tuve exito..

lo imortante ahora es que gracias a vos.. ya hay una traduccion para otro que pueda necesitarlo..y ahora yo voy a tratar de hacer lo que falta.. entenderlo bien.. para poder explicarlo.. para que no solo sea un copy paste de un tema..

reitero mi agradecimiento.

Etiquetas: Ninguno
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 20:34.