Example #1
0
        /// <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));
        }
Example #2
0
        public void FillOutAndSign(String keystore, String src, String name, String fname, String value, String dest)
        {
            Pkcs12Store store = new Pkcs12Store(new FileStream(keystore, FileMode.Open), PASSWORD);
            String      alias = "";
            ICollection <X509Certificate> chain = new List <X509Certificate>();

            // searching for private key
            foreach (string al in store.Aliases)
            {
                if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }
            AsymmetricKeyEntry pk = store.GetKey(alias);

            foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
            {
                chain.Add(c.Certificate);
            }
            RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;

            PdfReader  reader  = new PdfReader(src);
            FileStream os      = new FileStream(dest, FileMode.Create);
            PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true);
            AcroFields form    = stamper.AcroFields;

            form.SetField(fname, value);
            form.SetFieldProperty(name, "setfflags", PdfFormField.FF_READ_ONLY, null);
            form.SetFieldProperty(fname, "setfflags", PdfFormField.FF_READ_ONLY, null);
            // Creating the appearance
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;

            appearance.SetVisibleSignature(name);
            // Creating the signature
            PrivateKeySignature pks = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256);

            MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);
        }
        public IBigInteger ProcessBlock(
            IBigInteger input)
        {
            if (key is RsaPrivateCrtKeyParameters)
            {
                //
                // we have the extra factors, use the Chinese Remainder Theorem - the author
                // wishes to express his thanks to Dirk Bonekaemper at rtsffm.com for
                // advice regarding the expression of this.
                //
                RsaPrivateCrtKeyParameters crtKey = (RsaPrivateCrtKeyParameters)key;

                IBigInteger p    = crtKey.P;;
                IBigInteger q    = crtKey.Q;
                IBigInteger dP   = crtKey.DP;
                IBigInteger dQ   = crtKey.DQ;
                IBigInteger qInv = crtKey.QInv;

                IBigInteger mP, mQ, h, m;

                // mP = ((input Mod p) ^ dP)) Mod p
                mP = (input.Remainder(p)).ModPow(dP, p);

                // mQ = ((input Mod q) ^ dQ)) Mod q
                mQ = (input.Remainder(q)).ModPow(dQ, q);

                // h = qInv * (mP - mQ) Mod p
                h = mP.Subtract(mQ);
                h = h.Multiply(qInv);
                h = h.Mod(p);                               // Mod (in Java) returns the positive residual

                // m = h * q + mQ
                m = h.Multiply(q);
                m = m.Add(mQ);

                return(m);
            }

            return(input.ModPow(key.Exponent, key.Modulus));
        }
        /// <summary>Reads the private key.</summary>
        /// <returns>The private key from key pair.</returns>
        private RsaKeyParameters ReadKey()
        {
            AsymmetricCipherKeyPair keyPair;

            using (StreamReader reader = File.OpenText(FileUtils.ExpandUserHome(pemFilePath)))
            {
                try
                {
                    // PemReader uses password only if the private is password encrypted.
                    // If password is passed for a plain private key, it would be ignored.
                    object pemReader = new PemReader(reader, this.passPhrase == null ? null : new PasswordFinder(this.passPhrase)).ReadObject();
                    if (pemReader is AsymmetricCipherKeyPair)
                    {
                        keyPair = (AsymmetricCipherKeyPair)pemReader;
                        return(key = (RsaKeyParameters)keyPair.Private);
                    }
                    else if (pemReader is AsymmetricKeyParameter)
                    {
                        RsaPrivateCrtKeyParameters rsaPrivateCrtKeyParameters = (RsaPrivateCrtKeyParameters)pemReader;
                        return(key = new RsaKeyParameters(rsaPrivateCrtKeyParameters.IsPrivate, rsaPrivateCrtKeyParameters.Modulus, rsaPrivateCrtKeyParameters.Exponent));
                    }
                    else
                    {
                        throw new FormatException("The given key does not have the expected type");
                    }
                }
                catch (InvalidCipherTextException e)
                {
                    throw new ArgumentException("Incorrect passphrase for private key", e);
                }
                catch (PasswordException e)
                {
                    throw new ArgumentException("Private key is encrypted with a pass phrase. Please provide passphrase in the config", e);
                }
                catch (InvalidKeyException e)
                {
                    throw new ArgumentException("Invalid Key has been provided", e);
                }
            }
        }
