Silverlight中非对称加密及数字签名RSA算法的实现

简介: RSA算法是第一个既能用于数据加密也能用于数字签名的算法。它易于理解和操作,也很流行。它的安全性是基于大整数素因子分解的困难性,而大整数因子分解问题是数学上的著名难题,至今没有有效的方法予以解决,因此可以确保RSA算法的安全性。

RSA算法是第一个既能用于数据加密也能用于数字签名的算法。它易于理解和操作,也很流行。它的安全性是基于大整数素因子分解的困难性,而大整数因子分解问题是数学上的著名难题,至今没有有效的方法予以解决,因此可以确保RSA算法的安全性。

    到目前Silverlight4 Beta发布为止,Silverlight中仍然没有提供非对称加密及数字签名相关的算法。而.NET Framework中提供的RSA等算法,都是通过操作系统提供的相关API实现的,没法移植到Silverlight中使用。因此很难实现一个健壮点的Silverlight纯客户端的注册验证算法。这几天抽空写了个Silverlight下可用的RSA算法,使用非对称加密和数字签名使Silverlight纯客户端的注册验证算法健壮了不少。关于这个Silverlight下可用的RSA算法的具体实现,记录在下面,欢迎大家拍砖。在进行Silverlight开发时,还可以借助一些开发工具。ComponentOne Studio for Silverlight 拥有50多个基于Microsoft Silverlight的控件,能够满足开发最流行Web界面的需要。

    RSA算法实现主要分为三部分:包括公钥和私钥的产生,非对称加密和解密,数字签名和验证,下面将逐个介绍RSA算法的工作原理及我的实现方法。

 

 

    1,公钥和私钥的产生

    随意选择两个大素数p、q,p不等于q,计算n = p * q。
    随机选择一个整数e,满足e和( p – 1 ) * ( q – 1 )互质。(注:e很容易选择,如3, 17, 65537等都可以。.NET Framework中e默认选择的就是65537)
利用Euclid算法计算解密密钥d,满足
      e * d ≡ 1 ( mod ( p - 1 ) * ( q - 1 ) )
    其中n和d也要互质。

    其中e和n就是公钥,d和n就是私钥。P、q销毁。

    在.NET Framework的RSA算法中,e对应RSAParameters.Exponent;d对应RSAParameters.D;n对应RSAParameters.ModulusExponent。.NET Framework中的RSA算法默认使用1024位长的密钥。公钥和私钥是利用.NET Framework的RSACryptoServiceProvider生成公钥xml文件和私钥xml文件来实现的。生成公钥和私钥xml文件的程序本身不是Silverlight程序。

 

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

    //生成公钥XML字符串
    string publicKeyXmlString = rsa.ToXmlString(false);

    //生成私钥XML字符串
    string privateKeyXmlString = rsa.ToXmlString(true);

 

 

公钥和私钥将从生成的公钥xml文件和私钥xml文件中导入。

public class RSAPublicKey
    {
        public byte[] Modulus;
        public byte[] Exponent;

        public static RSAPublicKey FromXmlString(string xmlString)
        {
            if (string.IsNullOrEmpty(xmlString))
            {
                return null;
            }

            try
            {
                using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
                {
                    if (!reader.ReadToFollowing("RSAKeyValue"))
                    {
                        return null;
                    }

                    if (reader.LocalName != "Modulus" && !reader.ReadToFollowing("Modulus"))
                    {
                        return null;
                    }
                    string modulus = reader.ReadElementContentAsString();

                    if (reader.LocalName != "Exponent" && !reader.ReadToFollowing("Exponent"))
                    {
                        return null;
                    }
                    string exponent = reader.ReadElementContentAsString();

                    RSAPublicKey publicKey = new RSAPublicKey();
                    publicKey.Modulus = Convert.FromBase64String(modulus);
                    publicKey.Exponent = Convert.FromBase64String(exponent);

                    return publicKey;
                }
            }
            catch
            {
                return null;
            }
        }        
    }

 

 

