Exemplo n.º 1
2
        private static RsaKeyPair GetRsaKeyPair(RSA rsa, string comment)
        {
            const string sshrsa = "ssh-rsa";

            // Use Bouncy castle's pem reader to get the modulus and exponent as a byte array
            PemReader reader = new PemReader(new StringReader(rsa.PublicKeyAsPEM));
            RsaKeyParameters r = (RsaKeyParameters)reader.ReadObject();

            byte[] sshrsa_bytes = Encoding.Default.GetBytes(sshrsa);
            byte[] n = r.Modulus.ToByteArray();
            byte[] e = r.Exponent.ToByteArray();

            Buffer buf = new Buffer(sshrsa_bytes.Length + 4 + e.Length + 4 + n.Length + 4);

            // Add the bytes
            buf.add(sshrsa_bytes, e, n);

            // Encode in Base64
            string buffer64 = buf.AsBase64String();

            // Set the base DTO
            RsaKeyPair pair = new RsaKeyPair()
            {
                PublicSSHKey = string.Format("ssh-rsa {0} {1}", buffer64, comment),
                PublicKeyAsPEM = rsa.PublicKeyAsPEM,
                PrivateKeyAsPEM = rsa.PrivateKeyAsPEM,
                // Later add parameters if required.
            };

            return pair;
        }
        private void importButton_Click(object sender, RoutedEventArgs e)
        {
            RsaKeyPair result = new RsaKeyPair()
            {
                PublicKey  = publicTextBox.Text,
                PrivateKey = privateTextBox.Text,
                Timestamp  = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds
            };

            bool error = false;

            if (Crypto.PublicKeyFromPem(result.PublicKey) == null)
            {
                Result = null;
                error  = true;
                errorTextBlock.Visibility = Visibility.Visible;
            }

            if (!result.PublicOnly && Crypto.PrivateKeyFromPem(result.PrivateKey) == null)
            {
                Result = null;
                error  = true;
                errorTextBlock.Visibility = Visibility.Visible;
            }

            if (!error)
            {
                Result = result;
                this.Close();
            }
        }
Exemplo n.º 3
0
        public void CreateKeyPair()
        {
            var pair = new RsaKeyPair();

            Assert.NotNull(pair.PublicKey);
            Assert.NotNull(pair.PrivateKey);
        }
        private static RsaKeyPair GetRsaKeyPair(RSA rsa, string comment)
        {
            const string sshrsa = "ssh-rsa";

            // Use Bouncy castle's pem reader to get the modulus and exponent as a byte array
            PemReader        reader = new PemReader(new StringReader(rsa.PublicKeyAsPEM));
            RsaKeyParameters r      = (RsaKeyParameters)reader.ReadObject();

            byte[] sshrsa_bytes = Encoding.Default.GetBytes(sshrsa);
            byte[] n            = r.Modulus.ToByteArray();
            byte[] e            = r.Exponent.ToByteArray();

            Buffer buf = new Buffer(sshrsa_bytes.Length + 4 + e.Length + 4 + n.Length + 4);

            // Add the bytes
            buf.add(sshrsa_bytes, e, n);

            // Encode in Base64
            string buffer64 = buf.AsBase64String();

            // Set the base DTO
            RsaKeyPair pair = new RsaKeyPair()
            {
                PublicSSHKey    = string.Format("ssh-rsa {0} {1}", buffer64, comment),
                PublicKeyAsPEM  = rsa.PublicKeyAsPEM,
                PrivateKeyAsPEM = rsa.PrivateKeyAsPEM,
                // Later add parameters if required.
            };

            return(pair);
        }
