Exemplo n.º 1
0
        static void Main(string[] args)
        {
            Console.WriteLine(2 << 1);
            Console.WriteLine(RsaKeyGenerator.XmlKey(2048)[0]);
            Console.WriteLine(RsaKeyGenerator.Pkcs1Key(2048, true)[0]);
            Console.WriteLine(RsaKeyGenerator.Pkcs8Key(2048, true)[0]);


            Console.WriteLine("Key Convert:");
            var keyList    = RsaKeyGenerator.Pkcs1Key(512, false);
            var privateKey = keyList[0];
            var publicKey  = keyList[1];

            Console.WriteLine("public key pkcs1->xml:");
            Console.WriteLine(RsaKeyConvert.PublicKeyPemToXml(publicKey));

            var bigDataRsa = new RsaPkcs1Util(Encoding.UTF8, publicKey, privateKey, 2048);
            var data       = "响应式布局的概念是一个页面适配多个终端及不同分辨率。在针对特定屏幕宽度优化应用 UI 时,我们将此称为创建响应式设计。WPF设计之初响应式设计的概念并不流行,那时候大部分网页设计师都按着宽度960像素的标准设计。到了UWP诞生的时候响应式布局已经很流行了,所以UWP提供了很多响应式布局的技术,这篇文章简单总结了一些响应式布局常用的技术,更完整的内容请看文章最后给出的参考网站。所谓的传统,是指在响应式设计没流行前XAML就已经存在的应对不同分辨率的技术,毕竟桌面客户端常常也调整窗体的大小,有些人还同时使用两个不同分辨率的屏幕。以我的经验来说以下这些做法可以使UI有效应对分辨率改变不同的DPI设定、不同的本地化字符串长度都可能使整个页面布局乱掉。而且和网页不同,WPF窗体默认没有提供ScrollViewer,所以千万不能忘记。在桌面客户端合理使用以上技术可以避免客户投诉。但UWP主打跨平台,它需要更先进(或者说,更激进)的技术。微软的官方文档介绍了UWP中响应式设计常用的6个技术,包括重新定位、调整大小、重新排列、显示/隐藏、替换和重新构建,具体可见以下网站:UWP中部分控件已经实现了响应式行为, 最典型的就是NavigationView。可以使用 PaneDisplayMode 属性配置不同的导航样式或显示模式。默认情况下,PaneDisplayMode 设置为 Auto。在 Auto 模式下,导航视图会进行自适应,在窗口狭窄时为 LeftMinimal,接下来为 LeftCompact,随后在窗口变宽时为 Left。这种时候MVVM的优势就体现出来了,因为VIEW和VIEWMODEL解耦了,VIEW随便换,而且整个UI显示隐藏说不定比多个小模块独自改变性能更好。说到性能,UWP的很多场景都为已经死了多年的WindowsWobile考虑了性能,更不用说现在的桌面平台,所以做UWP不需要太过介意性能,尤其是已经在WPF上培养出小心翼翼的习惯的开发者,UWP的性能问题等真的出现了再说。除了使用显示隐藏,UWP还可以使用限定符名称指定CodeBehind对应的XAML文件,这有点像是自适应应用的话题。使用格式如下";
            var str        = bigDataRsa.EncryptBigData(data, RSAEncryptionPadding.Pkcs1);

            Console.WriteLine("Big Data Encrypt:");
            Console.WriteLine(str);
            Console.WriteLine("Big Data Decrypt:");
            Console.WriteLine(string.Join("", bigDataRsa.DecryptBigData(str, RSAEncryptionPadding.Pkcs1)));

            Console.ReadKey();
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            Console.WriteLine(RsaKeyGenerator.XmlKey(2048)[0]);
            Console.WriteLine(RsaKeyGenerator.Pkcs1Key(2048, true)[0]);
            Console.WriteLine(RsaKeyGenerator.Pkcs8Key(2048, true)[0]);


            Console.WriteLine("Key Convert:");
            var keyList    = RsaKeyGenerator.Pkcs1Key(2048, false);
            var privateKey = keyList[0];
            var publicKey  = keyList[1];

            Console.WriteLine("public key pkcs1->xml:");
            Console.WriteLine(RsaKeyConvert.PublicKeyPemToXml(publicKey));

            var bigDataRsa = new RsaPkcs1Util(Encoding.UTF8, publicKey, privateKey, 2048);
            var str        = bigDataRsa.EncryptBigData("abcdefg", 3, "$", RSAEncryptionPadding.Pkcs1);

            Console.WriteLine("Big Data Encrypt:");
            Console.WriteLine(str);
            Console.WriteLine("Big Data Decrypt:");
            Console.WriteLine(string.Join("", bigDataRsa.DecryptBigData(str, "$", RSAEncryptionPadding.Pkcs1)));

            Console.ReadKey();
        }