public class RSAPrivateKey
    {
        public byte[] Modulus;
        public byte[] D;

        public static RSAPrivateKey FromXmlString(string xmlString)
        {
            if (string.IsNullOrEmpty(xmlString))
            {
                return null;
            }

            try
            {
                using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
                {
                    if (!reader.ReadToFollowing("RSAKeyValue"))
                    {
                        return null;
                    }

                    if (reader.LocalName != "Modulus" && !reader.ReadToFollowing("Modulus"))
                    {
                        return null;
                    }
                    string modulus = reader.ReadElementContentAsString();

                    if (reader.LocalName != "D" && !reader.ReadToFollowing("D"))
                    {
                        return null;
                    }
                    string d = reader.ReadElementContentAsString();

                    RSAPrivateKey privateKey = new RSAPrivateKey();
                    privateKey.Modulus = Convert.FromBase64String(modulus);
                    privateKey.D = Convert.FromBase64String(d);

                    return privateKey;
                }
            }
            catch
            {
                return null;
            }
        }        
    }

 

 

2,非对称加密和解密
    私钥加密m(二进制表示)时,首先把m分成长s的数据块 m1, m2 ... mi,其中 2^s <= n, s 尽可能的大。执行如下计算:
        ci = mi ^ d (mod n)
    公钥解密c(二进制表示)时,也需要将c分成长s的数据块c1, c2 ... ci,执行如下计算:
        mi = ci ^ e (mod n)

    在某些情况下,也会使用公钥加密->私钥解密。原理和私钥加密->公钥解密一样。下面是私钥计算和公钥计算的算法。其中利用到了Chew Keong TAN的BigInteger类。.NET Framework 4中提供的BigInteger.ModPow方法好像有问题。 

 

 

private static byte[] Compute(byte[] data, RSAPublicKey publicKey, int blockSize)
        {
            //
            // 公钥加密/解密公式为:ci = mi^e ( mod n )            
            // 
            // 先将 m(二进制表示)分成数据块 m1, m2, ..., mi ,然后进行运算。
            //
            BigInteger e = new BigInteger(publicKey.Exponent);
            BigInteger n = new BigInteger(publicKey.Modulus);

            int blockOffset = 0;
            using (MemoryStream stream = new MemoryStream())
            {
                while (blockOffset < data.Length)
                {
                    int blockLen = Math.Min(blockSize, data.Length - blockOffset);
                    byte[] blockData = new byte[blockLen];
                    Buffer.BlockCopy(data, blockOffset, blockData, 0, blockLen);

                    BigInteger mi = new BigInteger(blockData);
                    BigInteger ci = mi.modPow(e, n);//ci = mi^e ( mod n )

                    byte[] block = ci.getBytes();
                    stream.Write(block, 0, block.Length);
                    blockOffset += blockLen;
                }

                return stream.ToArray();
            }
        }

        private static byte[] Compute(byte[] data, RSAPrivateKey privateKey, int blockSize)
        {
            //
            // 私钥加密/解密公式为:mi = ci^d ( mod n )
            // 
            // 先将 c(二进制表示)分成数据块 c1, c2, ..., ci ,然后进行运算。            
            //
            BigInteger d = new BigInteger(privateKey.D);
            BigInteger n = new BigInteger(privateKey.Modulus);

            int blockOffset = 0;

            using (MemoryStream stream = new MemoryStream())
            {
                while (blockOffset < data.Length)
                {
                    int blockLen = Math.Min(blockSize, data.Length - blockOffset);
                    byte[] blockData = new byte[blockLen];
                    Buffer.BlockCopy(data, blockOffset, blockData, 0, blockLen);

                    BigInteger ci = new BigInteger(blockData);
                    BigInteger mi = ci.modPow(d, n);//mi = ci^d ( mod n )

                    byte[] block = mi.getBytes();
                    stream.Write(block, 0, block.Length);
                    blockOffset += blockLen;
                }

                return stream.ToArray();
            }
        }

 

 

下面是私钥加密->公钥解密的实现。

 

public static byte[] Encrypt(byte[] data, RSAPublicKey publicKey)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (publicKey == null)
            {
                throw new ArgumentNullException("publicKey");
            }

            int blockSize = publicKey.Modulus.Length - 1;
            return Compute(data, publicKey, blockSize);
        }

        public static byte[] Decrypt(byte[] data, RSAPrivateKey privateKey)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (privateKey == null)
            {
                throw new ArgumentNullException("privateKey");
            }

            int blockSize = privateKey.Modulus.Length;
            return Compute(data, privateKey, blockSize);
        }

 

 

