隐藏rgb彩色像素中的消息

时间:2015-03-13 14:16:56

标签: c#

我已经写了一些代码,它只是一个实验。我有一个想法(可能以前已经完成)创建随机图像并将随机位置的像素rgb值设置为ascii字符数,以隐藏图像中的消息。它几乎可以工作,但由于某种原因,我得到了解密的奇怪回报,例如" tiis是我的文本"而不是"这是我的秘密文本"那么这里是代码:

   public Form1()
    {
        InitializeComponent();
    }

    //storing pixel locations
    public static List<int> pixel_list = new List<int>();

    public static Bitmap bitmap = new Bitmap(144, 119);
    private void Form1_Load(object sender, EventArgs e)
    {

        bitmap = GenerateNoise(144, 119);

        bitmap = encrypt("this is my secret text",bitmap);

        pictureBox1.Image = bitmap;
    }

    public static void decrypt(Bitmap img) 
    {
        string str="";
        foreach (int pix in pixel_list)
        {
            //get the pixel from the list of pixel locations
            Color color = img.GetPixel(pix, pix);
            //convert the pixels rgb value in to a char and append it to str
            str += Convert.ToChar(color.R).ToString();

        }
        //we have the original message
        MessageBox.Show(str);
    }

    public Bitmap encrypt(string message, Bitmap img)
    {
        Random rnd = new Random();
        byte[] ASCIIValues = Encoding.ASCII.GetBytes(message);
        foreach (byte b in ASCIIValues)
        {
            //select a random pixel
            int pixelXY = rnd.Next(1, 119); 
            //add it to the list
            pixel_list.Add(pixelXY);
            //chnage that pixels rgb value to the ascii code (b)
            img.SetPixel(pixelXY, pixelXY, Color.FromArgb(b, b, b));
        }

        return img;
    }

    public Bitmap GenerateNoise(int width, int height)
    {
        Bitmap finalBmp = new Bitmap(width, height);
        Random r = new Random();

        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                int num = r.Next(0, 256);
                finalBmp.SetPixel(x, y, Color.FromArgb(10, num, num, num));
            }
        }

        return finalBmp;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        decrypt(bitmap);
    }

1 个答案:

答案 0 :(得分:1)

我认为在解密时,您使用的是Unicode而不是ASCII。您应该以与加密方式相反的方式解密。首先将所有字节存储在字节数组中,然后使用string str = System.Text.Encoding.ASCII.GetString(yourByteArray)

将数组转换为字符串