Exemplo n.º 5
0
        public static Certificate Deserialize(string data, RsaKeyPair key)
        {
            var result = new Certificate(key);

            result.AddChain(new CertificateChain(data));
            return(result);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Create a new private/public key pair as PEM formatted strings.
        /// </summary>
        /// <returns>An <see cref="RsaKeyPair"/>.</returns>
        public static RsaKeyPair GenerateRsaKeyPair()
        {
            var rsaGenerator = new RsaKeyPairGenerator();

            rsaGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            var keyPair = rsaGenerator.GenerateKeyPair();

            var rsaKeyPair = new RsaKeyPair();

            using (var privateKeyTextWriter = new StringWriter())
            {
                var pemWriter = new PemWriter(privateKeyTextWriter);
                pemWriter.WriteObject(keyPair.Private);
                pemWriter.Writer.Flush();

                rsaKeyPair.PrivateKey = privateKeyTextWriter.ToString();
            }

            using (var publicKeyTextWriter = new StringWriter())
            {
                var pemWriter = new PemWriter(publicKeyTextWriter);
                pemWriter.WriteObject(keyPair.Public);
                pemWriter.Writer.Flush();

                rsaKeyPair.PublicKey = publicKeyTextWriter.ToString();
            }

            return(rsaKeyPair);
        }
Exemplo n.º 7
0
        public static Csr GenerateCsr(CsrDetails csrDetails, RsaKeyPair rsaKeyPair, string messageDigest = "SHA256")
        {
            var rsaKeys = CryptoKey.FromPrivateKey(rsaKeyPair.Pem, null);

            // Translate from our external form to our OpenSSL internal form
            // Ref:  https://www.openssl.org/docs/manmaster/crypto/X509_NAME_new.html
            var xn = new X509Name();
            if (!string.IsNullOrEmpty(csrDetails.CommonName         /**/)) xn.Common = csrDetails.CommonName;       // CN;
            if (!string.IsNullOrEmpty(csrDetails.Country            /**/)) xn.Common = csrDetails.Country;          // C;
            if (!string.IsNullOrEmpty(csrDetails.StateOrProvince    /**/)) xn.Common = csrDetails.StateOrProvince;  // ST;
            if (!string.IsNullOrEmpty(csrDetails.Locality           /**/)) xn.Common = csrDetails.Locality;         // L;
            if (!string.IsNullOrEmpty(csrDetails.Organization       /**/)) xn.Common = csrDetails.Organization;     // O;
            if (!string.IsNullOrEmpty(csrDetails.OrganizationUnit   /**/)) xn.Common = csrDetails.OrganizationUnit; // OU;
            if (!string.IsNullOrEmpty(csrDetails.Description        /**/)) xn.Common = csrDetails.Description;      // D;
            if (!string.IsNullOrEmpty(csrDetails.Surname            /**/)) xn.Common = csrDetails.Surname;          // S;
            if (!string.IsNullOrEmpty(csrDetails.GivenName          /**/)) xn.Common = csrDetails.GivenName;        // G;
            if (!string.IsNullOrEmpty(csrDetails.Initials           /**/)) xn.Common = csrDetails.Initials;         // I;
            if (!string.IsNullOrEmpty(csrDetails.Title              /**/)) xn.Common = csrDetails.Title;            // T;
            if (!string.IsNullOrEmpty(csrDetails.SerialNumber       /**/)) xn.Common = csrDetails.SerialNumber;     // SN;
            if (!string.IsNullOrEmpty(csrDetails.UniqueIdentifier   /**/)) xn.Common = csrDetails.UniqueIdentifier; // UID;

            var xr = new X509Request(0, xn, rsaKeys);
            var md = MessageDigest.CreateByName(messageDigest); ;
            xr.Sign(rsaKeys, md);
            using (var bio = BIO.MemoryBuffer())
            {
                xr.Write(bio);
                return new Csr(bio.ReadString());
            }
        }
        /// <summary>
        /// Creates a new wire message.
        /// </summary>
        /// <param name="messageType">Message type name</param>
        /// <param name="serializedMessage">Serialized message</param>
        /// <param name="serializer">Serializer used to serialize the signed content</param>
        /// <param name="keyPair">RSA key pair to be used for creating a RSA signature for the message data</param>
        /// <param name="sharedSecret">Shared secret (wire message will be not encrypted, if null)</param>
        /// <param name="error">Species whether the wire message is in error state</param>
        /// <param name="uniqueCallKey">Unique key to correlate RPC call</param>
        /// <returns>The created wire message</returns>
        /// <exception cref="ArgumentException">Thrown if the message type is left empty.</exception>
        public WireMessage CreateWireMessage(
            string messageType,
            byte[] serializedMessage,
            ISerializerAdapter serializer,
            RsaKeyPair keyPair   = null,
            byte[] sharedSecret  = null,
            bool error           = false,
            byte[] uniqueCallKey = null)
        {
            if (string.IsNullOrWhiteSpace(messageType))
            {
                throw new ArgumentException("Message type must not be empty.", nameof(messageType));
            }

            byte[] iv =
                sharedSecret == null
                    ? new byte[0]
                    : AesEncryption.GenerateIv();

            byte[] rawContent;

            if (keyPair != null && sharedSecret != null)
            {
                var signedMessageData =
                    new SignedMessageData()
                {
                    MessageRawData = serializedMessage,
                    Signature      =
                        RsaSignature.CreateSignature(
                            keySize: keyPair.KeySize,
                            sendersPrivateKeyBlob: keyPair.PrivateKey,
                            rawData: serializedMessage)
                };

                rawContent = serializer.Serialize(typeof(SignedMessageData), signedMessageData);
            }
            else
            {
                rawContent = serializedMessage;
            }

            byte[] messageContent =
                sharedSecret == null
                    ? rawContent
                    : AesEncryption.Encrypt(
                    dataToEncrypt: rawContent,
                    sharedSecret: sharedSecret,
                    iv: iv);

            return
                (new WireMessage()
            {
                MessageType = messageType,
                Data = messageContent,
                Iv = iv,
                Error = error,
                UniqueCallKey = uniqueCallKey
            });
        }
Exemplo n.º 9
0
        private void ciphertextTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!editingPlaintext && !string.IsNullOrWhiteSpace(ciphertextTextBox.Text))
            {
                lastPlaintext     = false;
                editingCiphertext = true;

                if (identityComboBox.SelectedIndex != -1)
                {
                    RsaKeyPair selectedKey = KeyManager.Keys[identityComboBox.SelectedIndex];

                    if (!selectedKey.PublicOnly)
                    {
                        string cipher = ciphertextTextBox.Text.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries).Last();
                        cipher = cipher.Replace("\n", "");

                        string error       = string.Empty;
                        byte[] cipherBytes = null;
                        try
                        {
                            cipherBytes = Convert.FromBase64String(cipher);
                        }
                        catch
                        {
                            error = "Invalid Base64";
                        }

                        string plain = "";
                        if (string.IsNullOrWhiteSpace(error))
                        {
                            try
                            {
                                plain = System.Text.Encoding.UTF8.GetString(Crypto.RsaDecrypt(selectedKey.PrivateCsp, cipherBytes));
                            }
                            catch
                            {
                                error = "Decryption Failure";
                            }
                        }

                        if (string.IsNullOrWhiteSpace(error))
                        {
                            plaintextTextBox.Text     = plain;
                            arrowRight.Visibility     = Visibility.Collapsed;
                            arrowLeft.Visibility      = Visibility.Visible;
                            errorTextBlock.Visibility = Visibility.Collapsed;
                        }
                        else
                        {
                            errorTextBlock.Visibility = Visibility.Visible;
                            errorTextBlock.Text       = error;
                        }
                    }
                }
            }

            editingCiphertext = false;
        }
