求大神指点,一种将文本编码为图片格式的方法
分类:计算机编程

世界上的文字可以被四个字节完全覆盖,也就是UTF-32,其他都是变长的格式。而恰好ARGB加起来四个字节,于是完全可以把一个字符映射为一个像素点嘛!

RSA解密异常,求大神指点
public string Encryption(string strKey) { CspParameters param = new CspParameters(); param.KeyContainerName = "Rich_CRM";//密匙容器的名称,保持加密解密一致才能解密成功 using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider { byte[] plaindata = Encoding.Default.GetBytes;//将要加密的字符串转换为字节数组 byte[] encryptdata = rsa.Encrypt(plaindata, false);//将加密后的字节数据转换为新的加密字节数组 return Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为字符串 } } //解密 public string Decrypt(string ciphertext) { CspParameters param = new CspParameters(); param.KeyContainerName = "Rich_CRM"; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider { byte[] encryptdata = Convert.FromBase64String(ciphertext); byte[] decryptdata = rsa.Decrypt(encryptdata, true); return Encoding.Default.GetString(decryptdata); } } 同样的代码,用winform测试都是可以的,但是写webservice的时候,解密执行到byte[] decryptdata = rsa.Decrypt(encryptdata, true);会有问题,没有报错,直接跳出去了,这是为什么?求大神指点

.NET Core上面的DES等加密算法要等到1.2 才支持,我们可是急需这个算法的支持,文章《使用 JavaScriptService 在.NET Core 里实现DES加密算法》需要用Nodejs,很多人觉得这个有点不好,今天就给大家介绍下BouncyCastle (Portable.BouncyCastle)库为我们提供的原生的.NET Core的支持库的Des算法。BouncyCastle的文档比较少,折腾了好久才写出了.NET 代码等价的一个封装。

刚刚学会的C#的加密与解密MD5加密/RSA加密与解密/DES加密。也是刚刚申请的blog随便发布一下。

并且图片上的字节可以再次加密,非常好玩!我仅演示的超级无敌简单的取反操作。

  public class TDesbouncy
    {

、MD5加密

 

        IBlockCipher engine = new DesEngine();

MD5 md5 = new MD5CryptoServiceProvider();
byte[] palindata = Encoding.Default.GetBytes(textBox1.Text);//将要加密的字符串转换为字节数组
byte[] encryptdata = md5.ComputeHash(palindata);//将字符串加密后也转换为字符数组
textBox2.Text = Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为加密字符串

我自己习惯看方形的图片,于是开平方取整,如果字符数量不足就从字符本身随机取一段,这是为了图片尾部不会几个像素留白,炒鸡不美观,以白色(0xFFFFFFFF)作为终止字符。

        /// <summary>
        /// 使用DES加密,key输入密码的时候,必须使用英文字符,区分大小写,且字符数量是8个,不能多也不能少
        /// </summary>
        /// <param name="plainText">需要加密的字符串</param>
        /// <param name="keys">加密字符串的密钥</param>
        /// <returns>加密后的字符串</returns>
        public string Encrypt(string keys, string plainText)
        {

、RAS加密

static Bitmap ArgbTextEncode(string input)
        {
            var x = 0;
            var y = 0;
            var lenth = input.Length;
            var yValue = (int)(Math.Sqrt(input.Length)   1);
            var fill = (yValue * yValue) % (Encoding.Unicode.GetByteCount(input) / 4);
            input  = input.Substring(Rnd.random.Next(input.Length - fill - 1), fill);
            var image = new Bitmap(yValue, yValue);

            //fill
            for (int i = 0; i < yValue * yValue; i  )
            {
                if (i == lenth - 1)
                {
                    image.SetPixel(x, y, Color.White);
                }
                else
                {
                    byte[] bytes = Encoding.Unicode.GetBytes(input[i].ToString());
                    var prefix = 4 - bytes.Length;
                    bytes = Enumerable.Repeat<byte>(0, prefix).Concat(bytes).ToArray();
                    Encrypt(bytes);
                    image.SetPixel(x, y, Color.FromArgb(bytes[0], bytes[1], bytes[2], bytes[3]));
                }
                //Console.WriteLine("{0},{1} = {2}", x, y, input[i]);
                x  ;
                if (x % yValue == 0)
                {
                    x = 0;
                    y  ;
                }
            }
            return image;
        }

            byte[] ptBytes = Encoding.UTF8.GetBytes(plainText);
            byte[] rv = Encrypt(keys, ptBytes);
            StringBuilder ret = new StringBuilder();
            foreach (byte b in rv)
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

首先声明全局变量:CspParameters param;

  

        private byte[] Encrypt(string keys, byte[] ptBytes)
        {
            byte[] key = Encoding.UTF8.GetBytes(keys);
            BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine),new Pkcs7Padding());
            cipher.Init(true, new ParametersWithIV(new DesParameters(key),key));
            byte[] rv = new byte[cipher.GetOutputSize(ptBytes.Length)];
            int tam = cipher.ProcessBytes(ptBytes, 0, ptBytes.Length, rv, 0);

RAS加密:

找了一个日志文本,看看效果

             cipher.DoFinal(rv, tam);
             return rv;
        }

param = new CspParameters();
param.KeyContainerName = "Olive";//密匙容器的名称,保持加密解密一致才能解密成功
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider
{
byte[] plaindata = Encoding.Default.GetBytes(textBox1.Text);//将要加密的字符串转换为字节数组
byte[] encryptdata = rsa.Encrypt(plaindata, false);//将加密后的字节数据转换为新的加密字节数组
textBox2.Text = Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为字符串
}

图片 1

        /// <summary>
        /// 使用DES解密,key输入密码的时候,必须使用英文字符,区分大小写,且字符数量是8个,不能多也不能少
        /// </summary>
        /// <param name="cipherText">需要加密的字符串</param>
        /// <param name="keys">加密字符串的密钥</param>
        /// <returns>解密后的字符串</returns>
        public string Decrypt(string keys, string cipherText)
        {
            byte[] inputByteArray = new byte[cipherText.Length / 2];
            for (int x = 0; x < cipherText.Length / 2; x )
            {
                int i = (Convert.ToInt32(cipherText.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }
            var rv = Decrypt(keys, inputByteArray);

RAS解密:

 

            return Encoding.UTF8.GetString(rv);

param = new CspParameters();
param.KeyContainerName = "Olive";
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider
{
byte[] encryptdata = Convert.FromBase64String(this.textBox2.Text);
byte[] decryptdata = rsa.Decrypt(encryptdata, false);
textBox3.Text = Encoding.Default.GetString(decryptdata);
}

 

        }

DES加密:

解码函数

        private byte[] Decrypt(string keys, byte[] cipherText)
        {
            byte[] key = Encoding.UTF8.GetBytes(keys);
            BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine));
            cipher.Init(false, new ParametersWithIV(new DesParameters(key), key));
            byte[] rv = new byte[cipher.GetOutputSize(cipherText.Length)];
            int tam = cipher.ProcessBytes(cipherText, 0, cipherText.Length, rv, 0);

首先声明全局变量

 

            cipher.DoFinal(rv, tam);

byte[] buffer;
DESCryptoServiceProvider DesCSP = new DESCryptoServiceProvider();

static string DecodeTextFromArgb(Bitmap image)
        {
            //ComplexImage comp = ComplexImage.FromBitmap(image);
            //comp.BackwardFourierTransform();
            var str = "";
            for (int i = 0; i < image.Height; i  )
            {
                for (int j = 0; j < image.Width; j  )
                {
                    var color = image.GetPixel(j, i);
                    if (color.A == 255 && color.R == 255 && color.G == 255 && color.B == 255)
                        return str;
                    var bytes = new byte[] { color.A, color.R, color.G, color.B };
                    Decrypt(bytes);
                    int skip = 0;
                    if (bytes[0] == 0)
                    {
                        if (bytes[1] == 0)
                        {
                            skip = 2;
                        }
                        else
                        {
                            skip = 1;
                        }
                    }
                    else
                    {
                        skip = 0;
                    }
                    var t = Encoding.Unicode.GetString(bytes.Skip(skip).ToArray());
                    //Console.WriteLine("{0},{1} = {2}", j, i, t);
                    str  = t;
                }
            }
            return str;
        }

            return rv;
        }

DES解密:

  

    }

