using System;
using System.Text;
using System.Security.Cryptography;
using System.Xml;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
using Com.Bocom.OpenApi.Security.Crypt;
using Com.Bocom.OpenApi.Utils;

namespace Com.Bocom.OpenApi
{
    namespace Security
    {
        namespace Sign
        {
            public class RSASignature
            {
                //private static infosecapiLib.infosec icbcCA = new infosecapiLib.infosec();

                public static string Sign(string content, string privateKey, string charset)
                {
                    return Sign(content, privateKey, charset, null);
                }

                public static string Sign(string content, string privateKey, string charset, string password)
                {
                    return RSACryptor.RSAFromPkcs8.SignWithRSASHA256(content, privateKey, charset);
                }

                public static bool Verify(string content, string publicKey, string charset, string sign)
                {
                    try
                    {
                        byte[] contentBytes = Encoding.GetEncoding(charset).GetBytes(content);
                        return RSACryptor.RSAFromPkcs8.VerifySHA256(content, sign, publicKey, charset);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(
                            "get content charset exception. content: " + content + " charset: " + charset,
                            e);
                    }
                }

                public static string RSAPrivateKeyJava2DotNet(string privateKey)
                {
                    RsaPrivateCrtKeyParameters privateKeyParam =
                        (RsaPrivateCrtKeyParameters) PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
                    return string.Format(
                        "<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
                        Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
                        Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
                        Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
                        Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
                        Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
                        Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
                        Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
                        Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
                }

                /// <summary> 
                /// RSA私钥格式转换，.net->java 
                /// </summary> 
                /// <param name="privateKey">.net生成的私钥</param> 
                /// <returns></returns> 
                public static string RSAPrivateKeyDotNet2Java(string privateKey)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(privateKey);
                    BigInteger m = new BigInteger(1,
                        Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
                    BigInteger exp = new BigInteger(1,
                        Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
                    BigInteger d = new BigInteger(1,
                        Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
                    BigInteger p = new BigInteger(1,
                        Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
                    BigInteger q = new BigInteger(1,
                        Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
                    BigInteger dp = new BigInteger(1,
                        Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
                    BigInteger dq = new BigInteger(1,
                        Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
                    BigInteger qinv = new BigInteger(1,
                        Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));
                    RsaPrivateCrtKeyParameters privateKeyParam =
                        new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);
                    PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
                    byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
                    return Convert.ToBase64String(serializedPrivateBytes);
                }

                /// <summary> 
                /// RSA公钥格式转换，.net->java 
                /// </summary> 
                /// <param name="publicKey">.net生成的公钥</param> 
                /// <returns></returns> 
                public static string RSAPublicKeyDotNet2Java(string publicKey)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(publicKey);
                    BigInteger m = new BigInteger(1,
                        Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
                    BigInteger p = new BigInteger(1,
                        Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
                    RsaKeyParameters pub = new RsaKeyParameters(false, m, p);
                    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
                    byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
                    return Convert.ToBase64String(serializedPublicBytes);
                }

                //AES内容解密
                public static string DecryptContent(string content, string encryptType, string encryptKey,
                    string charset)
                {
                    if (encryptType.Equals(BocomConstants.ENCRYPT_TYPE_RSA_AND_AES))
                        return AesDecrypt(content, encryptKey);
                    else
                        throw new Exception("当前不支持该算法类型：encrypeType=" + encryptType);
                }

                //AES内容加密
                public static string EncryptContent(string content, string encryptType, string encryptKey,
                    string charset)
                {
                    if (encryptType.Equals(BocomConstants.ENCRYPT_TYPE_RSA_AND_AES))
                        return AesEncrypt(content, encryptKey);
                    throw new Exception("当前不支持该算法类型：encrypeType=" + encryptType);
                }


                /// <summary>
                ///AES加密（加密步骤）
                ///1，加密字符串得到2进制数组；
                ///2，将2禁止数组转为16进制；
                ///3，进行base64编码
                /// </summary>
                /// <param name="toEncrypt">要加密的字符串</param>
                /// <param name="key">密钥</param>
                public static string AesEncrypt(string toEncrypt, string key)
                {
                    Byte[] _Key = Convert.FromBase64String(key);
                    Byte[] _Source = Encoding.UTF8.GetBytes(toEncrypt);
                    Aes aes = Aes.Create("AES");
                    aes.Mode = CipherMode.CBC;
                    aes.Padding = PaddingMode.PKCS7;
                    aes.Key = _Key;
                    aes.IV = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
                    ICryptoTransform cTransform = aes.CreateEncryptor();
                    Byte[] cryptData = cTransform.TransformFinalBlock(_Source, 0, _Source.Length);
                    string CryptString = Convert.ToBase64String(cryptData);
                    return CryptString;
                }

                /// <summary>
                /// AES解密（解密步骤）
                /// 1，将BASE64字符串转为16进制数组
                /// 2，将16进制数组转为字符串
                /// 3，将字符串转为2进制数据
                /// 4，用AES解密数据
                /// </summary>
                /// <param name="encryptedSource">已加密的内容</param>
                /// <param name="key">密钥</param>
                public static string AesDecrypt(string encryptedSource, string key)
                {
                    Byte[] _Key = Convert.FromBase64String(key);
                    Aes aes = Aes.Create("AES");
                    aes.Mode = CipherMode.CBC;
                    aes.Padding = PaddingMode.PKCS7;
                    aes.Key = _Key;
                    aes.IV = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
                    ICryptoTransform cTransform = aes.CreateDecryptor();
                    Byte[] encryptedData = Convert.FromBase64String(encryptedSource);
                    Byte[] originalSourceData = cTransform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
                    string originalString = Encoding.UTF8.GetString(originalSourceData);
                    return originalString;
                }
            }
        }
    }
}