Example #5
0
        public RSAStreamDecoder(Stream source, Stream p12, string storePass, string keyPass, bool isBase64)
        {
            Pkcs12Store pkcs12Store = new Pkcs12StoreBuilder().Build();

            pkcs12Store.Load(p12, storePass.ToCharArray());
            string alias = null;

            foreach (string alias3 in pkcs12Store.Aliases)
            {
                if (pkcs12Store.IsKeyEntry(alias3))
                {
                    alias = alias3;
                    break;
                }
            }
            if (isBase64)
            {
                StreamReader streamReader = new StreamReader(source);
                b = new MemoryStream();
                Base64.Decode(streamReader.ReadToEnd(), b);
                b.Position = 0L;
            }
            else
            {
                b = source;
            }
            c = pkcs12Store.GetCertificate(alias);
            d = pkcs12Store.GetKey(alias);
            foreach (string alias4 in pkcs12Store.Aliases)
            {
                if (pkcs12Store.IsKeyEntry(alias4))
                {
                    AsymmetricKeyEntry key = pkcs12Store.GetKey(alias4);
                    if (key.Key.IsPrivate)
                    {
                        e = (key.Key as RsaPrivateCrtKeyParameters);
                    }
                }
            }
        }
Example #6
0
        public void TestCreateKeyStore()
        {
            AsymmetricCipherKeyPair    keyPair    = KeyStoreUtil.GenerateKeyPair();
            RsaPrivateCrtKeyParameters RSAprivKey = (RsaPrivateCrtKeyParameters)keyPair.Private;
            RsaKeyParameters           RSApubKey  = (RsaKeyParameters)keyPair.Public;

            Org.BouncyCastle.X509.X509Certificate cert = KeyStoreUtil.CreateCert("Test", RSApubKey, RSAprivKey);
            Console.WriteLine(cert.ToString());

            string pfxPath = TEST_PFX_PATH;

            if (File.Exists(pfxPath))
            {
                pfxPath += "_old";
                if (File.Exists(pfxPath))
                {
                    File.Delete(pfxPath);
                }
            }
            FileStream fs = new FileStream(pfxPath, FileMode.CreateNew);

            KeyStoreUtil.WritePkcs12(RSAprivKey, cert, TEST_PFX_PASSWORD, fs);
            fs.Close();

            string crtPath = TEST_CRT_PATH;

            if (File.Exists(crtPath))
            {
                crtPath += "_old";
                if (File.Exists(crtPath))
                {
                    File.Delete(crtPath);
                }
            }
            FileStream certFileStream = new FileStream(crtPath, FileMode.CreateNew);

            byte[] encodedCert = cert.GetEncoded();
            certFileStream.Write(encodedCert, 0, encodedCert.Length);
            certFileStream.Close();
        }
        public bool GenerarLLavesSoftware(string subject, string challenge, string fileName)
        {
            try
            {
                RsaKeyPairGenerator r = new RsaKeyPairGenerator();
                var param             = new RsaKeyGenerationParameters(new BigInteger("10001", 16), new SecureRandom(), 1024, 80);
                r.Init(param);
                AsymmetricCipherKeyPair k = r.GenerateKeyPair();
                var privada = PrivateKeyInfoFactory.CreatePrivateKeyInfo(k.Private);
                SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(k.Public);
                string priv = Convert.ToBase64String(privada.GetDerEncoded());
                string pub  = Convert.ToBase64String(pubInfo.GetDerEncoded());
                File.WriteAllText("Privada.pem", priv);
                File.WriteAllText("Publica.pem", pub);
                RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(priv));
                RsaKeyParameters           publicKey  = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(pub));

                DerSet derset = null;
                if (challenge != null)
                {
                    ChallengePassword chpass = new ChallengePassword(challenge);
                    derset = new DerSet(chpass);
                }
                else
                {
                    derset = new DerSet();
                }

                X509Name sub = new X509Name(subject, new ConverterSidetec());
                Pkcs10CertificationRequest ds = new Pkcs10CertificationRequest("SHA1WITHRSA", sub, publicKey, derset, privateKey);

                File.WriteAllBytes(fileName, ds.GetDerEncoded());
                return(true);
            }
            catch (Exception ee)
            {
                Log.Error(ee.Message);
                return(false);
            }
        }
