Ejemplo n.º 1
0
        public static (string, string) CreateCSR(string DN)
        {
            RSA rSA = new RSACryptoServiceProvider(2048);


            string keygen = CertificateUtils.PemEncodeKey(Convert.ToBase64String(rSA.ExportRSAPrivateKey()));

            var    res  = FileHandler.CheckAndCreatePath("CSRs", "CSR");
            string path = res.Item1;
            string idx  = res.Item2;

            File.WriteAllText(path + $"\\SLjavad_{idx}.key", keygen);

            CertificateRequest certificateRequest = new CertificateRequest(
                $"{DN}", rSA, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

            certificateRequest.CertificateExtensions.Add(
                new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyCertSign, false));

            certificateRequest.CertificateExtensions.Add(
                new X509SubjectKeyIdentifierExtension(certificateRequest.PublicKey, false));

            certificateRequest.CertificateExtensions.Add(
                new X509BasicConstraintsExtension(true, false, 0, true));


            var csr = certificateRequest.CreateSigningRequest();

            File.WriteAllText(path + $"\\SLjavad_{idx}.csr", CertificateUtils.PemEncodeSigningRequest(Convert.ToBase64String(csr)));
            return(CertificateUtils.PemEncodeSigningRequest(Convert.ToBase64String(csr)), (path + $"\\SLjavad_{idx}.csr"));
        }
Ejemplo n.º 2
0
        public IActionResult OnPostConvertPEM(string xmldata)
        {
            XMLData = xmldata;

            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();

            try
            {
                provider.FromXmlString(xmldata);

                byte[] ber = null;
                if (provider.PublicOnly)
                {
                    ber     = provider.ExportSubjectPublicKeyInfo();
                    PEMData = MakePem(ber, "PUBLIC KEY");
                }
                else
                {
                    ber     = provider.ExportPkcs8PrivateKey();
                    PEMData = MakePem(ber, "PRIVATE KEY");

                    var berRSA = provider.ExportRSAPrivateKey();
                    RSAData = MakePem(berRSA, "RSA PRIVATE KEY");
                }
            }
            catch (Exception ex) {
                ErrorJS = "<script>toastr.error('" + ex.Message.Replace("'", "¡¦") + "')</script>";
            }

            return(Page());
        }
Ejemplo n.º 3
0
        public Merchant(string name, string email, List <string> currencies, string commandId = null)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException($"invalid {nameof(name)}");
            }

            if (!email.IsValidEmail())
            {
                throw new ArgumentException($"invalid email: {email}");
            }

            Name  = name;
            Email = email;
            // Keysize can be adjusted based on requirements
            using var rsa = new RSACryptoServiceProvider(512);
            PublicKey     = $"pk_{Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo()).ToLower()}";
            PrivateKey    = $"sk_{Convert.ToBase64String(rsa.ExportRSAPrivateKey()).ToLower()}";

            if (currencies.Any(currency => currency.Length != 3))
            {
                throw new ArgumentException($"{nameof(currencies)} invalid");
            }

            _supportedCurrencies.AddRange(currencies.ConvertAll(x => x.ToUpper()));

            RaiseDomainEvent(new MerchantAddedDomainEvent(Id, name, email, currencies, PublicKey, PrivateKey, commandId));
        }
Ejemplo n.º 4
0
        public static byte[] RsaDecrypt(RSACryptoServiceProvider PrivateKey, byte[] Cyphertext)
        {
            Console.WriteLine(Convert.ToBase64String(PrivateKey.ExportRSAPrivateKey()));
            int            segmentLength   = 256;
            int            offset          = 0;
            int            decryptedLength = 0;
            Queue <byte[]> segments        = new Queue <byte[]>();

            while (offset < Cyphertext.Length)
            {
                byte[] segment = new byte[256];
                Array.Copy(Cyphertext, offset, segment, 0, segment.Length);
                offset += segmentLength;

                segment          = PrivateKey.Decrypt(segment, false);
                decryptedLength += segment.Length;

                segments.Enqueue(segment);
            }

            byte[] plaintext = new byte[decryptedLength];
            offset = 0;
            while (segments.Count > 0)
            {
                byte[] segment = segments.Dequeue();
                Array.Copy(segment, 0, plaintext, offset, segment.Length);
                offset += segment.Length;
            }

            return(plaintext);
        }
Ejemplo n.º 5
0
        private string SignToken(string payload, string name)
        {
            List <string> pjeset = new List <string>();

            var header = new { alg = "RS256", typ = "JWT" };

            byte[] headerB  = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Formatting.None));
            byte[] payloadB = Encoding.UTF8.GetBytes(payload);

            pjeset.Add(Base64UrlEncode(headerB));
            pjeset.Add(Base64UrlEncode(payloadB));

            string str = string.Join(".", pjeset.ToArray());

            byte[]       bytesToSign = Encoding.UTF8.GetBytes(str);
            string       path        = "C://keys//" + name + ".xml";
            StreamReader reader      = new StreamReader(path);
            string       parametrat  = reader.ReadToEnd();

            objRSA.FromXmlString(parametrat);
            byte[] key = objRSA.ExportRSAPrivateKey();

            var privat  = Asn1Object.FromByteArray(key);
            var privatS = RsaPrivateKeyStructure.GetInstance((Asn1Sequence)privat);

            ISigner nenshkrimi = SignerUtilities.GetSigner("SHA256withRSA");

            nenshkrimi.Init(true, new RsaKeyParameters(true, privatS.Modulus, privatS.PrivateExponent));

            nenshkrimi.BlockUpdate(bytesToSign, 0, bytesToSign.Length);
            byte[] gensignature = nenshkrimi.GenerateSignature();

            pjeset.Add(Base64UrlEncode(gensignature));
            return(string.Join(".", pjeset.ToArray()));
        }