Exemplo n.º 3
0
        public string setRsa()      //初始化,生成PKCS1密钥对,将私钥保存在session中用于解密接收到的密码密文,将公钥传到前端用于密码加密
        {
            RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
            //添加参数
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(BigInteger.ValueOf(3), new SecureRandom(), 1024, 25);

            //初始化构造器
            keyGenerator.Init(param);
            //生成密钥对
            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
            TextWriter textWriter           = new StringWriter();
            PemWriter  pemWriter            = new PemWriter(textWriter);

            pemWriter.WriteObject(keyPair.Private); //获取密钥对的私钥
            pemWriter.Writer.Flush();               //清空缓存区,防止脏写
            string priKey = textWriter.ToString();

            priKey             = RsaKeyConvert.PrivateKeyPkcs1ToPkcs8(priKey);
            Session["Private"] = priKey;    //将私钥保存在session中
            TextWriter textWriter1 = new StringWriter();
            PemWriter  pemWriter1  = new PemWriter(textWriter1);

            pemWriter1.WriteObject(keyPair.Public); //获取密钥对的公钥
            pemWriter1.Writer.Flush();              //清空缓存区,防止脏写
            string pubKey = textWriter1.ToString();

            Session["pub"] = pubKey;    //将私钥保存在session中

            //将公钥存入cookie方便读取
            Response.Cookies["Key"].Expires = DateTime.Now.AddDays(-1);
            Response.Cookies["Key"].Value   = pubKey;
            Response.Cookies["Key"].Expires = DateTime.Now.AddDays(1);
            return(pubKey);  //将公钥传到前端
        }
Exemplo n.º 4
0
        /// <summary>
        /// 使用现有秘钥覆盖生成秘钥
        /// </summary>
        /// <param name="publicKey">公钥</param>
        /// <param name="privateKey">私钥</param>
        public static void InitRsaByKey(string publicKey, string privateKey)
        {
            PublicKeyString  = string.IsNullOrEmpty(publicKey) ? PublicKeyString : publicKey;
            PrivateKeyString = string.IsNullOrEmpty(privateKey) ? PrivateKeyString : privateKey;

            ImportKeyPair(RsaKeyConvert.PublicKeyPemToXml(PublicKeyString),
                          RsaKeyConvert.PrivateKeyPkcs1ToXml(PrivateKeyString));
        }
Exemplo n.º 5
0
        /// <summary>
        /// 获取公钥的内容
        /// </summary>
        /// <returns></returns>
        public async Task <string> GetPublicKeyStringAsync()
        {
            var pubKey = await cacheMemory.GetAsync <string>(RSAConfig.Cache_PublicKey);

            if (string.IsNullOrWhiteSpace(pubKey))
            {
                await CreateRSACacheAsync();

                pubKey = await cacheMemory.GetAsync <string>(RSAConfig.Cache_PublicKey);
            }
            return(RsaKeyConvert.PublicKeyXmlToPem(pubKey));
        }
Exemplo n.º 6
0
        /// <summary>
        /// 生成秘钥
        /// </summary>
        private static void InitRsa()
        {
            var handle = RSA.Create();

            PublicKey  = handle.ExportParameters(false);
            PrivateKey = handle.ExportParameters(true);

            PublicKeyString = RsaKeyConvert.PublicKeyXmlToPem(
                handle.ToXmlString(false));
            PrivateKeyString = RsaKeyConvert.PrivateKeyXmlToPkcs1(
                handle.ToXmlString(true));
        }