MemoryStream ms = new MemoryStream;//将加密后的字节数据加入内存流中
CryptoStream cryStream = new CryptoStream(ms, DesCSP.CreateDecryptor(), CryptoStreamMode.Read);//内存流连接到解密流中
StreamReader sr = new StreamReader(cryStream);
textBox5.Text = sr.ReadLine();//将解密流读取为字符串
sr.Close();
cryStream.Close();
ms.Close();

 

public static void Main(string[] args)
{
           
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

好了,就先写到这吧,界面就不展示了。

里面用到的Encrypt和Decrypt是取反的,不然图片一片漆黑,啥看不见。这句是我刚想到真的用取反操作符来,实际我是用的255去减的。

            string key = "geffzhan";
            string content =   "This project.config whoopla is a mess. So what they mean by .NetCore, you still have to reference everything correctly";

unchecked((byte)~(byte)value)

            TDesbouncy bouncy = new TDesbouncy();

  

            var encrypt = bouncy.Encrypt(key, content);
            Console.WriteLine(encrypt);

Encrypt和Decrypt,其实一样的。。哈哈

            string descontent = bouncy.Decrypt(key, encrypt);
            Console.WriteLine(descontent);
}

static byte[] Encrypt(byte[] values)
        {
            for (int i = 0; i < values.Length; i  )
            {
                values[i] = (byte)(255 - values[i]);
            }
            return values;
        }
        static byte[] Decrypt(byte[] values)
        {
            for (int i = 0; i < values.Length; i  )
            {
                values[i] = (byte)(255 - values[i]);
            }
            return values;
        }

  