Example #8
0
        /// <summary>
        /// Base64 RSA private key string -> xml private key
        /// </summary>
        /// <param name="privateKey">normal RSA private key</param>
        /// <returns>RSA private key has format of xml</returns>
        public static string ToXmlPrivateKey(string privateKey)
        {
            RsaPrivateCrtKeyParameters privateKeyParams =
                PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey)) as RsaPrivateCrtKeyParameters;

            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                RSAParameters rsaParams = new RSAParameters()
                {
                    Modulus  = privateKeyParams.Modulus.ToByteArrayUnsigned(),
                    Exponent = privateKeyParams.PublicExponent.ToByteArrayUnsigned(),
                    D        = privateKeyParams.Exponent.ToByteArrayUnsigned(),
                    DP       = privateKeyParams.DP.ToByteArrayUnsigned(),
                    DQ       = privateKeyParams.DQ.ToByteArrayUnsigned(),
                    P        = privateKeyParams.P.ToByteArrayUnsigned(),
                    Q        = privateKeyParams.Q.ToByteArrayUnsigned(),
                    InverseQ = privateKeyParams.QInv.ToByteArrayUnsigned()
                };
                rsa.ImportParameters(rsaParams);
                return(rsa.ToXmlString(true));
            }
        }
 /// <summary>
 /// RSA私钥格式转换 java->.net
 /// </summary>
 /// <param name="strPrivateKey">Java生成的RSA私钥</param>
 /// <returns>C#使用的私钥</returns>
 public static string ConvertRSAPrivateKey_Java2DotNet(string strPrivateJavaRSAKey)
 {
     try
     {
         RsaPrivateCrtKeyParameters privateKeyParam =
             (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(strPrivateJavaRSAKey));
         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())));
     }
     catch (Exception e)
     {
         Console.WriteLine($"[Error] Convert RSA private key (Java to DotNet) failed. Error = {e.ToString()}");
         return(string.Empty);
     }
 }
Example #10
0
        /// <summary>
        /// 把pem私钥转xml格式
        /// </summary>
        /// <param name="privateKey">直接从private pem文件中读取的字符串</param>
        /// <returns></returns>
        public static string ConvertPemToXmlPrivateKey(string privateKey)
        {
            object pemObject = null;

            using (StringReader sReader = new StringReader(privateKey))
            {
                var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sReader);
                pemObject = pemReader.ReadObject();
            }
            RsaPrivateCrtKeyParameters key = (RsaPrivateCrtKeyParameters)((AsymmetricCipherKeyPair)pemObject).Private;
            string xmlPrivateKey           = 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(key.Modulus.ToByteArrayUnsigned()),
                                                           Convert.ToBase64String(key.PublicExponent.ToByteArrayUnsigned()),
                                                           Convert.ToBase64String(key.P.ToByteArrayUnsigned()),
                                                           Convert.ToBase64String(key.Q.ToByteArrayUnsigned()),
                                                           Convert.ToBase64String(key.DP.ToByteArrayUnsigned()),
                                                           Convert.ToBase64String(key.DQ.ToByteArrayUnsigned()),
                                                           Convert.ToBase64String(key.QInv.ToByteArrayUnsigned()),
                                                           Convert.ToBase64String(key.Exponent.ToByteArrayUnsigned()));

            return(xmlPrivateKey);
        }
Example #11
0
        private byte[] get_plain_session_key(byte[] cipherTextBytes)
        {
            RsaPrivateCrtKeyParameters keys = settings.get_private_key();


            // Pure mathematical RSA implementation
            // RsaEngine eng = new RsaEngine();

            // PKCS1 v1.5 paddings
            // Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine());

            // PKCS1 OAEP paddings
            OaepEncoding eng = new OaepEncoding(new RsaEngine());

            eng.Init(false, keys);

            int length    = cipherTextBytes.Length;
            int blockSize = eng.GetInputBlockSize();

            byte[] decipheredBytes = eng.ProcessBlock(cipherTextBytes, 0, length);
            return(decipheredBytes);
        }