Exemplo n.º 7
0
 /// <summary>
 /// Pkcs8-> Pkcs1
 /// </summary>
 /// <param name="privateKeyXml">私钥</param>
 /// <returns></returns>
 public static string ConvertPrivateKeyPkcs8ToPkcs1(string privateKeyXml)
 {
     if (privateKeyXml is null)
     {
         return("null");
     }
     try
     {
         return(RsaKeyConvert.PrivateKeyPkcs8ToPkcs1(privateKeyXml));
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
Exemplo n.º 8
0
 /// <summary>
 /// XML-> Pkcs1
 /// </summary>
 /// <param name="publicKeyXml">公钥</param>
 /// <returns></returns>
 public static string ConvertPublicKeyXmlToPkcs1(string publicKeyXml)
 {
     if (publicKeyXml is null)
     {
         return("null");
     }
     try
     {
         return(RsaKeyConvert.PublicKeyXmlToPem(publicKeyXml));
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
Exemplo n.º 9
0
        protected static string Sign(string content, string privateKey)
        {
            privateKey = RsaKeyConvert.PrivateKeyPkcs8ToXml(privateKey);
            byte[] bt     = Encoding.GetEncoding("utf-8").GetBytes(content);
            var    sha256 = new SHA256CryptoServiceProvider();

            byte[] rgbHash = sha256.ComputeHash(bt);

            RSACryptoServiceProvider key = new RSACryptoServiceProvider();

            key.FromXmlString(privateKey);
            RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);

            formatter.SetHashAlgorithm("SHA256");
            byte[] inArray = formatter.CreateSignature(rgbHash);
            return(Convert.ToBase64String(inArray));
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            Console.WriteLine(RsaKeyGenerator.XmlKey(2048)[0]);
            Console.WriteLine(RsaKeyGenerator.Pkcs1Key(2048, true)[0]);
            Console.WriteLine(RsaKeyGenerator.Pkcs8Key(2048, true)[0]);


            Console.WriteLine("Key Convert:");
            var keyList    = RsaKeyGenerator.Pkcs1Key(2048, false);
            var privateKey = keyList[0];
            var publicKey  = keyList[1];

            Console.WriteLine("public key pkcs1->xml:");
            Console.WriteLine(RsaKeyConvert.PublicKeyPemToXml(publicKey));

            Console.ReadKey();
        }
Exemplo n.º 11
0
        protected static bool verify(string content, string signedString, string publicKey)
        {
            signedString = signedString.Replace(" ", "+");
            publicKey    = publicKey.Replace("%0d", "\r").Replace("%0a", "\n");
            publicKey    = RsaKeyConvert.PublicKeyPemToXml(publicKey);
            byte[] bt     = Encoding.GetEncoding("utf-8").GetBytes(content);
            var    sha256 = new SHA256CryptoServiceProvider();

            byte[] rgbHash = sha256.ComputeHash(bt);

            RSACryptoServiceProvider key = new RSACryptoServiceProvider();

            key.FromXmlString(publicKey);
            RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key);

            deformatter.SetHashAlgorithm("SHA256");
            byte[] rgbSignature = Convert.FromBase64String(signedString);
            if (deformatter.VerifySignature(rgbHash, rgbSignature))
            {
                return(true);
            }
            return(false);
        }
Exemplo n.º 12
0
 //封装方法,实现委托
 public static void ConversionRSAKeyFunc(string privateKey, string publicKey, EnumConversionType enumConversionType)
 {
     if (enumConversionType == EnumConversionType.XML转化为Pkcs1)
     {
         if (!string.IsNullOrWhiteSpace(privateKey))
         {
             Console.WriteLine(privateKey);
             Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
             Console.WriteLine(RsaKeyConvert.PrivateKeyXmlToPkcs1(privateKey));
         }
         if (!string.IsNullOrWhiteSpace(publicKey))
         {
             Console.WriteLine(publicKey);
             Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
             Console.WriteLine(RsaKeyConvert.PublicKeyXmlToPem(privateKey));
         }
         if (string.IsNullOrWhiteSpace(privateKey) && string.IsNullOrWhiteSpace(publicKey))
         {
             Console.WriteLine("请输入正确的公私钥");
         }
     }
     else if (enumConversionType == EnumConversionType.XML转化为Pkcs8)
     {
         if (!string.IsNullOrWhiteSpace(privateKey))
         {
             Console.WriteLine(privateKey);
             Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
             Console.WriteLine(RsaKeyConvert.PrivateKeyXmlToPkcs8(privateKey));
         }
         if (!string.IsNullOrWhiteSpace(publicKey))
         {
             Console.WriteLine(publicKey);
             Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
             Console.WriteLine(RsaKeyConvert.PublicKeyXmlToPem(privateKey));
         }
         if (string.IsNullOrWhiteSpace(privateKey) && string.IsNullOrWhiteSpace(publicKey))
         {
             Console.WriteLine("请输入正确的公私钥");
         }
     }
     else if (enumConversionType == EnumConversionType.Pkcs1转化为XML)
     {
         if (!string.IsNullOrWhiteSpace(privateKey))
         {
             Console.WriteLine(privateKey);
             Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
             Console.WriteLine(RsaKeyConvert.PrivateKeyPkcs1ToXml(privateKey));
         }
         if (!string.IsNullOrWhiteSpace(publicKey))
         {
             Console.WriteLine(publicKey);
             Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
             Console.WriteLine(RsaKeyConvert.PublicKeyPemToXml(publicKey));
         }
         if (string.IsNullOrWhiteSpace(privateKey) && string.IsNullOrWhiteSpace(publicKey))
         {
             Console.WriteLine("请输入正确的公私钥");
         }
     }
     else if (enumConversionType == EnumConversionType.Pkcs1转化为Pkcs8)
     {
         if (!string.IsNullOrWhiteSpace(privateKey))
         {
             Console.WriteLine(privateKey);
             Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
             Console.WriteLine(RsaKeyConvert.PrivateKeyPkcs1ToPkcs8(privateKey));
         }
         if (!string.IsNullOrWhiteSpace(publicKey))
         {
             Console.WriteLine("No conversion required");
         }
         if (string.IsNullOrWhiteSpace(privateKey) && string.IsNullOrWhiteSpace(publicKey))
         {
             Console.WriteLine("请输入正确的公私钥");
         }
     }
     else if (enumConversionType == EnumConversionType.Pkcs8转化为XML)
     {
         if (!string.IsNullOrWhiteSpace(privateKey))
         {
             Console.WriteLine(privateKey);
             Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
             Console.WriteLine(RsaKeyConvert.PrivateKeyPkcs8ToXml(privateKey));
         }
         if (!string.IsNullOrWhiteSpace(publicKey))
         {
             Console.WriteLine(publicKey);
             Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
             Console.WriteLine(RsaKeyConvert.PublicKeyPemToXml(publicKey));
         }
         if (string.IsNullOrWhiteSpace(privateKey) && string.IsNullOrWhiteSpace(publicKey))
         {
             Console.WriteLine("请输入正确的公私钥");
         }
     }
     else
     {
         if (!string.IsNullOrWhiteSpace(privateKey))
         {
             Console.WriteLine(privateKey);
             Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
             Console.WriteLine(RsaKeyConvert.PrivateKeyPkcs8ToPkcs1(privateKey));
         }
         if (!string.IsNullOrWhiteSpace(publicKey))
         {
             Console.WriteLine("No conversion required");
         }
         if (string.IsNullOrWhiteSpace(privateKey) && string.IsNullOrWhiteSpace(publicKey))
         {
             Console.WriteLine("请输入正确的公私钥");
         }
     }
 }
Exemplo n.º 13
0
        private int OnExecute(CommandLineApplication app)
        {
            if (app.Options.Count == 1 && app.Options[0].ShortName == "h")
            {
                app.ShowHelp();
                return(0);
            }

            if (KeyType == "pub" && ((SourceFormat == "pkcs1" && TargetFormat == "pkcs8") ||
                                     (SourceFormat == "pkcs8" && TargetFormat == "pkcs1")))
            {
                app.Out.WriteLine("This public key does not need to be converted.");
                return(1);
            }

            if (SourceFormat == TargetFormat)
            {
                app.Out.WriteLine("Target format can not equal Source format.");
                return(1);
            }

            try
            {
                string result     = string.Empty;
                string keyContent = File.ReadAllText(KeyFilePath);

                if (KeyType == "pri")
                {
                    switch ($"{SourceFormat}->{TargetFormat}")
                    {
                    case "xml->pkcs1":
                        result = RsaKeyConvert.PrivateKeyXmlToPkcs1(keyContent);
                        break;

                    case "xml->pkcs8":
                        result = RsaKeyConvert.PrivateKeyXmlToPkcs8(keyContent);
                        break;

                    case "pkcs1->xml":
                        result = RsaKeyConvert.PrivateKeyPkcs1ToXml(keyContent);
                        break;

                    case "pkcs1->pkcs8":
                        result = RsaKeyConvert.PrivateKeyPkcs1ToPkcs8(keyContent);
                        break;

                    case "pkcs8->xml":
                        result = RsaKeyConvert.PrivateKeyPkcs8ToXml(keyContent);
                        break;

                    case "pkcs8->pkcs1":
                        result = RsaKeyConvert.PrivateKeyPkcs8ToPkcs1(keyContent);
                        break;
                    }
                }
                else
                {
                    result = SourceFormat == "xml" ? RsaKeyConvert.PublicKeyXmlToPem(keyContent) : RsaKeyConvert.PublicKeyPemToXml(keyContent);
                }

                if (!Directory.Exists(Output))
                {
                    Directory.CreateDirectory(Output);
                }
                string fileName = $"{new FileInfo(KeyFilePath).Name}.new.key";
                string savePath = Path.Combine(Output, fileName);
                File.WriteAllText(savePath, result);
                app.Out.WriteLine($"Process success.File saved in {savePath}.");
            }
            catch (Exception e)
            {
                app.Out.WriteLine($"Process error.Detail message:{e.Message}");
                return(1);
            }

            return(0);
        }
Exemplo n.º 14
0
        private static void Main(string[] args)
        {
            var input = ",130680807779,";
            // 取匹配
            var matches = Regex.Matches(input, @"(1)\d{10}")
                          .Select(m => m.Value)
                          .ToList();

            matches = Regex.Matches(",1306808077701234,", @"(1)\d{10,20}")
                      .Select(m => m.Value)
                      .ToList();

            matches = Regex.Matches("17703430350,,", @"(1)\d{10,20}")
                      .Select(m => m.Value)
                      .ToList();


            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var str      = "筷开动1234Abc";
            var gbk      = Encoding.GetEncoding("GBK").GetBytes(str);
            var gbkToStr = Encoding.GetEncoding("GBK").GetString(gbk);

            Console.WriteLine($"GBK是否相同:{str == gbkToStr}\n");

            Console.WriteLine("获取Ticks测试------start-------");
            for (var i = 0; i < 10; i++)
            {
                var ticks = DateTime.Now.Ticks.ToString();
                Console.WriteLine($"    {i} ticks:{ticks} len:{ticks.Length}");
            }

            Console.WriteLine("获取Ticks测试------end-------");

            var keyList    = RsaKeyGenerator.XmlKey(2048);
            var privateKey = keyList[0];
            var publicKey  = keyList[1];

            var source      = "1234再看看看!@#¥#!#";
            var rsaXmlUtil  = new RsaXmlUtil(Encoding.UTF8, publicKey, privateKey);
            var encryptData = rsaXmlUtil.Encrypt(source, RSAEncryptionPadding.OaepSHA256);

            Console.WriteLine("加密测试:");
            Console.WriteLine("   加密后的数据:{0}", encryptData);
            var decryptData = rsaXmlUtil.Decrypt(encryptData, RSAEncryptionPadding.OaepSHA256);

            Console.WriteLine("\n   解密后的数据:{0}", decryptData);

            Console.WriteLine("   解密后的数据与源数据相同:{0}", source == decryptData);
            Console.WriteLine("\n签名测试:");
            var signData = rsaXmlUtil.SignData(source, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

            Console.WriteLine("   签名值:{0}", signData);
            var verifyRet =
                rsaXmlUtil.VerifyData(source, signData, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

            Console.WriteLine("   验证签名:{0}", verifyRet);

            Console.WriteLine("\n签名转换:");
            var privatePkcs1 = RsaKeyConvert.PrivateKeyXmlToPkcs1(privateKey);
            var publicPkcs1  = RsaKeyConvert.PublicKeyXmlToPem(publicKey);

            Console.WriteLine(" private key of Pkcs1:{0}", privatePkcs1);
            Console.WriteLine(" public key of Pkcs1:{0}", publicPkcs1);

            Console.WriteLine("Guid转换String测试.---开始---");
            var id = Guid.NewGuid();

            var idString = id.ToString("N");

            Console.WriteLine("Guid.ToString(N)={0},原guid:{1}", idString, id);
            var idFromString = Guid.ParseExact(idString, "N");

            Console.WriteLine("Guid.ParseExact(idString,N):{0} ,是否相等:{1}", idFromString, idFromString == id);
            Console.WriteLine("Guid转换String测试.---结束。");
            Console.ReadLine();
        }
Exemplo n.º 15
0
 /// <summary>
 /// Pkcs8-> Pkcs1
 /// </summary>
 public void Pkcs8ToPkcs1()
 {
     PrivateKey = RsaKeyConvert.PrivateKeyPkcs8ToPkcs1(PrivateKey);
 }
Exemplo n.º 16
0
 /// <summary>
 /// Pkcs8-> XML
 /// </summary>
 public void Pkcs8ToXml()
 {
     PrivateKey = RsaKeyConvert.PrivateKeyPkcs8ToXml(PrivateKey);
     PublicKey  = RsaKeyConvert.PublicKeyPemToXml(PublicKey);
 }
Exemplo n.º 17
0
 /// <summary>
 /// XML-> Pkcs8
 /// </summary>
 public void XmlToPkcs8()
 {
     PrivateKey = RsaKeyConvert.PrivateKeyXmlToPkcs8(PrivateKey);
     PublicKey  = RsaKeyConvert.PublicKeyXmlToPem(PublicKey);
 }