本程序完整代码如下:

class Program
    {
        static void Main(string[] args)
        {
            if (!args.Any())
            {
                return;
            }
            else if (args[0].EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
            {
                var textRaw = File.ReadAllText(args[0], Encoding.Unicode);
                var image = ArgbTextEncode(textRaw);
                var imagePath = Path.ChangeExtension(args[0], ".png");
                image.Save(imagePath, ImageFormat.Png);
                image.Dispose();
                Console.WriteLine("TXT->PNG, "   imagePath);
                try
                {
                    Process.Start(imagePath);
                }
                catch
                {
                }
            }
            else if (args[0].EndsWith(".png", StringComparison.OrdinalIgnoreCase))
            {
                var image = (Bitmap)Bitmap.FromFile(args[0]);
                string text = "";
                try
                {
                    text = DecodeTextFromArgb(image);

                }
                catch (Exception ex)
                {
                    Console.WriteLine("PNG->TXT, 转换失败");
                    return;
                }
                var txtPath = Path.ChangeExtension(args[0], ".txt");
                File.WriteAllText(txtPath, text, Encoding.Unicode);
                Console.WriteLine("PNG->TXT, "   txtPath);
                try
                {
                    Process.Start(txtPath);
                }
                catch
                {
                }
            }
            else
            {
                Console.WriteLine("只支持TXT和PNG文件");
            }
        }

        static Bitmap ArgbTextEncode(string input)
        {
            var x = 0;
            var y = 0;
            var lenth = input.Length;
            var yValue = (int)(Math.Sqrt(input.Length)   1);
            var fill = (yValue * yValue) % (Encoding.Unicode.GetByteCount(input) / 4);
            input  = input.Substring(Rnd.random.Next(input.Length - fill - 1), fill);
            var image = new Bitmap(yValue, yValue);

            //fill
            for (int i = 0; i < yValue * yValue; i  )
            {
                if (i == lenth - 1)
                {
                    image.SetPixel(x, y, Color.White);
                }
                else
                {
                    byte[] bytes = Encoding.Unicode.GetBytes(input[i].ToString());
                    var prefix = 4 - bytes.Length;
                    bytes = Enumerable.Repeat<byte>(0, prefix).Concat(bytes).ToArray();
                    Encrypt(bytes);
                    image.SetPixel(x, y, Color.FromArgb(bytes[0], bytes[1], bytes[2], bytes[3]));
                }
                //Console.WriteLine("{0},{1} = {2}", x, y, input[i]);
                x  ;
                if (x % yValue == 0)
                {
                    x = 0;
                    y  ;
                }
            }
            return image;
        }

        static byte[] Encrypt(byte[] values)
        {
            for (int i = 0; i < values.Length; i  )
            {
                values[i] = (byte)(255 - values[i]);
            }
            return values;
        }
        static byte[] Decrypt(byte[] values)
        {
            for (int i = 0; i < values.Length; i  )
            {
                values[i] = (byte)(255 - values[i]);
            }
            return values;
        }

        static string DecodeTextFromArgb(Bitmap image)
        {
            //ComplexImage comp = ComplexImage.FromBitmap(image);
            //comp.BackwardFourierTransform();
            var str = "";
            for (int i = 0; i < image.Height; i  )
            {
                for (int j = 0; j < image.Width; j  )
                {
                    var color = image.GetPixel(j, i);
                    if (color.A == 255 && color.R == 255 && color.G == 255 && color.B == 255)
                        return str;
                    var bytes = new byte[] { color.A, color.R, color.G, color.B };
                    Decrypt(bytes);
                    int skip = 0;
                    if (bytes[0] == 0)
                    {
                        if (bytes[1] == 0)
                        {
                            skip = 2;
                        }
                        else
                        {
                            skip = 1;
                        }
                    }
                    else
                    {
                        skip = 0;
                    }
                    var t = Encoding.Unicode.GetString(bytes.Skip(skip).ToArray());
                    //Console.WriteLine("{0},{1} = {2}", j, i, t);
                    str  = t;
                }
            }
            return str;
        }
    }

  

 源码地址:

本文由pc28.am发布于计算机编程,转载请注明出处:求大神指点,一种将文本编码为图片格式的方法

上一篇:0A_Windows下相同的时候设置Python2和Python3 下一篇:没有了
猜你喜欢
热门排行
精彩图文