Example #12
0
        public IHttpActionResult Decrypt([FromBody] Cryptographymodel item)
        {
            try
            {
                RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(item.PrivateKey));
                RSACryptoServiceProvider   rsa        = new RSACryptoServiceProvider();

                RSAParameters rsaParameters2 = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)privateKey);

                rsa.ImportParameters(rsaParameters2);

                byte[] dec    = rsa.Decrypt(Convert.FromBase64String(item.Chipertext), false);
                string decStr = Encoding.UTF8.GetString(dec);


                return(Ok(decStr));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
        private byte[] ConvertToPfx(X509Certificate2 x509, RsaPrivateCrtKeyParameters rsaParams, string pfxPassword)
        {
            var             store            = new Pkcs12Store();
            SecureRandom    random           = randomService.GenerateRandom();
            X509Certificate cert             = DotNetUtilities.FromX509Certificate(x509);
            string          friendlyName     = cert.SubjectDN.ToString();
            var             certificateEntry = new X509CertificateEntry(cert);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName,
                              new AsymmetricKeyEntry(rsaParams),
                              new[]
            {
                certificateEntry
            });

            using (var stream = new MemoryStream())
            {
                store.Save(stream, pfxPassword.ToCharArray(), random);
                return(stream.ToArray());
            }
        }
Example #14
0
        public static RSACryptoServiceProvider ConvertAsymmetricKeyParameterToRSACryptoServiceProvider(AsymmetricKeyParameter key)
        {
            RSAParameters rsaParameters = new RSAParameters();

            if (!key.IsPrivate)
            {
                RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)key;
                rsaParameters.Modulus  = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
                rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
            }
            else
            {
                RsaPrivateCrtKeyParameters keyParams = (RsaPrivateCrtKeyParameters)key;
                rsaParameters = DotNetUtilities.ToRSAParameters(keyParams);
                CspParameters            cspParameters = new CspParameters();
                RSACryptoServiceProvider rsaKey        = new RSACryptoServiceProvider(cspParameters);
            }
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(rsaParameters);
            return(rsa);
        }
        public static AsymmetricCipherKeyPair GetRsaKeyPair(RSAParameters rp)
        {
            BigInteger modulus = new BigInteger(1, rp.Modulus);
            BigInteger pubExp  = new BigInteger(1, rp.Exponent);

            RsaKeyParameters pubKey = new RsaKeyParameters(
                false,
                modulus,
                pubExp);

            RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(
                modulus,
                pubExp,
                new BigInteger(1, rp.D),
                new BigInteger(1, rp.P),
                new BigInteger(1, rp.Q),
                new BigInteger(1, rp.DP),
                new BigInteger(1, rp.DQ),
                new BigInteger(1, rp.InverseQ));

            return(new AsymmetricCipherKeyPair(pubKey, privKey));
        }
Example #16
0
        public static string CreateToken(Dictionary <string, object> payload, string privateRsaKeyPath)
        {
            RSAParameters rsaParams;

            using (var tr = new StreamReader(privateRsaKeyPath))
            {
                var pemReader = new PemReader(tr);

                RsaPrivateCrtKeyParameters privkey = null;
                Object obj = pemReader.ReadObject();
                if (obj != null)
                {
                    privkey = (RsaPrivateCrtKeyParameters)obj;
                }
                rsaParams = DotNetUtilities.ToRSAParameters(privkey);
            }
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(rsaParams);
                return(Jose.JWT.Encode(payload, rsa, Jose.JwsAlgorithm.RS512));
            }
        }
Example #17
0
        /// <summary>
        /// C#格式秘钥转成BouncyCastle格式秘钥
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static RsaKeyParameters RSAPrivateKeyDotNetTransfer(string privateKey)
        {
            /*加载私钥xml字符串*/
            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 pri = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);

            return(pri);
        }
Example #18
0
            internal override void Evaluate(RsaBlindedEngine rsaEngine)
            {
                RsaKeyParameters pubParameters  = new RsaKeyParameters(false, mod, pubExp);
                RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters(mod, pubExp, privExp, p, q, pExp, qExp, crtCoef);

                byte[] data = edgeInput;

                rsaEngine.Init(true, new ParametersWithRandom(pubParameters, Utils.testRandom));

                try
                {
                    data = rsaEngine.ProcessBlock(data, 0, data.Length);
                }
                catch (Exception e)
                {
                    Fail("Self test failed: exception " + e.Message);
                }

                if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.RsaStartupRawEnc], data))
                {
                    Fail("Self test failed: input does not match decrypted output");
                }

                rsaEngine.Init(false, new ParametersWithRandom(privParameters, Utils.testRandom));

                try
                {
                    data = rsaEngine.ProcessBlock(data, 0, data.Length);
                }
                catch (Exception e)
                {
                    Fail("Self test failed: exception " + e.Message);
                }

                if (!Arrays.AreEqual(FipsKats.Values[FipsKats.Vec.RsaStartupRawDec], data))
                {
                    Fail("Self test failed: input does not match decrypted output");
                }
            }