Ejemplo n.º 6
0
        public void ImportPrivateKeyTest()
        {
            var rsa = new RSACryptoServiceProvider();

            rsa.ImportPrivateKey(privatekeypem);
            var key = Convert.ToBase64String(rsa.ExportRSAPrivateKey());

            Assert.AreEqual(key, privatekey);
        }
Ejemplo n.º 7
0
        public RsaKeys GenerateKeys()
        {
            using (var rsa = new RSACryptoServiceProvider(2048))
            {
                rsa.PersistKeyInCsp = false;

                var publicKey  = rsa.ExportRSAPublicKey();
                var privateKey = rsa.ExportRSAPrivateKey();

                return(new RsaKeys(publicKey, privateKey));
            }
        }
Ejemplo n.º 8
0
 public static void GenerateRSAKey()
 {
     using (var rsa = new RSACryptoServiceProvider(2048))
     {
         try
         {
             var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".hologram");
             Directory.CreateDirectory(path);
             File.WriteAllBytes(path + "/spacebridge.key", rsa.ExportRSAPrivateKey());
             File.WriteAllBytes(path + "/spacebridge.key.pub", rsa.ExportRSAPublicKey());
         }
         finally
         {
             rsa.PersistKeyInCsp = false;
         }
     }
 }
        public override Task <KeyPair> GenerateKey(HandshakeMethod method)
        {
            var _rsa       = new RSACryptoServiceProvider();
            var rsaKeyInfo = _rsa.ExportParameters(true);

            return(Task.FromResult(new KeyPair()
            {
                Public = new PublicKey()
                {
                    Value = Convert.ToBase64String(_rsa.ExportSubjectPublicKeyInfo()),
                    Format = Format,
                    Type = Type,
                },
                Private = new PrivateKey()
                {
                    Value = Convert.ToBase64String(_rsa.ExportRSAPrivateKey()),
                    Format = Format,
                    Type = Type,
                },
            }));
        }
Ejemplo n.º 10
0
        public static void Run()
        {
            var importedKey = PEM.Read(@"resources\example.org.key", "RSA PRIVATE KEY");

            Console.WriteLine("Imported key length: {0}", importedKey.Length);

            using var rsa = new RSACryptoServiceProvider();
            rsa.ImportRSAPrivateKey(importedKey, out _);

            var parameters       = rsa.ExportParameters(true);
            var parametersLength = parameters.D.Length +
                                   parameters.DP.Length +
                                   parameters.DQ.Length +
                                   parameters.Exponent.Length +
                                   parameters.InverseQ.Length +
                                   parameters.Modulus.Length +
                                   parameters.P.Length +
                                   parameters.Q.Length;

            Console.WriteLine();
            Console.WriteLine("Parameters length: {0}", parametersLength);
            Console.WriteLine("Modulus: {0} ({1})", parameters.Modulus.Length, importedKey.IndexOf(parameters.Modulus));
            Console.WriteLine("Exponent: {0} ({1})", parameters.Exponent.Length, importedKey.IndexOf(parameters.Exponent));
            Console.WriteLine("D: {0} ({1})", parameters.D.Length, importedKey.IndexOf(parameters.D));
            Console.WriteLine("P: {0} ({1})", parameters.P.Length, importedKey.IndexOf(parameters.P));
            Console.WriteLine("Q: {0} ({1})", parameters.Q.Length, importedKey.IndexOf(parameters.Q));
            Console.WriteLine("DP: {0} ({1})", parameters.DP.Length, importedKey.IndexOf(parameters.DP));
            Console.WriteLine("DQ: {0} ({1})", parameters.DQ.Length, importedKey.IndexOf(parameters.DQ));
            Console.WriteLine("InverseQ: {0} ({1})", parameters.InverseQ.Length, importedKey.IndexOf(parameters.InverseQ));

            var exportedKey = rsa.ExportRSAPrivateKey();

            Console.WriteLine();
            Console.WriteLine("Exported key length: {0}", exportedKey.Length);
            Console.WriteLine("Matches exported key: {0}", importedKey.IndexOf(exportedKey) == 0);
        }
Ejemplo n.º 11
0
 /// <summary>Regenerate the asymmetric service's keys and return the pair in hex string format.</summary>
 /// <returns>Hex string variant of <c>KeyPair</c></returns>
 public KeyPair GetKeys()
 {
     return(new KeyPair(BitConverter.ToString(rsa.ExportRSAPublicKey()), BitConverter.ToString(rsa.ExportRSAPrivateKey())));
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Base64 encoded private key, use this to restore the key later
 /// </summary>
 public string ToRsaPrivateKey()
 {
     return(Convert.ToBase64String(_rsa.ExportRSAPrivateKey()));
 }