Пример #1
0
 public CryptoBroker()
 {
     using var rsa = new RSACryptoServiceProvider(2048);
     PublicKey     = rsa.ExportRSAPublicKey();
     _privateKey   = rsa.ExportParameters(true);
     Contracted    = false;
 }
Пример #2
0
        public static string toBase64(RSACryptoServiceProvider publicKey)
        {
            Debug.Assert(publicKey != null, nameof(publicKey) + " != null");

            var encodedPublicKey = publicKey.ExportRSAPublicKey();

            return(Convert.ToBase64String(encodedPublicKey));
        }
Пример #3
0
        public void ImportPublicKeyTest()
        {
            var rsa = new RSACryptoServiceProvider();

            rsa.ImportPublicKey(publickeypem);
            var key = Convert.ToBase64String(rsa.ExportRSAPublicKey());

            Assert.AreEqual(key, publickey);
        }
Пример #4
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));
            }
        }
Пример #5
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;
         }
     }
 }
Пример #6
0
        static async Task Main(string[] args)
        {
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = delegate { return(true); }
            };

            using var authClient = new HttpClient(handler)
                  {
                      BaseAddress = new Uri("https://localhost:7001")
                  };

            var csParams = new CspParameters
            {
                KeyContainerName = "client_secret_container",
                Flags            = CspProviderFlags.UseDefaultKeyContainer,
            };

            using var rsa = new RSACryptoServiceProvider(2048, csParams)
                  {
                      PersistKeyInCsp = false
                  };
            var publicKey = rsa.ExportPublicKey();

            rsa.PersistKeyInCsp = false;
            var computeHash = MD5.Create().ComputeHash(rsa.ExportRSAPublicKey());
            var username    = Convert.ToBase64String(computeHash);

            Console.WriteLine($"username: {username}");
            string secret;

            if (File.Exists("secret.txt"))
            {
                secret = File.ReadAllText("secret.txt");
            }
            else
            {
                secret = Guid.NewGuid().ToString();
                File.WriteAllText("secret.txt", secret);
            }

            var user = new UserRegistration
            {
                ClientId = username,
                Secret   = secret,
                Name     = "Console app"
            };
            var content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
            var result  = await authClient.PostAsync("account/register", content);

            Console.WriteLine(result.StatusCode);
            Console.WriteLine(await result.Content.ReadAsStringAsync());
            if (result.StatusCode != HttpStatusCode.Created)
            {
                throw new Exception(await result.Content.ReadAsStringAsync());
            }

            var tokenContent = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("grant_type", "client_credentials"),
                new KeyValuePair <string, string>("client_id", username),
                new KeyValuePair <string, string>("client_secret", secret)
            });
            var login = await authClient.PostAsync("connect/token", tokenContent);

            var token = JsonConvert.DeserializeObject <JObject>(await login.Content.ReadAsStringAsync())
                        .SelectToken("access_token")
                        .Value <string>();

            using var resourceClient   = new HttpClient(handler);
            resourceClient.BaseAddress = new Uri("http://localhost:7002");

            var resourceResult = await resourceClient.GetAsync("/protected-resource");

            if (resourceResult.StatusCode != HttpStatusCode.Unauthorized)
            {
                throw new Exception("Request should be unauthorized");
            }

            resourceClient.DefaultRequestHeaders.Authorization
                           = new AuthenticationHeaderValue("Bearer", token);
            resourceResult = await resourceClient.GetAsync("/protected-resource");

            Console.WriteLine(await resourceResult.Content.ReadAsStringAsync());

            Console.ReadLine();
        }
Пример #7
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())));
 }
Пример #8
0
        private void assinarItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog           sfd    = new SaveFileDialog();
            RSACryptoServiceProvider encRSA = new RSACryptoServiceProvider();

            sfd.Filter = "SignedRSA|*.sign";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(Path.GetDirectoryName(sfd.FileName) + "\\texto-limpo.txt", textoBox.Text);
                File.WriteAllText(sfd.FileName, RSASign(textoBox.Text, encRSA));
                File.WriteAllText(Path.GetDirectoryName(sfd.FileName) + "\\PK.pem", Convert.ToBase64String(encRSA.ExportRSAPublicKey()));
            }
        }
Пример #9
0
 /// <summary>
 /// Gets the public key in bytes
 /// </summary>
 /// <returns>The public key in bytes</returns>
 public byte[] GetPublicKey()
 {
     return(rsa.ExportRSAPublicKey());
 }
Пример #10
0
 /// <summary>
 /// Base64 public key, could be used to generate a public .pem
 /// </summary>
 public string ToRsaPublicKey()
 {
     return(Convert.ToBase64String(_rsa.ExportRSAPublicKey()));
 }