Example #19
0
    /// <summary>

    /// RSA私钥格式转换,java->.net

    /// </summary>

    /// <param name="privateKey">java生成的RSA私钥</param>

    /// <returns></returns>

    public static string RSAPrivateKeyJava2DotNet(this 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())));
    }
Example #20
0
            /// <summary>
            /// C#xml密钥转base64密钥
            /// </summary>
            /// <param name="RSAKey"></param>
            /// <param name="isPrivateKey"></param>
            /// <returns></returns>
            public static string ConvertXmlKeyToPem(string xmlKey, bool isPrivateKey)
            {
                if (string.IsNullOrEmpty(xmlKey))
                {
                    return(null);
                }

                string pemKey = string.Empty;
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                rsa.FromXmlString(xmlKey);
                RSAParameters    rsaPara = new RSAParameters();
                RsaKeyParameters key     = null;

                if (isPrivateKey)
                {
                    rsaPara = rsa.ExportParameters(true);
                    key     = new RsaPrivateCrtKeyParameters(
                        new BigInteger(1, rsaPara.Modulus), new BigInteger(1, rsaPara.Exponent), new BigInteger(1, rsaPara.D),
                        new BigInteger(1, rsaPara.P), new BigInteger(1, rsaPara.Q), new BigInteger(1, rsaPara.DP), new BigInteger(1, rsaPara.DQ),
                        new BigInteger(1, rsaPara.InverseQ));
                }
                else
                {
                    rsaPara = rsa.ExportParameters(false);
                    key     = new RsaKeyParameters(false,
                                                   new BigInteger(1, rsaPara.Modulus),
                                                   new BigInteger(1, rsaPara.Exponent));
                }

                using (TextWriter sw = new StringWriter())
                {
                    var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw);
                    pemWriter.WriteObject(key);
                    pemWriter.Writer.Flush();
                    pemKey = sw.ToString();
                }
                return(pemKey);
            }
Example #21
0
        /// <summary>
        /// Convert RSA Private Key from PKCS8 to PKCS1 format
        /// </summary>
        /// <param name="privateKey">Private Key</param>
        /// <returns></returns>
        public static string PrivateKeyPkcs8ToPkcs1(string privateKey)
        {
            privateKey = RsaPemFormatHelper.Pkcs8PrivateKeyFormat(privateKey);

            PemReader pr = new PemReader(new StringReader(privateKey));

            RsaPrivateCrtKeyParameters kp = pr.ReadObject() as RsaPrivateCrtKeyParameters;

            AsymmetricKeyParameter keyParameter = PrivateKeyFactory.CreateKey(PrivateKeyInfoFactory.CreatePrivateKeyInfo(kp));

            StringWriter sw = new StringWriter();

            PemWriter pWrt = new PemWriter(sw);

            pWrt.WriteObject(keyParameter);

            pWrt.Writer.Close();

            string result = sw.ToString();

            return(result);
        }
Example #22
0
        public virtual byte[] ProcessBlock(byte[] inBuf, int inOff, int inLen)
        {
            //IL_000d: Unknown result type (might be due to invalid IL or missing references)
            //IL_00cb: Unknown result type (might be due to invalid IL or missing references)
            if (key == null)
            {
                throw new InvalidOperationException("RSA engine not initialised");
            }
            BigInteger bigInteger = core.ConvertInput(inBuf, inOff, inLen);
            BigInteger bigInteger4;

            if (key is RsaPrivateCrtKeyParameters)
            {
                RsaPrivateCrtKeyParameters rsaPrivateCrtKeyParameters = (RsaPrivateCrtKeyParameters)key;
                BigInteger publicExponent = rsaPrivateCrtKeyParameters.PublicExponent;
                if (publicExponent != null)
                {
                    BigInteger modulus     = rsaPrivateCrtKeyParameters.Modulus;
                    BigInteger bigInteger2 = BigIntegers.CreateRandomInRange(BigInteger.One, modulus.Subtract(BigInteger.One), random);
                    BigInteger input       = bigInteger2.ModPow(publicExponent, modulus).Multiply(bigInteger).Mod(modulus);
                    BigInteger bigInteger3 = core.ProcessBlock(input);
                    BigInteger val         = bigInteger2.ModInverse(modulus);
                    bigInteger4 = bigInteger3.Multiply(val).Mod(modulus);
                    if (!bigInteger.Equals(bigInteger4.ModPow(publicExponent, modulus)))
                    {
                        throw new InvalidOperationException("RSA engine faulty decryption/signing detected");
                    }
                }
                else
                {
                    bigInteger4 = core.ProcessBlock(bigInteger);
                }
            }
            else
            {
                bigInteger4 = core.ProcessBlock(bigInteger);
            }
            return(core.ConvertOutput(bigInteger4));
        }
