using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;

namespace CSharDemoFQB
{
    public class EncryptHelper
    {
        //此为提供的测试密钥
        public static string privateKey_pkcs1 =
@"MIIEogIBAAKCAQEAnKM+ofeOdZYSh9Oq4badkJqQUAXiOM1KHWNxS6zOu24vWa/K
XoBw1vwcX2x7qvTx/THiAjyGugYx//KJjOXCDK8ORWj/f8PGm233+Q7hiYEVJuwy
So+6wK4xvYm4qMrcc9HdJ1SvpO+UHwRuKIEz2v5GveHIhu6PkJk9Jksevtm65WuM
+YuIcfeFEevOP7SPJduyHZNx+gHhkfmcgRZPYvAiASglLMqE4BRAIJ4z3TcRfQyx
x88LtGOqMrtE1bTQ4lOhknJGeNhy2x6SvOw/9Drn15omzDutGYCzVYpX+zRzFVAd
H/gmTqDgkGgL9Pf9MtkOzcdc4i2GfhMhEj1FtwIDAQABAoIBAHQo13TTmjD3Ruy1
et8CRx0KkoTVqCsJirH6ofVFxNXYY4L2S3QDeirkMcJON/PSzHZA/OM9sYfYulGd
soXriRlQ5Jtyvy8np2xyg9eOQpFvSZlgxfbnWc40ICz4Khn6vruhYYkeU1dUWBsc
dPjSv/riYOHFw6jU12CbU27HfJh4vhVTUSU1y/NI/5axL2YcU3/pb70towK5qBog
514FHhL/U1nyBxyxsjUtSZOVjk2oH7wOnANNVyQga8sR/0G8CanGbnhvCPXhu1e7
lYZW186jDOOrASIuJgNiJL6S0vonWL7FF2UD/kWmbiOgmouOkR00KTwN+KLFFrMh
obKbMsECgYEA9Kz7TRqsqpMTIWu85RmjF0oIXsJA/XfCT5TPwsfMvryBY3Sqjnzc
smDPiU1NFV7lo5EriJ+Hmio837vOQj1jHuv4hhkvKXMuLxEGgRDX+EkMZ7Nt3nkF
tk+GrJuNm+0DVlipu1hgIQMzvxoJZx0rRNPrFg8ypCgAJs4FPHdUASECgYEAo+Mm
9kGTitMgBZ4T86kswAE4DjrJ7HCcD6YROmbVoSWfN9xEsgFdHKxOo6MWiTA6FmnX
hWZyt83W9XhauQLW/qP9Rdxq/vN6e7NCo36pc5CDfgPHdeskQ7zCjgf+gb2JNwqm
cb1Afbgpk+FQkDRbhqHUQl7rQCBsgDkhf8Pe89cCgYBQUgDlHN6V2FYtYHrQEoxx
dsIsqURAcPH+wfE6FfDmpGctSP08bUzd2d4HSrMFUvO7sEpEPWp8d2UoZTSelhxV
6EzbaKUMzFza4pHqCKd9QC2sVUC6CayQXqbtPttL1pCD5fNCJw7Xh3+TOm7fxLmR
jKfdw/tx3BfApV0ermWLQQKBgCJMADRaxtivlCz4xu4gAkhwON3peaZsboxr0YEq
Uhy2NdrH0ux5kpXUjWR7VdUB7bYRElRNe0Zx4kFenYXITVvez7sWBKI0K/bFLfXv
JOEVZh8yBUTtH5q5XvHARIe8NYH6TZjR5TQqHTFgXq6+9kR3i2cUXCEAaBRxYExP
nlHjAoGATt+YPRY0cu+seY3p23F5iR0g28hucquF/6jE5aYsJhXD2OSZ5lSN1X0T
iE55/N5+TvIWW0KySctArTkgF7vTstQcgIrhfu6Jc2w39d3JnacQnCfkRkI0a91e
g5rCV6VRAfW05SQLIqr3dhJCGXX0U0mL3f3jGo5NN7du0rddFG0=";
        //此为测试密钥转换成的PKCS8版本
        public static string privateKey_pkcs8 =
@"MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCcoz6h9451lhKH
06rhtp2QmpBQBeI4zUodY3FLrM67bi9Zr8pegHDW/BxfbHuq9PH9MeICPIa6BjH/
8omM5cIMrw5FaP9/w8abbff5DuGJgRUm7DJKj7rArjG9ibioytxz0d0nVK+k75Qf
BG4ogTPa/ka94ciG7o+QmT0mSx6+2brla4z5i4hx94UR684/tI8l27Idk3H6AeGR
+ZyBFk9i8CIBKCUsyoTgFEAgnjPdNxF9DLHHzwu0Y6oyu0TVtNDiU6GSckZ42HLb
HpK87D/0OufXmibMO60ZgLNVilf7NHMVUB0f+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oFHFgTE+eUeMCgYBO35g9FjRy76x5jenbcXmJ
HSDbyG5yq4X/qMTlpiwmFcPY5JnmVI3VfROITnn83n5O8hZbQrJJy0CtOSAXu9Oy
1ByAiuF+7olzbDf13cmdpxCcJ+RGQjRr3V6DmsJXpVEB9bTlJAsiqvd2EkIZdfRT
SYvd/eMajk03t27St10UbQ==";

        public static string Signature(string str, string privateKey, string encoding, bool isDotNetKey = false)
        {
            //SHA256withRSA
            byte[] bt = Encoding.GetEncoding(encoding).GetBytes(str);
            var sha256 = new SHA256CryptoServiceProvider();
            byte[] rgbHash = sha256.ComputeHash(bt);

            string netKey;
            if (isDotNetKey)
                netKey = privateKey;
            else
                netKey = RSAPrivateKeyJava2DotNet(privateKey);

            RSACryptoServiceProvider key = new RSACryptoServiceProvider();
            key.FromXmlString(netKey);
            RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
            formatter.SetHashAlgorithm("SHA256");//此处是你需要加签的hash算法，需要和上边你计算的hash值的算法一致，不然会报错。
            byte[] inArray = formatter.CreateSignature(rgbHash);
            return Convert.ToBase64String(inArray);

        }

        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()));
        }

        public static string RSAPublicKeyJava2DotNet(string publikKey)
        {
            RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publikKey));
            return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
                Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
                Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
        }
    }
}