下面是公钥加密->私钥解密的实现。 

public static byte[] Encrypt(byte[] data, RSAPrivateKey privateKey)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (privateKey == null)
            {
                throw new ArgumentNullException("privateKey");
            }

            int blockSize = privateKey.Modulus.Length - 1;
            return Compute(data, privateKey, blockSize);
        }

        public static byte[] Decrypt(byte[] data, RSAPublicKey publicKey)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (publicKey == null)
            {
                throw new ArgumentNullException("publicKey");
            }

            int blockSize = publicKey.Modulus.Length;
            return Compute(data, publicKey, blockSize);
        }
 

3,数字签名和验证
    私钥签名数据m时,先对m进行hash计算,得到计算结果h。然后将h使用私钥加密,得到加密后的密文s即为签名。
    公钥验证签名s时,先将m进行hash计算,得到计算结果h。然后使用公钥解密s得到结果h’。如果h==h’即验证成功,否则验证失败。

    在某些情况下,也会使用公钥签名->私钥验证。原理和私钥签名->公钥验证一样。

    下面是私钥签名->公钥验证的实现。 

 

 public static byte[] Sign(byte[] data, RSAPublicKey publicKey, HashAlgorithm hash)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (publicKey == null)
            {
                throw new ArgumentNullException("publicKey");
            }

            if (hash == null)
            {
                throw new ArgumentNullException("hash");
            }

            byte[] hashData = hash.ComputeHash(data);
            byte[] signature = Encrypt(hashData, publicKey);
            return signature;
        }

        public static bool Verify(byte[] data, RSAPrivateKey privateKey, HashAlgorithm hash, byte[] signature)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (privateKey == null)
            {
                throw new ArgumentNullException("privateKey");
            }

            if (hash == null)
            {
                throw new ArgumentNullException("hash");
            }

            if (signature == null)
            {
                throw new ArgumentNullException("signature");
            }

            byte[] hashData = hash.ComputeHash(data);
            byte[] signatureHashData = Decrypt(signature, privateKey);

            if (signatureHashData != null && signatureHashData.Length == hashData.Length)
            {
                for (int i = 0; i < signatureHashData.Length; i++)
                {
                    if (signatureHashData[i] != hashData[i])
                    {
                        return false;
                    }
                }
                return true;
            }

            return false;
        }

 

 

下面是公钥签名->私钥验证的实现。

public static byte[] Sign(byte[] data, RSAPrivateKey privateKey, HashAlgorithm hash)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (privateKey == null)
            {
                throw new ArgumentNullException("privateKey");
            }

            if (hash == null)
            {
                throw new ArgumentNullException("hash");
            }

            byte[] hashData = hash.ComputeHash(data);
            byte[] signature = Encrypt(hashData, privateKey);
            return signature;
        }

        public static bool Verify(byte[] data, RSAPublicKey publicKey, HashAlgorithm hash, byte[] signature)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (publicKey == null)
            {
                throw new ArgumentNullException("publicKey");
            }

            if (hash == null)
            {
                throw new ArgumentNullException("hash");
            }

            if (signature == null)
            {
                throw new ArgumentNullException("signature");
            }

            byte[] hashData = hash.ComputeHash(data);

            byte[] signatureHashData = Decrypt(signature, publicKey);

            if (signatureHashData != null && signatureHashData.Length == hashData.Length)
            {
                for (int i = 0; i < signatureHashData.Length; i++)
                {
                    if (signatureHashData[i] != hashData[i])
                    {
                        return false;
                    }
                }
                return true;
            }

            return false;
        }