Example #23
0
        /// <summary>
        /// Save certificate as pfx file with private key
        /// </summary>
        /// <param name="issuerKeyPair"></param>
        /// <param name="x509"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private X509Certificate2 SaveToPFX(AsymmetricCipherKeyPair issuerKeyPair, X509Certificate2 x509, string fileName)
        {
            // add private key to x509
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(issuerKeyPair.Private);
            var            seq  = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());

            // It should thow if seq.c**t != 9 because folowing info should be stored in RSA key.
            // following page has more info: https://tls.mbed.org/kb/cryptography/asn1-key-structures-in-der-and-pem
            // version           Version,
            // modulus INTEGER,  --n
            // publicExponent INTEGER,  --e
            // privateExponent INTEGER,  --d
            // prime1 INTEGER,  --p
            // prime2 INTEGER,  --q
            // exponent1 INTEGER,  --d mod(p - 1)
            // exponent2 INTEGER,  --d mod(q - 1)
            // coefficient INTEGER,  --(inverse of q) mod p
            // otherPrimeInfos OtherPrimeInfos OPTIONAL
            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);


            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            var utils = new GeneralUtils();

            if (!fileName.EndsWith(".pfx"))
            {
                fileName += ".pfx";
            }
            File.WriteAllBytes(utils.PathWithName(fileName), x509.Export(X509ContentType.Pkcs12, GetCertPassword()));
            return(x509);
        }
        public string GenerateToken(string uid, IEnumerable <Claim> claims)
        {
            // Get the RsaPrivateCrtKeyParameters if we haven't already determined them
            if (_rsaParams == null)
            {
                lock (_rsaParamsLocker)
                {
                    if (_rsaParams == null)
                    {
                        using (var streamWriter = WriteToStreamWithString(_firebasePrivateKey.Replace(@"\n", "\n")))
                        {
                            using (var sr = new StreamReader(streamWriter.BaseStream))
                            {
                                var pr = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                                _rsaParams = (RsaPrivateCrtKeyParameters)pr.ReadObject();
                            }
                        }
                    }
                }
            }

            var payload = new Dictionary <string, object> {
                { "uid", uid }
                , { "iat", SecondsSinceEpoch(DateTime.UtcNow) }
                , { "exp", SecondsSinceEpoch(DateTime.UtcNow.AddSeconds(FirebaseTokenExpirySecs)) }
                , { "aud", FirebasePayloadAud }
                , { "iss", _firebasePayloadIss }
                , { "sub", _firebasePayloadSub }
            };

            if (claims != null && claims.Any())
            {
                var customClaims = claims.ToDictionary((x) => x.Type, (y) => (object)y.Value);
                payload.Add("claims", customClaims);
            }

            return(JWT.Encode(payload, Org.BouncyCastle.Security.DotNetUtilities.ToRSA(_rsaParams), JwsAlgorithm.RS256));
        }
