C#实现RSA加解密,验证同Cryptopp561的一致性成功

 /*
     * 功能:C#实现RSA加解密,验证同Cryptopp561的一致性(成功)
     *       研究目的:异构软件之间,如何保证数据在网络上的安全通讯。
     * 作者:李军
     * 时间:2012-07
     * 说明:警告,仅使用本代码段是无法保证数据通讯安全的,请参考相关资料!
     */
    class RSACryption
    {
        private System.Security.Cryptography.RSACryptoServiceProvider m_rsa = new RSACryptoServiceProvider();

        private String Byte2Str(Byte[] arrayB)
        {
            StringBuilder sb = new StringBuilder();
            String s2;

            foreach (Byte b in arrayB)
            {
                s2 = b.ToString("X");
                if (s2.Length == 1)
                    sb.Append("0");

                sb.Append(s2);
            }
            return sb.ToString();
        } 

        //需要重构m_rsa才会产生新的PubKey和PriKey
        public String RSA_PubKey()
        {
            String pubKey = m_rsa.ToXmlString(false);
    
            return pubKey;
        }

        //把公钥拆分为Modulus,Exponent两部份分别传给Crypotpp561库,用于明文加密
        //WinXPSP3+VS2008SP1环境下,C++程序中测试通过!
        public void RSA_PubKey(out String strModulus,out String strExponent)
        {
            RSAParameters rp = m_rsa.ExportParameters(false);

            strModulus = Convert.ToBase64String(rp.Modulus);
            strExponent = Convert.ToBase64String(rp.Exponent);
        }

        public String RSA_PriKey()
        {
            return m_rsa.ToXmlString(true);
        }

        //RSA 方式加密 
        //KEY必须是XML的行式的字符串,明文有 长度 限制。
        public string RSAEncrypt(String xmlPublicKey, String plainText)
        {

            byte[] PlainTextBArray;
            byte[] CypherTextBArray;
            string Result;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xmlPublicKey);
            PlainTextBArray = System.Text.UTF8Encoding.UTF8.GetBytes(plainText);
            CypherTextBArray = rsa.Encrypt(PlainTextBArray, true);
            Result = Convert.ToBase64String(CypherTextBArray);
            return Result;
        }

        public string RSADecrypt(String xmlPrivateKey, String cipherText)
        {
            byte[] PlainTextBArray;
            byte[] DypherTextBArray;
            string Result;
            System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xmlPrivateKey);
            PlainTextBArray = Convert.FromBase64String(cipherText);
            DypherTextBArray = rsa.Decrypt(PlainTextBArray, true);
            Result = System.Text.UTF8Encoding.UTF8.GetString(DypherTextBArray);
            return Result;
        }
    }


你可能感兴趣的:(加密,String,解密,C#,byte,通讯)