相关文章
|
6月前
|
存储 搜索推荐 算法
加密算法、排序算法、字符串处理及搜索算法详解
本文涵盖四大类核心技术知识。加密算法部分介绍了对称加密(如 AES)、非对称加密(如 RSA)、哈希摘要(如 SHA-2)、签名算法的特点及密码存储方案(加盐、BCrypt 等)。 排序算法部分分类讲解了比较排序(冒泡、选择、插入、归并、快排、堆排序)和非比较排序(计数、桶、基数排序)的时间复杂度、适用场景及实现思路,强调混合排序的工业应用。 字符串处理部分包括字符串反转的双指针法,及项目中用正则进行表单校验、网页爬取、日志处理的实例。 搜索算法部分详解了二分查找的实现(双指针与中间索引计算)和回溯算法的概念(递归 + 剪枝),以 N 皇后问题为例说明回溯应用。内容全面覆盖算法原理与实践
221 0
|
7月前
|
算法 数据安全/隐私保护
基于混沌加密的遥感图像加密算法matlab仿真
本项目实现了一种基于混沌加密的遥感图像加密算法MATLAB仿真(测试版本:MATLAB2022A)。通过Logistic映射与Baker映射生成混沌序列,对遥感图像进行加密和解密处理。程序分析了加解密后图像的直方图、像素相关性、信息熵及解密图像质量等指标。结果显示,加密图像具有良好的随机性和安全性,能有效保护遥感图像中的敏感信息。该算法适用于军事、环境监测等领域,具备加密速度快、密钥空间大、安全性高的特点。
|
安全 算法 网络安全
浅谈非对称加密(RSA)
浅谈非对称加密(RSA)
632 0
|
11月前
|
弹性计算 算法 Linux
使用SM4算法加密LUKS格式磁盘
本文介绍了在Anolis 8操作系统使用cryptsetup对磁盘进行分区、加密和挂载的过程。采用SM4加密算法。具体步骤包括:初始化加密卷、解锁加密分区、格式化并挂载设备。最后,展示了如何取消挂载并关闭加密卷以确保数据安全。整个过程确保了磁盘数据的安全性和隐私保护。
928 2
使用SM4算法加密LUKS格式磁盘
|
算法 安全 Go
Go 语言中实现 RSA 加解密、签名验证算法
随着互联网的发展,安全需求日益增长。非对称加密算法RSA成为密码学中的重要代表。本文介绍如何使用Go语言和[forgoer/openssl](https://github.com/forgoer/openssl)库简化RSA加解密操作,包括秘钥生成、加解密及签名验证。该库还支持AES、DES等常用算法,安装简便,代码示例清晰易懂。
351 12
|
算法 安全 Go
RSA加密算法详解与Python和Go实现
RSA加密算法详解与Python和Go实现
1604 1
|
算法 安全 网络安全
使用 Python 实现 RSA 加密
使用 Python 实现 RSA 加密
509 2
|
安全 算法 数据安全/隐私保护
黑客克星!Python加密艺术大公开,AES、RSA双剑合璧,守护你的数字世界
在这个数据泛滥的时代,数字世界既充满了知识,也潜藏安全隐患。Python 作为强大的编程语言,以其独特的加密技术为我们的信息安全保驾护航。本文将介绍 AES 和 RSA 这两种加密算法,揭示它们如何协同工作,保护你的数字世界。AES(高级加密标准)以其高效、安全著称,能将敏感信息转化为难以破解的乱码。Python 的 `pycryptodome` 库让 AES 加密变得简单易行。然而,AES 面临密钥分发难题,此时 RSA(非对称加密算法)便大显身手,通过公钥加密、私钥解密的方式确保密钥传输安全。AES 与 RSA 在 Python 中交织成一道坚不可摧的防护网,共同守护我们的数字世界。
384 0
|
11月前
|
云安全 安全 数据建模
《数字证书:互联网世界的"身份证"与"防盗门"》 ——揭秘网络安全背后的加密江湖
在2023年某深夜,上海陆家嘴金融公司机房遭遇黑客攻击,神秘青铜大门与九大掌门封印的玉牌突现,阻止了入侵。此门象征数字证书,保障网络安全。数字证书如验钞机识别假币,保护用户数据。它通过SSL/TLS加密、CA认证和非对称加密,构建安全通信。证书分为DV、OV、EV三类,分别适合不同场景。忽视证书安全可能导致巨额损失。阿里云提供一站式证书服务,助力企业部署SSL证书,迎接未来量子计算和物联网挑战。

热门文章

最新文章