Example #25
0
        public IActionResult Index(string docid)
        {
            var id   = _userManager.GetUserId(User);
            var user = _aadeDbIntegration.GetUser(id);
            var doc  = _messageDbIntegration.GetMessage(docid);

            if (doc == null)
            {
                Response.StatusCode = 400;
                return(Content("Document was not found"));
            }

            // Grab the AADE user's private key for the decryption of the symmetric key
            // that was used to encrypt the document
            RsaPrivateCrtKeyParameters privateKeyRecovered = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(user.PrivateKey));
            IAsymmetricBlockCipher     engine = new RsaEngine();

            engine.Init(false, privateKeyRecovered);

            // the message is saved as a byte array so convert back to Document object
            var message = Document.Deserialize(doc.Message);

            // recover symmetric key
            var derivedKeyBytesToReceive = engine.ProcessBlock(message.EncryptedSymmetricKey, 0, message.EncryptedSymmetricKeyLength);

            // use this now to Decrypt the message
            var decryptedDocument = AesOperation.DecryptString(Document.ByteArrayToString(derivedKeyBytesToReceive), message.EncryptedDocument);

            var decryptedDocumentAsBytes = Convert.FromBase64String(decryptedDocument);

            // verify signature to ensure message was not tampered with
            //var isvalid = VerifySignature(decryptedDocument, doc.UsersPublicKey, doc.Signature);

            doc.Status = 1;
            _messageDbIntegration.UpdateMessage(doc);

            return(File(decryptedDocumentAsBytes, doc.ContentType, doc.FileName));
        }
Example #26
0
        public static string GetSign(string jsonContent, RsaPrivateCrtKeyParameters pr)
        {
            // MD5计算
            string SignMD5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(jsonContent, "MD5").ToUpper();

            // SHA1计算
            string SignSHA1 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(SignMD5, "SHA1");

            // Rsa计算
            //Org.BouncyCastle.Math.BigInteger mod = new Org.BouncyCastle.Math.BigInteger(sMod, 16);
            //Org.BouncyCastle.Math.BigInteger pubExp = new Org.BouncyCastle.Math.BigInteger(sPubExp, 16);
            //Org.BouncyCastle.Math.BigInteger privExp = new Org.BouncyCastle.Math.BigInteger(sPrivExp, 16);
            //Org.BouncyCastle.Math.BigInteger p = new Org.BouncyCastle.Math.BigInteger(sP, 16);
            //Org.BouncyCastle.Math.BigInteger q = new Org.BouncyCastle.Math.BigInteger(sQ, 16);
            //Org.BouncyCastle.Math.BigInteger pExp = new Org.BouncyCastle.Math.BigInteger(sPExp, 16);
            //Org.BouncyCastle.Math.BigInteger qExp = new Org.BouncyCastle.Math.BigInteger(sQExp, 16);
            //Org.BouncyCastle.Math.BigInteger crtCoef = new Org.BouncyCastle.Math.BigInteger(sCrtCoef, 16);

            //RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp);
            //RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters(mod, pubExp, privExp, p, q, pExp, qExp, crtCoef);

            RsaKeyParameters pubParameters  = new RsaKeyParameters(false, pr.Modulus, pr.PublicExponent);
            RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters(pr.Modulus, pr.PublicExponent, pr.Exponent, pr.P, pr.Q, pr.DP, pr.DQ, pr.QInv);

            byte[] digInfo = System.Text.Encoding.Default.GetBytes(SignSHA1);

            ISigner rawSig = SignerUtilities.GetSigner("RSA");

            rawSig.Init(true, privParameters);
            rawSig.BlockUpdate(digInfo, 0, digInfo.Length);
            // Sign签名
            byte[] rawResult = rawSig.GenerateSignature();

            // 十六进制计算
            string SignRSA = byteToHexStr(rawResult).ToUpper();

            return(SignRSA);
        }
Example #27
0
        /// <summary>
        /// Private Key Convert xml->Pkcs8
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string PrivateKeyXmlToPkcs8(string privateKey)
        {
            XElement root = XElement.Parse(privateKey);
            //Modulus
            var modulus = root.Element("Modulus");
            //Exponent
            var exponent = root.Element("Exponent");
            //P
            var p = root.Element("P");
            //Q
            var q = root.Element("Q");
            //DP
            var dp = root.Element("DP");
            //DQ
            var dq = root.Element("DQ");
            //InverseQ
            var inverseQ = root.Element("InverseQ");
            //D
            var d = root.Element("D");

            RsaPrivateCrtKeyParameters rsaPrivateCrtKeyParameters = new RsaPrivateCrtKeyParameters(
                new BigInteger(1, Convert.FromBase64String(modulus.Value)),
                new BigInteger(1, Convert.FromBase64String(exponent.Value)),
                new BigInteger(1, Convert.FromBase64String(d.Value)),
                new BigInteger(1, Convert.FromBase64String(p.Value)),
                new BigInteger(1, Convert.FromBase64String(q.Value)),
                new BigInteger(1, Convert.FromBase64String(dp.Value)),
                new BigInteger(1, Convert.FromBase64String(dq.Value)),
                new BigInteger(1, Convert.FromBase64String(inverseQ.Value)));

            StringWriter   swpri   = new StringWriter();
            PemWriter      pWrtpri = new PemWriter(swpri);
            Pkcs8Generator pkcs8   = new Pkcs8Generator(rsaPrivateCrtKeyParameters);

            pWrtpri.WriteObject(pkcs8);
            pWrtpri.Writer.Close();
            return(swpri.ToString());
        }
