• 密码学系列——非对称加密


    前言

    ① 非对称加密算法又称现代加密算法。
    ② 非对称加密是计算机通信安全的基石,保证了加密数据不会被破解。
    ③ 与对称加密算法不同,非对称加密算法需要两个密钥:公开密钥(publickey) 和私有密(privatekey)
    ④ 公开密钥和私有密钥是一对
    ⑤ 如果用公开密钥对数据进行加密,只有用对应的私有密钥才能解密。
    ⑥ 如果用私有密钥对数据进行加密,只有用对应的公开密钥才能解密。
    ⑦ 因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。

    特点:
    加密和解密使用不同的密钥
    如果使用私钥加密, 只能使用公钥解密
    如果使用公钥加密, 只能使用私钥解密
    处理数据的速度较慢, 因为安全级别高
    常见算法:
    RSA
    ECC

    正文

    认识RSA 之前,需要认识一个叫做PKCS的东西。

    百度百科地址:

    https://baike.baidu.com/item/PKCS/1042350?fr=aladdin
    

    它其实是一组公钥密码学标准。

    测试代码如下:

    static void Main(string[] args)
    {
    	//RSACryptoServiceProvider rsaService = new RSACryptoServiceProvider();
    	//var privatyKey=rsaService.ToXmlString(true);
    	//var publicKey = rsaService.ToXmlString(false);
    	//Console.WriteLine("打印私钥:"+privatyKey);
    	//Console.WriteLine("打印公钥:"+publicKey);
    	//Console.ReadKey();
    	RSAKeyParameter rsa1=Pkcs1(1000);
    	Console.WriteLine("公钥为:"+rsa1.PublicKey+"私钥为:"+rsa1.PrivateKey);
    	RSAKeyParameter rsa2 = Pkcs1(1000,true);
    	Console.WriteLine("公钥为:" + rsa2.PublicKey + "私钥为:" + rsa2.PrivateKey);
    	Console.ReadKey();
    }
    /// <summary>
    /// pkcs1 rsa 加密
    /// </summary>
    /// <param name="size">秘钥长度,一般为1024的倍数</param>
    /// <param name="pemFormat">是否转换成大小</param>
    /// <returns></returns>
    public static RSAKeyParameter Pkcs1(int size, bool pemFormat = false)
    {
    	var keyGenerator = GeneratorUtilities.GetKeyPairGenerator("RSA");
    	keyGenerator.Init(new KeyGenerationParameters(new SecureRandom(), size));
    	var keyPair = keyGenerator.GenerateKeyPair();
    	var subjectPublicKeyInfo=SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
    	var privateKeyInfo= PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
    	if (!pemFormat)
    	{
    		return new RSAKeyParameter
    		{
    			PrivateKey = Base64.ToBase64String(privateKeyInfo.ParsePrivateKey().GetEncoded()),
    			PublicKey = Base64.ToBase64String(subjectPublicKeyInfo.GetEncoded())
    		};
    	}
    	var rsaKey = new RSAKeyParameter();
    	using (var sw=new StringWriter())
    	{
    		var pWrt = new PemWriter(sw);
    		pWrt.WriteObject(keyPair.Private);
    		pWrt.Writer.Close();
    		rsaKey.PrivateKey = sw.ToString();
    	}
    	using (var sw = new StringWriter())
    	{
    		var pWrt = new PemWriter(sw);
    		pWrt.WriteObject(keyPair.Public);
    		pWrt.Writer.Close();
    		rsaKey.PublicKey = sw.ToString();
    	}
    	return rsaKey;
    }
    

    结果:

    最后说明,其实从秘钥中可以获取公钥,所以说其实我们保护的其实是私钥。

  • 相关阅读:
    lucene4 Filter
    lucene Query
    MyEclipse 中各种 libraries 的含义
    CRF++使用小结
    链表的输入与输出

    数据结构队列的各种操作
    设置背景颜色
    JavaScript由单价、数量计算总价
    中文和拼音自动转换的输入框
  • 原文地址:https://www.cnblogs.com/aoximin/p/13476401.html
Copyright © 2020-2023  润新知