Exemplo n.º 10
0
        // Static Methods

        public static Account Create(List <string> contactEmails)
        {
            var key = RsaKeyPair.New();

            return(new Account(key)
            {
                Contact = contactEmails
            });
        }
Exemplo n.º 11
0
        // Sign up user with passed credentials. RSA key pair will be generated automatically.
        public static bool SignUp(string name, string login, string password)
        {
            // Generate new key pair.
            var keyPair = RsaKeyPair.GenerateKeyPair();

            // Persist private key. Not the best place to do it, but it doesn't matter.
            CredentialsManager.Store(login, keyPair.PrivateKeyXml);
            // Client method call.
            return(AppUser.GetInstance().Client.SignUp(login, name, password, keyPair.PublicKeyXml));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Writes the public key from the private key specified.
        /// </summary>
        /// <param name="privateKeyFile"></param>
        public static void WriteRsaKeyPair(string privateKeyFile, string comment)
        {
            RsaKeyPair pair = GenerateRsaKeyPair(privateKeyFile, comment);

            // We only need to write the public key since we already got the private one.
            TextWriter tw = new StreamWriter(privateKeyFile + ".pub", false);

            tw.WriteLine(pair.PublicSSHKey);
            tw.Close();
        }
Exemplo n.º 13
0
        public static void RsaManagerTests()
        {
            string data = "HelloWorld!!!";

            Console.WriteLine("█ BER");
            RsaKeyPair keyPair = RsaManager.CreateKeyPair(4096, RsaKeyEncoding.Ber);

            Console.WriteLine("Public:\n" + keyPair.PublicKey);
            Console.WriteLine("Private:\n" + keyPair.PrivateKey);
            string encrypted = RsaManager.EncryptToBase64(data, keyPair.PublicKey);

            Console.WriteLine("Encrypted: " + encrypted);
            Console.WriteLine("Decrypted: " + RsaManager.DecryptFromBase64(encrypted, keyPair.PrivateKey));

            Console.WriteLine("█ XML");
            keyPair = RsaManager.CreateKeyPair(4096, RsaKeyEncoding.Xml, false);
            Console.WriteLine("Public:\n" + keyPair.PublicKey);
            Console.WriteLine("Private:\n" + keyPair.PrivateKey);
            encrypted = RsaManager.EncryptToBase64(data, keyPair.PublicKey);
            Console.WriteLine("Encrypted: " + encrypted);
            Console.WriteLine("Decrypted: " + RsaManager.DecryptFromBase64(encrypted, keyPair.PrivateKey));

            Console.WriteLine("█ XML INDENTED");
            keyPair = RsaManager.CreateKeyPair(4096, RsaKeyEncoding.Xml);
            Console.WriteLine("Public:\n" + keyPair.PublicKey);
            Console.WriteLine("Private:\n" + keyPair.PrivateKey);
            encrypted = RsaManager.EncryptToBase64(data, keyPair.PublicKey);
            Console.WriteLine("Encrypted: " + encrypted);
            Console.WriteLine("Decrypted: " + RsaManager.DecryptFromBase64(encrypted, keyPair.PrivateKey));

            Console.WriteLine("█ JSON");
            keyPair = RsaManager.CreateKeyPair(4096, RsaKeyEncoding.Json, false);
            Console.WriteLine("Public:\n" + keyPair.PublicKey);
            Console.WriteLine("Private:\n" + keyPair.PrivateKey);
            encrypted = RsaManager.EncryptToBase64(data, keyPair.PublicKey);
            Console.WriteLine("Encrypted: " + encrypted);
            Console.WriteLine("Decrypted: " + RsaManager.DecryptFromBase64(encrypted, keyPair.PrivateKey));

            Console.WriteLine("█ JSON INDENTED");
            keyPair = RsaManager.CreateKeyPair(512, RsaKeyEncoding.Json);
            Console.WriteLine("Public:\n" + keyPair.PublicKey);
            Console.WriteLine("Private:\n" + keyPair.PrivateKey);
            encrypted = RsaManager.EncryptToBase64(data, keyPair.PublicKey);
            Console.WriteLine("Encrypted: " + encrypted);
            Console.WriteLine("Decrypted: " + RsaManager.DecryptFromBase64(encrypted, keyPair.PrivateKey));

            Console.WriteLine("█ PEM");
            keyPair = RsaManager.CreateKeyPair(4096, RsaKeyEncoding.Pem);
            Console.WriteLine("Public:\n" + keyPair.PublicKey);
            Console.WriteLine("Private:\n" + keyPair.PrivateKey);
            encrypted = RsaManager.EncryptToBase64(data, keyPair.PublicKey);
            Console.WriteLine("Encrypted: " + encrypted);
            Console.WriteLine("Decrypted: " + RsaManager.DecryptFromBase64(encrypted, keyPair.PrivateKey));
        }
Exemplo n.º 14
0
        private const string XmlPublicAndPrivateKeyPattern  = "(\\s*<\\s*RSAKeyValue\\s*>\\s*(?:\\s*<\\s*Modulus\\s*>\\s*[a-zA-Z0-9\\+\\/]+={0,2}\\s*<\\/\\s*Modulus\\s*>()|\\s*<\\s*Exponent\\s*>\\s*[a-zA-Z0-9\\+\\/]+={0,2}\\s*<\\/\\s*Exponent\\s*>()|\\s*<\\s*P\\s*>\\s*[a-zA-Z0-9\\+\\/]+={0,2}\\s*<\\/\\s*P\\s*>()|\\s*<\\s*Q\\s*>\\s*[a-zA-Z0-9\\+\\/]+={0,2}\\s*<\\/\\s*Q\\s*>()|\\s*<\\s*DP\\s*>\\s*[a-zA-Z0-9\\+\\/]+={0,2}\\s*<\\/\\s*DP\\s*>()|\\s*<\\s*DQ\\s*>\\s*[a-zA-Z0-9\\+\\/]+={0,2}\\s*<\\/\\s*DQ\\s*>()|\\s*<\\s*InverseQ\\s*>\\s*[a-zA-Z0-9\\+\\/]+={0,2}\\s*<\\/\\s*InverseQ\\s*>()|\\s*<\\s*D\\s*>\\s*[a-zA-Z0-9\\+\\/]+={0,2}\\s*<\\/\\s*D\\s*>()){8}\\s*<\\/\\s*RSAKeyValue\\s*>\\s*\\2\\3\\4\\5\\6\\7\\8\\9)|(\\s*<\\s*RSAKeyValue\\s*>\\s*(?:\\s*<\\s*Modulus\\s*>\\s*[a-zA-Z0-9\\+\\/]+={0,2}\\s*<\\/\\s*Modulus\\s*>()|\\s*<\\s*Exponent\\s*>\\s*[a-zA-Z0-9\\+\\/]+={0,2}\\s*<\\/\\s*Exponent\\s*>()){2}\\s*<\\/\\s*RSAKeyValue\\s*>\\s*\\11\\12)";                                                                                                                                                                                                                                                                                    //https://regex101.com/r/fQV2VN/4  (\s*<\s*RSAKeyValue\s*>\s*(?:\s*<\s*Modulus\s*>\s*[a-zA-Z0-9\+\/]+={0,2}\s*<\/\s*Modulus\s*>()|\s*<\s*Exponent\s*>\s*[a-zA-Z0-9\+\/]+={0,2}\s*<\/\s*Exponent\s*>()|\s*<\s*P\s*>\s*[a-zA-Z0-9\+\/]+={0,2}\s*<\/\s*P\s*>()|\s*<\s*Q\s*>\s*[a-zA-Z0-9\+\/]+={0,2}\s*<\/\s*Q\s*>()|\s*<\s*DP\s*>\s*[a-zA-Z0-9\+\/]+={0,2}\s*<\/\s*DP\s*>()|\s*<\s*DQ\s*>\s*[a-zA-Z0-9\+\/]+={0,2}\s*<\/\s*DQ\s*>()|\s*<\s*InverseQ\s*>\s*[a-zA-Z0-9\+\/]+={0,2}\s*<\/\s*InverseQ\s*>()|\s*<\s*D\s*>\s*[a-zA-Z0-9\+\/]+={0,2}\s*<\/\s*D\s*>()){8}\s*<\/\s*RSAKeyValue\s*>\s*\2\3\4\5\6\7\8\9)|(\s*<\s*RSAKeyValue\s*>\s*(?:\s*<\s*Modulus\s*>\s*[a-zA-Z0-9\+\/]+={0,2}\s*<\/\s*Modulus\s*>()|\s*<\s*Exponent\s*>\s*[a-zA-Z0-9\+\/]+={0,2}\s*<\/\s*Exponent\s*>()){2}\s*<\/\s*RSAKeyValue\s*>\s*\11\12)


        public static RsaKeyPair CreateRsaKeyPair(this uint keySize, RsaKeyEncoding encoding = RsaKeyEncoding.Ber, bool indent = true)
        {
            RsaKeyPair result;

            using (RSACryptoServiceProvider Csp = new RSACryptoServiceProvider((int)keySize))
            {
                switch (encoding)
                {
                case RsaKeyEncoding.Xml:
                    result = new RsaKeyPair(
                        publicKey: XDocument.Parse(Csp.ToXmlString(false)).ToString(indent ? SaveOptions.None : SaveOptions.DisableFormatting),
                        privateKey: XDocument.Parse(Csp.ToXmlString(true)).ToString(indent ? SaveOptions.None : SaveOptions.DisableFormatting)
                        );
                    break;

                case RsaKeyEncoding.Json:
                    RSAParameters parameters = Csp.ExportParameters(true);
                    var           pubKey     = new
                    {
                        Modulus  = (parameters.Modulus !).ToBase64(),
                        Exponent = (parameters.Exponent !).ToBase64(),
                    };
                    var privKey = new
                    {
                        Modulus  = (parameters.Modulus !).ToBase64(),
                        Exponent = (parameters.Exponent !).ToBase64(),
                        P        = (parameters.P !).ToBase64(),
                        Q        = (parameters.Q !).ToBase64(),
                        DP       = (parameters.DP !).ToBase64(),
                        DQ       = (parameters.DQ !).ToBase64(),
                        InverseQ = (parameters.InverseQ !).ToBase64(),
                        D        = (parameters.D !).ToBase64()
                    };
                    var options = new JsonSerializerOptions
                    {
                        WriteIndented = indent
                    };
                    result = new RsaKeyPair(JsonSerializer.Serialize(pubKey, options), JsonSerializer.Serialize(privKey, options));
                    break;

                case RsaKeyEncoding.Pem:
                    result = new RsaKeyPair($"{RsaPemPublicKeyInitialString}{Environment.NewLine}{Csp.ExportSubjectPublicKeyInfo().ToBase64(HashExtensions.PemLineBreaksLength)}{Environment.NewLine}{RsaPemPublicKeyFinalString}",
                                            $"{RsaPemPrivateKeyInitialString}{Environment.NewLine}{Csp.ExportPkcs8PrivateKey().ToBase64(HashExtensions.PemLineBreaksLength)}{Environment.NewLine}{RsaPemPrivateKeyFinalString}");
                    break;

                default:
                    result = new RsaKeyPair(publicKey: Csp.ExportSubjectPublicKeyInfo().ToBase64(), privateKey: Csp.ExportPkcs8PrivateKey().ToBase64());
                    break;
                }
                ValidateRsaPublicKey(result.PublicKey);
                ValidateRsaPrivateKey(result.PrivateKey);
                return(result);
            }
        }
Exemplo n.º 15
0
        // Ctor

        public Certificate(RsaKeyPair key = null)
        {
            // Generate new RSA key for certificate
            if (key == null)
            {
                Key = RsaKeyPair.New();
            }
            else
            {
                Key = key;
            }
        }
Exemplo n.º 16
0
        public static async Task <Account> LoadAsync(string contactEmail)
        {
            var location = await _localStorage.LoadAccount(contactEmail);

            var privateKeyPem = await _localStorage.LoadPrivateKey(contactEmail);

            //var publicKeyPem = await _localStorage.LoadPublicKey(contactEmail);

            var key = new RsaKeyPair(privateKeyPem);

            return(new Account(key, location));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Writes a pair of files representing the Public Key in ssh-required format
        /// and the Private key in PEM format.
        /// </summary>
        /// <param name="bits"></param>
        /// <param name="comment"></param>
        /// <param name="privFileName"></param>
        public static void WriteRsaKeyPair(int bits, string comment, string privFileName)
        {
            RsaKeyPair pair = GenerateRsaKeyPair(bits, comment);
            TextWriter tw;

            tw = new StreamWriter(privFileName, false);
            tw.WriteLine(pair.PrivateKeyAsPEM);
            tw.Close();

            tw = new StreamWriter(privFileName + ".pub", false);
            tw.WriteLine(pair.PublicSSHKey);
            tw.Close();
        }
Exemplo n.º 18
0
        public void TestRsaEncryptAndDecrypt()
        {
            string _data               = "I am union guy."
            , _dataEncrypted           = ""
            , _dataDecrypted           = "";
            RsaKeyPair   _rsaKeyPair   = new RsaKeyPair();
            RsaKeyFormat _rsaKeyFormat = RsaKeyFormat.PEM;

            _dataEncrypted = RsaHelper.Encrypt(_rsaKeyFormat, _rsaKeyPair.PublicKey_PEM, _data);
            _dataDecrypted = RsaHelper.Decrypt(_rsaKeyFormat, _rsaKeyPair.PrivateKey_PEM, _dataEncrypted);

            Assert.AreEqual(_data, _dataDecrypted, string.Format("Data = {0}, DataEncrypted = {1}, DataDecrypted = {2}", _data, _dataEncrypted, _dataDecrypted));
        }
Exemplo n.º 19
0
        public static void SaveKey(RsaKeyPair Key)
        {
            string json = Key.ToJson();

            byte[] bytes = Crypto.RsaEncrypt(masterKey.PublicCsp, System.Text.Encoding.UTF8.GetBytes(json));

            string filename = $"{path}\\{Key.Hash.Replace("+", "").Replace("=", "").Replace("/", "").Substring(0, 16)}.key";

            if (System.IO.File.Exists(filename))
            {
                System.IO.File.Delete(filename);
            }
            System.IO.File.WriteAllBytes(filename, bytes);
        }
Exemplo n.º 20
0
        public void EncryptAndDecrypt()
        {
            var pair = new RsaKeyPair();

            var str = "Hello";

            var encoded = RsaCipher.Encrypt(str, pair.PublicKey);

            Assert.NotEqual(str, encoded);

            var decoded = RsaCipher.Decrypt(encoded, pair.PrivateKey);

            Assert.Equal(str, decoded);
        }
Exemplo n.º 21
0
        public void SaveAndLoad()
        {
            var pair = new RsaKeyPair();

            pair.SaveToFile(PairFile);

            var pair2 = new RsaKeyPair();

            pair2.LoadFromFile(PairFile);

            Assert.Equal(pair.PublicKey.Parameters.Exponent, pair2.PublicKey.Parameters.Exponent);
            Assert.Equal(pair.PublicKey.Parameters.Modulus, pair2.PublicKey.Parameters.Modulus);
            Assert.Equal(pair2.PublicKey.Parameters.D, null);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Creates a new instance of the RemotingClient class.
        /// </summary>
        /// <param name="config">Configuration settings</param>
        public RemotingClient(ClientConfig config) : this()
        {
            if (config == null)
            {
                throw new ArgumentException("No config provided and no default configuration found.");
            }

            Serializer        = config.Serializer ?? new BsonSerializerAdapter();
            MessageEncryption = config.MessageEncryption;

            _config = config;

            if (MessageEncryption)
            {
                _keyPair = new RsaKeyPair(config.KeySize);
            }

            _channel = config.Channel ?? new WebsocketClientChannel();

            _channel.Init(this);
            _rawMessageTransport = _channel.RawMessageTransport;
            _rawMessageTransport.ReceiveMessage += OnMessage;
            _rawMessageTransport.ErrorOccured   += (s, exception) =>
            {
                if (exception != null)
                {
                    throw exception;
                }

                throw new NetworkException(s);
            };

            _clientInstances.AddOrUpdate(
                key: config.UniqueClientInstanceName,
                addValueFactory: uniqueInstanceName => this,
                updateValueFactory: (uniqueInstanceName, oldClient) =>
            {
                oldClient?.Dispose();
                return(this);
            });

            if (!config.IsDefault)
            {
                return;
            }

            RemotingClient.DefaultRemotingClient ??= this;
        }
Exemplo n.º 23
0
        private void exportButton_Click(object sender, RoutedEventArgs e)
        {
            RsaKeyPair key = ((Button)e.OriginalSource).DataContext as RsaKeyPair;

            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName         = MakeValidFileName((string.IsNullOrWhiteSpace(key.Note) ? "" : key.Note + ".") + (key.PublicOnly ? "Public." : "") + key.Hash.Substring(0, 16));//key.Hash.Substring(0,16);
            dlg.Filter           = "JSON (.json)|*.json|plain text (*.txt)|*.txt|All files (*.*)|*.*";
            dlg.FilterIndex      = 1;
            dlg.RestoreDirectory = true;
            dlg.Title            = "Export Key";

            if (dlg.ShowDialog() == true)
            {
                try
                {
                    if (System.IO.File.Exists(dlg.FileName))
                    {
                        System.IO.File.Delete(dlg.FileName);
                    }

                    if (dlg.FileName.EndsWith(".JSON", StringComparison.InvariantCultureIgnoreCase))
                    {
                        System.IO.File.WriteAllText(dlg.FileName, key.ToJson());
                    }
                    else
                    {
                        string text = key.PublicKey;
                        if (!key.PublicOnly)
                        {
                            text += "\n" + key.PrivateKey;
                        }
                        text += "\n";
                        System.IO.File.WriteAllText(dlg.FileName, text);
                    }

                    MessageBox.Show("File saved", "Success", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Encountered an error while trying to write to\n{dlg.FileName}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
Exemplo n.º 24
0
        private void plaintextTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!editingCiphertext && !string.IsNullOrWhiteSpace(plaintextTextBox.Text))
            {
                lastPlaintext    = true;
                editingPlaintext = true;
                if (identityComboBox.SelectedIndex != -1)
                {
                    RsaKeyPair selectedKey = KeyManager.Keys[identityComboBox.SelectedIndex];

                    byte[] buffer = Crypto.RsaEncrypt(selectedKey.PublicCsp, System.Text.Encoding.UTF8.GetBytes(plaintextTextBox.Text));

                    string cipher = $"[{selectedKey.Hash.Substring(0, 16)}]\n{Convert.ToBase64String(buffer)}";

                    ciphertextTextBox.Text = cipher;
                    arrowRight.Visibility  = Visibility.Visible;
                    arrowLeft.Visibility   = Visibility.Collapsed;
                }
            }

            editingPlaintext = false;
        }
Exemplo n.º 25
0
        public void VerifySignature_should_return_true_if_signature_is_valid()
        {
            int keySize = 4096;
            var keyPair = new RsaKeyPair(keySize);

            var data = Encoding.UTF8.GetBytes("Test");

            var signature =
                RsaSignature.CreateSignature(
                    keySize: keySize,
                    sendersPrivateKeyBlob: keyPair.PrivateKey,
                    rawData: data);

            var result =
                RsaSignature.VerifySignature(
                    keySize: keySize,
                    sendersPublicKeyBlob: keyPair.PublicKey,
                    rawData: data,
                    signature: signature);

            Assert.Equal(512, signature.Length);
            Assert.True(result);
        }
Exemplo n.º 26
0
        public static void Initialize(string Password)
        {
            if (Initialized)
            {
                return;
            }

            path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + @"\OradeTech\CryptoTool\Keys";

            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }

            salt      = System.Text.Encoding.UTF8.GetBytes(Password);
            masterKey = Crypto.RsaKeysFromPassword(Password, salt);

            var files = System.IO.Directory.GetFiles(path);

            foreach (string keyFile in files)
            {
                try
                {
                    byte[]     buffer    = System.IO.File.ReadAllBytes(keyFile);
                    byte[]     decrypted = Crypto.RsaDecrypt(masterKey.PrivateCsp, buffer);
                    string     json      = System.Text.Encoding.UTF8.GetString(decrypted);
                    RsaKeyPair key       = RsaKeyPair.FromJson(json);
                    Keys.Add(key);
                }
                catch
                {
                    Console.WriteLine("Failed to load key");
                }
            }

            Initialized = true;
        }
Exemplo n.º 27
0
 public Account(RsaKeyPair key)
     : this()
 {
     Key    = key;
     Signer = new JwsSigner(Key);
 }
 private void privateTextBox_TextChanged(object sender, TextChangedEventArgs e)
 {
     Result = null;
     errorTextBlock.Visibility = Visibility.Hidden;
 }
Exemplo n.º 29
0
        // Ctor

        public JwsSigner(RsaKeyPair key)
        {
            _key = key;
        }
Exemplo n.º 30
0
 public Account(RsaKeyPair key, string location)
     : this(key)
 {
     Location = new Uri(location);
 }
Exemplo n.º 31
0
        public static Csr GenerateCsr(CsrDetails csrDetails, RsaKeyPair rsaKeyPair, string messageDigest = "SHA256")
        {
            var rsaKeys = CryptoKey.FromPrivateKey(rsaKeyPair.Pem, null);

            // Translate from our external form to our OpenSSL internal form
            // Ref:  https://www.openssl.org/docs/manmaster/crypto/X509_NAME_new.html
            var xn = new X509Name();

            if (!string.IsNullOrEmpty(csrDetails.CommonName /**/))
            {
                xn.Common = csrDetails.CommonName;                                                                  // CN;
            }
            if (!string.IsNullOrEmpty(csrDetails.Country /**/))
            {
                xn.Common = csrDetails.Country;                                                                     // C;
            }
            if (!string.IsNullOrEmpty(csrDetails.StateOrProvince /**/))
            {
                xn.Common = csrDetails.StateOrProvince;                                                             // ST;
            }
            if (!string.IsNullOrEmpty(csrDetails.Locality /**/))
            {
                xn.Common = csrDetails.Locality;                                                                    // L;
            }
            if (!string.IsNullOrEmpty(csrDetails.Organization /**/))
            {
                xn.Common = csrDetails.Organization;                                                                // O;
            }
            if (!string.IsNullOrEmpty(csrDetails.OrganizationUnit /**/))
            {
                xn.Common = csrDetails.OrganizationUnit;                                                            // OU;
            }
            if (!string.IsNullOrEmpty(csrDetails.Description /**/))
            {
                xn.Common = csrDetails.Description;                                                                 // D;
            }
            if (!string.IsNullOrEmpty(csrDetails.Surname /**/))
            {
                xn.Common = csrDetails.Surname;                                                                     // S;
            }
            if (!string.IsNullOrEmpty(csrDetails.GivenName /**/))
            {
                xn.Common = csrDetails.GivenName;                                                                   // G;
            }
            if (!string.IsNullOrEmpty(csrDetails.Initials /**/))
            {
                xn.Common = csrDetails.Initials;                                                                    // I;
            }
            if (!string.IsNullOrEmpty(csrDetails.Title /**/))
            {
                xn.Common = csrDetails.Title;                                                                       // T;
            }
            if (!string.IsNullOrEmpty(csrDetails.SerialNumber /**/))
            {
                xn.Common = csrDetails.SerialNumber;                                                                // SN;
            }
            if (!string.IsNullOrEmpty(csrDetails.UniqueIdentifier /**/))
            {
                xn.Common = csrDetails.UniqueIdentifier;                                                            // UID;
            }
            var xr = new X509Request(0, xn, rsaKeys);
            var md = MessageDigest.CreateByName(messageDigest);;

            xr.Sign(rsaKeys, md);
            using (var bio = BIO.MemoryBuffer())
            {
                xr.Write(bio);
                return(new Csr(bio.ReadString()));
            }
        }
 private void cancelButton_Click(object sender, RoutedEventArgs e)
 {
     Result = null;
     this.Close();
 }