Example #28
0
        public virtual byte[] ProcessBlock(byte[] inBuf, int inOff, int inLen)
        {
            BigInteger integer2;

            if (this.key == null)
            {
                throw new InvalidOperationException("RSA engine not initialised");
            }
            BigInteger val = this.core.ConvertInput(inBuf, inOff, inLen);

            if (this.key is RsaPrivateCrtKeyParameters)
            {
                RsaPrivateCrtKeyParameters key = (RsaPrivateCrtKeyParameters)this.key;
                BigInteger publicExponent      = key.PublicExponent;
                if (publicExponent != null)
                {
                    BigInteger modulus  = key.Modulus;
                    BigInteger integer5 = BigIntegers.CreateRandomInRange(BigInteger.One, modulus.Subtract(BigInteger.One), this.random);
                    BigInteger input    = integer5.ModPow(publicExponent, modulus).Multiply(val).Mod(modulus);
                    BigInteger integer7 = this.core.ProcessBlock(input);
                    BigInteger integer8 = integer5.ModInverse(modulus);
                    integer2 = integer7.Multiply(integer8).Mod(modulus);
                    if (!val.Equals(integer2.ModPow(publicExponent, modulus)))
                    {
                        throw new InvalidOperationException("RSA engine faulty decryption/signing detected");
                    }
                }
                else
                {
                    integer2 = this.core.ProcessBlock(val);
                }
            }
            else
            {
                integer2 = this.core.ProcessBlock(val);
            }
            return(this.core.ConvertOutput(integer2));
        }
        public AsymmetricCipherKeyPair ComposeKeyPair(BigInteger p, BigInteger q, BigInteger publicExponent)
        {
            if (p.Max(q).Equals(q))
            {
                var tmp = p;
                p = q;
                q = tmp;
            }

            var modulus = p.Multiply(q);

            var p1              = p.Subtract(BigInteger.One);
            var q1              = q.Subtract(BigInteger.One);
            var phi             = p1.Multiply(q1);
            var privateExponent = publicExponent.ModInverse(phi);
            var dP              = privateExponent.Remainder(p1);
            var dQ              = privateExponent.Remainder(q1);
            var qInv            = q.ModInverse(p);

            var priv = new RsaPrivateCrtKeyParameters(modulus, publicExponent, privateExponent, p, q, dP, dQ, qInv);

            return(new AsymmetricCipherKeyPair(new RsaKeyParameters(false, priv.Modulus, publicExponent), priv));
        }
Example #30
0
        /// <summary>
        /// 获取私钥
        /// </summary>
        /// <param name="cert"></param>
        /// <returns></returns>
        public static string GetPrivateKeyPem(X509Certificate2 cert)
        {
            try
            {
                var p   = cert.GetRSAPrivateKey().ExportParameters(true);
                var key = new RsaPrivateCrtKeyParameters(
                    new Org.BouncyCastle.Math.BigInteger(1, p.Modulus), new Org.BouncyCastle.Math.BigInteger(1, p.Exponent), new Org.BouncyCastle.Math.BigInteger(1, p.D),
                    new Org.BouncyCastle.Math.BigInteger(1, p.P), new Org.BouncyCastle.Math.BigInteger(1, p.Q), new Org.BouncyCastle.Math.BigInteger(1, p.DP), new Org.BouncyCastle.Math.BigInteger(1, p.DQ),
                    new Org.BouncyCastle.Math.BigInteger(1, p.InverseQ));


                using (var stringWriter = new StringWriter())
                {
                    var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(stringWriter);
                    pemWriter.WriteObject(key);
                    return(stringWriter.GetStringBuilder().ToString());
                }
            }
            catch
            {
                throw new Exception("cert必须具有 X509KeyStorageFlags.Exportable 标识,才能导出私钥。");
            }
        }