using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
//using System.Security.Cryptography.Cng;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace ASHermed.SinoInterface.Tools
{

    /// <summary>
    /// RSA操作类
    /// </summary>
    public class RSAHelper
    {
        public static void RsaTest()
        {
            try
            {
                //Create a UnicodeEncoder to convert between byte array and string.
                UnicodeEncoding ByteConverter = new UnicodeEncoding();


                //Create byte arrays to hold original, encrypted, and decrypted data.
                byte[] dataToEncrypt = ByteConverter.GetBytes("Data to Encrypt");
                byte[] encryptedData;
                byte[] decryptedData;


                X509Certificate2 pubcrt = new X509Certificate2("D:\\public-rsa.cer");
                RSACryptoServiceProvider pubkey = (RSACryptoServiceProvider)pubcrt.PublicKey.Key;
                X509Certificate2 prvcrt = new X509Certificate2("D:\\user-rsa.pfx", "sino2556", X509KeyStorageFlags.Exportable);
                RSACryptoServiceProvider prvkey = (RSACryptoServiceProvider)prvcrt.PrivateKey;

                encryptedData = RSAEncrypt(dataToEncrypt, pubkey.ExportParameters(false), false);
                Console.WriteLine("Encrypted plaintext: {0}", Convert.ToBase64String(encryptedData));



                decryptedData = RSADecrypt(encryptedData, prvkey.ExportParameters(true), false);


                Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData));


                //加密长内容
                String data = @"RSA 是常用的非对称加密算法。最近使用时却出现了“不正确的长度”的异常，研究发现是由于待加密的数据超长所致。
　　                    .NET Framework 中提供的 RSA 算法规定：
　　                    待加密的字节数不能超过密钥的长度值除以 8 再减去 11（即：RSACryptoServiceProvider.KeySize / 8 - 11），而加密后得到密文的字节数，正好是密钥的长度值除以 8（即：RSACryptoServiceProvider.KeySize / 8）。
　　                    所以，如果要加密较长的数据，则可以采用分段加解密的方式，实现方式如下：";
                string encrypt = Encrypt(data, pubcrt);
                Console.WriteLine("Encrypted plaintext: {0}", encrypt);
                string decrypt = Decrypt(encrypt, prvcrt);
                Console.WriteLine("Decrypted plaintext: {0}", decrypt);

                prvkey.Clear();
                pubkey.Clear();
                Console.Read();
            }
            catch (ArgumentNullException)
            {
                //Catch this exception in case the encryption did
                //not succeed.
                Console.WriteLine("Encryption failed.");


            }
        }


        static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                byte[] encryptedData;
                //Create a new instance of RSACryptoServiceProvider.
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {


                    //Import the RSA Key information. This only needs
                    //toinclude the public key information.
                    RSA.ImportParameters(RSAKeyInfo);


                    //Encrypt the passed byte array and specify OAEP padding.  
                    //OAEP padding is only available on Microsoft Windows XP or
                    //later.  
                    encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
                }
                return encryptedData;
            }
            //Catch and display a CryptographicException  
            //to the console.
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);


                return null;
            }


        }


        static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                byte[] decryptedData;
                //Create a new instance of RSACryptoServiceProvider.
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    //Import the RSA Key information. This needs
                    //to include the private key information.
                    RSA.ImportParameters(RSAKeyInfo);


                    //Decrypt the passed byte array and specify OAEP padding.  
                    //OAEP padding is only available on Microsoft Windows XP or
                    //later.  
                    decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
                }
                return decryptedData;
            }
            //Catch and display a CryptographicException  
            //to the console.
            catch (CryptographicException e)
            {
                Console.WriteLine(e.ToString());


                return null;
            }


        }


        public static String Encrypt(String plaintext, X509Certificate2 pubcrt)
        {
            X509Certificate2 _X509Certificate2 = pubcrt;
            using (RSACryptoServiceProvider RSACryptography = _X509Certificate2.PublicKey.Key as RSACryptoServiceProvider)
            {
                Byte[] PlaintextData = Encoding.UTF8.GetBytes(plaintext);
                int MaxBlockSize = RSACryptography.KeySize / 8 - 11;    //加密块最大长度限制


                if (PlaintextData.Length <= MaxBlockSize)
                    return Convert.ToBase64String(RSACryptography.Encrypt(PlaintextData, false));


                using (MemoryStream PlaiStream = new MemoryStream(PlaintextData))
                using (MemoryStream CrypStream = new MemoryStream())
                {
                    Byte[] Buffer = new Byte[MaxBlockSize];
                    int BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize);


                    while (BlockSize > 0)
                    {
                        Byte[] ToEncrypt = new Byte[BlockSize];
                        Array.Copy(Buffer, 0, ToEncrypt, 0, BlockSize);


                        Byte[] Cryptograph = RSACryptography.Encrypt(ToEncrypt, false);
                        CrypStream.Write(Cryptograph, 0, Cryptograph.Length);


                        BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize);
                    }


                    return Convert.ToBase64String(CrypStream.ToArray(), Base64FormattingOptions.None);
                }
            }
        }


        public static String Decrypt(String ciphertext, X509Certificate2 prvpfx)
        {
            X509Certificate2 _X509Certificate2 = prvpfx;
            using (RSACryptoServiceProvider RSACryptography = _X509Certificate2.PrivateKey as RSACryptoServiceProvider)
            {
                Byte[] CiphertextData = Convert.FromBase64String(ciphertext);
                int MaxBlockSize = RSACryptography.KeySize / 8;    //解密块最大长度限制


                if (CiphertextData.Length <= MaxBlockSize)
                    return Encoding.UTF8.GetString(RSACryptography.Decrypt(CiphertextData, false));


                using (MemoryStream CrypStream = new MemoryStream(CiphertextData))
                using (MemoryStream PlaiStream = new MemoryStream())
                {
                    Byte[] Buffer = new Byte[MaxBlockSize];
                    int BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize);


                    while (BlockSize > 0)
                    {
                        Byte[] ToDecrypt = new Byte[BlockSize];
                        Array.Copy(Buffer, 0, ToDecrypt, 0, BlockSize);


                        Byte[] Plaintext = RSACryptography.Decrypt(ToDecrypt, false);
                        PlaiStream.Write(Plaintext, 0, Plaintext.Length);


                        BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize);
                    }


                    return Encoding.UTF8.GetString(PlaiStream.ToArray());
                }
            }
        }


        private static X509Certificate2 RetrieveX509Certificate()
        {
            return null;    //检索用于 RSA 加密的 X509Certificate2 证书
        }
    

    ///// <summary>
    ///// 生成公私钥
    ///// </summary>
    ///// <param name="PrivateKeyPath"></param>
    ///// <param name="PublicKeyPath"></param>
    //public void RSAKey(string PrivateKeyPath, string PublicKeyPath)
    //{
    //    try
    //    {
    //        RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
    //        CreatePrivateKeyXML(PrivateKeyPath, provider.ToXmlString(true));
    //        CreatePublicKeyXML(PublicKeyPath, provider.ToXmlString(false));
    //    }
    //    catch (Exception exception)
    //    {
    //        throw exception;
    //    }
    //}

    ///// <summary>
    ///// 对原始数据进行MD5加密
    ///// </summary>
    ///// <param name="m_strSource">待加密数据</param>
    ///// <returns>返回机密后的数据</returns>
    //public string GetHash(string m_strSource)
    //{
    //    HashAlgorithm algorithm = HashAlgorithm.Create("MD5");
    //    byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
    //    byte[] inArray = algorithm.ComputeHash(bytes);
    //    return Convert.ToBase64String(inArray);
    //}

    ///// <summary>
    ///// RSA加密
    ///// </summary>
    ///// <param name="xmlPublicKey">公钥</param>
    ///// <param name="m_strEncryptString">MD5加密后的数据</param>
    ///// <returns>RSA公钥加密后的数据</returns>
    //public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
    //{
    //    string str2;
    //    try
    //    {
    //        RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
    //        provider.FromXmlString(xmlPublicKey);
    //        byte[] bytes = new UnicodeEncoding().GetBytes(m_strEncryptString);
    //        str2 = Convert.ToBase64String(provider.Encrypt(bytes, false));
    //    }
    //    catch (Exception exception)
    //    {
    //        throw exception;
    //    }
    //    return str2;
    //}

    ///// <summary>
    ///// RSA解密
    ///// </summary>
    ///// <param name="xmlPrivateKey">私钥</param>
    ///// <param name="m_strDecryptString">待解密的数据</param>
    ///// <returns>解密后的结果</returns>
    //public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)
    //{
    //    string str2;
    //    try
    //    {
    //        RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
    //        provider.FromXmlString(xmlPrivateKey);
    //        byte[] rgb = Convert.FromBase64String(m_strDecryptString);
    //        byte[] buffer2 = provider.Decrypt(rgb, false);
    //        str2 = new UnicodeEncoding().GetString(buffer2);
    //    }
    //    catch (Exception exception)
    //    {
    //        throw exception;
    //    }
    //    return str2;
    //}

    ///// <summary>
    ///// 对MD5加密后的密文进行签名
    ///// </summary>
    ///// <param name="p_strKeyPrivate">私钥</param>
    ///// <param name="m_strHashbyteSignature">MD5加密后的密文</param>
    ///// <returns></returns>
    //public string SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature)
    //{
    //    byte[] rgbHash = Convert.FromBase64String(m_strHashbyteSignature);
    //    RSACryptoServiceProvider key = new RSACryptoServiceProvider();
    //    key.FromXmlString(p_strKeyPrivate);
    //    RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
    //    formatter.SetHashAlgorithm("MD5");
    //    byte[] inArray = formatter.CreateSignature(rgbHash);
    //    return Convert.ToBase64String(inArray);
    //}

    ///// <summary>
    ///// 签名验证
    ///// </summary>
    ///// <param name="p_strKeyPublic">公钥</param>
    ///// <param name="p_strHashbyteDeformatter">待验证的用户名</param>
    ///// <param name="p_strDeformatterData">注册码</param>
    ///// <returns></returns>
    //public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData)
    //{
    //    try
    //    {
    //        byte[] rgbHash = Convert.FromBase64String(p_strHashbyteDeformatter);
    //        RSACryptoServiceProvider key = new RSACryptoServiceProvider();
    //        key.FromXmlString(p_strKeyPublic);
    //        RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key);
    //        deformatter.SetHashAlgorithm("MD5");
    //        byte[] rgbSignature = Convert.FromBase64String(p_strDeformatterData);
    //        if (deformatter.VerifySignature(rgbHash, rgbSignature))
    //        {
    //            return true;
    //        }
    //        return false;
    //    }
    //    catch
    //    {
    //        return false;
    //    }

    //}




    ///// <summary>
    ///// 获取一个与指定值不同的随机整数
    ///// </summary>
    ///// <param name="temp">指定值</param>
    ///// <returns>随机整数</returns>
    //private int GetRandomNum(int temp)
    //{
    //    Random ra = new Random();
    //    while (true)
    //    {
    //        int r = ra.Next(1, 100000);
    //        if (r == temp)
    //            continue;
    //        else
    //            return r;
    //    }
    //}



    ///// <summary>
    ///// 创建私钥文件
    ///// </summary>
    ///// <param name="path"></param>
    ///// <param name="privatekey"></param>
    //public void CreatePrivateKeyXML(string path, string privatekey)
    //{
    //    try
    //    {
    //        FileStream privatekeyxml = new FileStream(path, FileMode.Create);
    //        StreamWriter sw = new StreamWriter(privatekeyxml);
    //        sw.WriteLine(privatekey);
    //        sw.Close();
    //        privatekeyxml.Close();
    //    }
    //    catch
    //    {
    //        throw;
    //    }
    //}
    ///// <summary>
    ///// 创建公钥文件
    ///// </summary>
    ///// <param name="path"></param>
    ///// <param name="publickey"></param>
    //public void CreatePublicKeyXML(string path, string publickey)
    //{
    //    try
    //    {
    //        FileStream publickeyxml = new FileStream(path, FileMode.Create);
    //        StreamWriter sw = new StreamWriter(publickeyxml);
    //        sw.WriteLine(publickey);
    //        sw.Close();
    //        publickeyxml.Close();
    //    }
    //    catch
    //    {
    //        throw;
    //    }
    //}
    ///// <summary>
    ///// 读取公钥
    ///// </summary>
    ///// <param name="path"></param>
    ///// <returns></returns>
    //public string ReadPublicKey(string path)
    //{
    //    StreamReader reader = new StreamReader(path);
    //    string publickey = reader.ReadToEnd();
    //    reader.Close();
    //    return publickey;
    //}

    ///// <summary>
    ///// 读取私钥
    ///// </summary>
    ///// <param name="path"></param>
    ///// <returns></returns>
    //public string ReadPrivateKey(string path)
    //{
    //    StreamReader reader = new StreamReader(path);
    //    string privatekey = reader.ReadToEnd();
    //    reader.Close();
    //    return privatekey;
    //}
}
}

