Пример #1
0
        static void Main(string[] args)
        {
            Console.WriteLine("\n --- RSA.ALGORITHM ---\n");

            RsaAlgorithm rsa = new RsaAlgorithm();

            RsaPublicKey  publicKey  = rsa.GetPublicKeyEN();
            RsaPrivateKey privateKey = rsa.GetPrivateKeyDN();

            Console.WriteLine($" * Private key: {privateKey.D}, {privateKey.N}");
            Console.WriteLine($" * Public key: {publicKey.E}, {publicKey.N}");

            int input;

            do
            {
                Console.Write("\n - Enter for encrypt/decrypt (1 - 10000): ");
                input = int.Parse(Console.ReadLine() ?? string.Empty);
            } while (input < 1 || input > 10000);

            int encrypt = rsa.EncryptMessage(input);
            int decrypt = rsa.DecryptMessage(encrypt);

            Console.WriteLine($"\n * Encrypt: {encrypt}");
            Console.WriteLine($" * Decrypt: {decrypt}");

            Console.Write("\n --- Press <ENTER>: ");
            Console.ReadLine();
        }
        private void GenerateKeys(string seed)
        {
            // generate the RSA keypair for the address
            AsymmetricCipherKeyPair rsaKeyPair = WalletController.GetRSAKeyPairFromSeed(seed);

            RsaKeyParameters rsaPublicKey = rsaKeyPair.Public as RsaKeyParameters;
            RsaPublicKey     pbk          = new RsaPublicKey()
            {
                Exponent = rsaPublicKey.Exponent.ToByteArrayUnsigned(),
                Modulus  = rsaPublicKey.Modulus.ToByteArrayUnsigned()
            };

            RsaPrivateCrtKeyParameters rsaPrivateKey = rsaKeyPair.Private as RsaPrivateCrtKeyParameters;
            RsaPrivateKey prk = new RsaPrivateKey()
            {
                DP             = rsaPrivateKey.DP.ToByteArrayUnsigned(),
                DQ             = rsaPrivateKey.DQ.ToByteArrayUnsigned(),
                Exponent       = rsaPrivateKey.Exponent.ToByteArrayUnsigned(),
                Modulus        = rsaPrivateKey.Modulus.ToByteArrayUnsigned(),
                P              = rsaPrivateKey.P.ToByteArrayUnsigned(),
                PublicExponent = rsaPrivateKey.PublicExponent.ToByteArrayUnsigned(),
                Q              = rsaPrivateKey.Q.ToByteArrayUnsigned(),
                QInv           = rsaPrivateKey.QInv.ToByteArrayUnsigned()
            };

            this._testOutputHelper.WriteLine($"Public key: {pbk.ToHex()}");
            this._testOutputHelper.WriteLine($"Private key: {prk.ToHex()}");
        }
Пример #3
0
        public void GenerateNewKeyset_Should_ThrowException_When_PublicKeyIsNull()
        {
            // Arrange
            var          key        = new RsaEncryption();
            var          privateKey = new RsaPrivateKey();
            RsaPublicKey publicKey  = null;

            // Act & Assert
            Assert.Throws <ArgumentNullException>(() => key.GenerateNewKeyset(ref publicKey, ref privateKey));
        }
Пример #4
0
        public void LoadFromCertificateFile_Should_LoadCertificate_When_FileIsPasswordProtected()
        {
            // Arrange
            var cert = $"{_assemblyPath}RsaEncrypt.pfx";

            // Act
            var publicKey = RsaPublicKey.LoadFromCertificateFile(cert, "password");

            // Assert
            Assert.NotNull(publicKey);
        }
Пример #5
0
        public void LoadFromXmlFile_Should_LoadThePublicKeyFromFile()
        {
            // Arrange
            var file = $"{_assemblyPath}publicKey.xml";

            // Act
            var key = RsaPublicKey.LoadFromXmlFile(file);

            // Assert
            Assert.Equal("AQAB", key.Exponent);
        }
Пример #6
0
        public async Task <string> ToJsonAsync(RsaPublicKey sigPubKey)
        {
            var jwt = await RetrieveUriContentsAsync(RequestUri);

            if (Util.IsCompactJwe(jwt))
            {
                return(CONTENT_IS_ENCRYPTED);
            }

            return(sigPubKey.VerifyCompactJws(jwt));
        }
Пример #7
0
        public void Constructor_Should_ThrowExceptionWhenRSAPublicKeyIsNotProvided()
        {
            // Arrange
            RsaPublicKey key = null;

            // Act & Assert
            Assert.Throws <ArgumentNullException>(() =>
            {
                var e1 = new ASymmetricEncryption(key);
            });
        }
        public void AgentCreateDeviceSetRsaKey()
        {
            // generate RSA key pair
            RsaKeyGenerator generator  = new RsaKeyGenerator();
            RsaPrivateKey   privateKey = generator.GeneratePrivateKey(2048);
            RsaPublicKey    publicKey  = generator.GeneratePublicKey(privateKey);

            // set RSA keys into a CreateDeviceRequest object
            CreateDeviceRequest request = new CreateDeviceRequest();

            request.ClientRsaPrivateKey = privateKey;
            request.ClientRsaPublicKey  = publicKey;
        }
Пример #9
0
        public void Constructor_Should_ThrowExceptionWhenNoRSAPublicKeyIsProvidedButPasswordIs()
        {
            // Arrange
            RsaPublicKey key      = null;
            var          password = new EncryptionData("password");

            // Act & Assert
            Assert.Throws <ArgumentNullException>(
                () =>
            {
                var e1 = new ASymmetricEncryption(key, password);
            });
        }
Пример #10
0
        public void Encrypt_Should_ThrowException_When_EncryptingToMuchData()
        {
            // Arrange
            var publicKey  = new RsaPublicKey();
            var privateKey = new RsaPrivateKey();
            var e1         = new RsaEncryption();

            // Act
            e1.GenerateNewKeyset(ref publicKey, ref privateKey);

            // Assert
            Assert.Throws <CryptographicException>(() => e1.Encrypt(new EncryptionData(_targetString), publicKey));
        }
Пример #11
0
        public string ToJson(RsaPublicKey sigPubKey)
        {
            if (Util.IsCompactJwe(Jwt))
            {
                return(Util.Jsonize(CONTENT_IS_ENCRYPTED));
            }
            if (Util.IsCompactJws(Jwt))
            {
                return(sigPubKey.VerifyCompactJws(Jwt));
            }

            throw new GoodIdException("Unsupported JWT format.");
        }
Пример #12
0
        public void Encrypt_Should_ThrowException_When_DataIsNull()
        {
            // Arrange
            var publicKey  = new RsaPublicKey();
            var privateKey = new RsaPrivateKey();
            var e1         = new RsaEncryption();

            e1.GenerateNewKeyset(ref publicKey, ref privateKey);
            EncryptionData data = null;

            // Act & Assert
            Assert.Throws <ArgumentNullException>(() => e1.Encrypt(data, publicKey));
        }
Пример #13
0
        public void LoadFromXml_Should_ReturnExpectedResult()
        {
            // Arrange
            const string xml = "<RSAKeyValue>" +
                               "<Modulus>0D59Km2Eo9oopcm7Y2wOXx0TRRXQFybl9HHe/ve47Qcf2EoKbs9nkuMmhCJlJ" +
                               "zrq6ZJzgQSEbpVyaWn8OHq0I50rQ13dJsALEquhlfwVWw6Hit7qRvveKlOAGfj8xdkaXJ" +
                               "LYS1tA06tKHfYxgt6ysMBZd0DIedYoE1fe3VlLZyE=</Modulus>" +
                               "<Exponent>AQAB</Exponent>" +
                               "</RSAKeyValue>";

            // Act
            var rsa = RsaPublicKey.LoadFromXml(xml);

            // Assert
            Assert.Equal("AQAB", rsa.Exponent);
        }
Пример #14
0
        public void Modulus_Should_ReturnExpectedResult()
        {
            // Arrange
            const string e = "AQAB";
            const string m = "z8FBNlJQrn4rEKhGlNvQDKgKDlHHOVu2hlWkP0pRrxTyp1/h/dJsBN4dfASY2A1"
                             + "r5KBCg1dySSNVFB5bJP9o9ob2GEL0dlbZtg0CiiWCwOFWBgakav3Va1+CUF6DbN"
                             + "g3gw2c/1WQaq73xB/WbKuLp5yk22HP/kVOUaG6H33Muv3s2/GxXClgnw8tOqLYbO"
                             + "A/tb9G9d0MIyhhEG/vOR8kkKrwZTeIECbT8vZl0B952leMKmoBN3AJVdnzmP43H"
                             + "Jvx28N0VJ0teV0emgOGnyhpNMB01KlTqd2Kc6Hls7AQbBJ/bkgmlnSdQA7vipig"
                             + "FKU19rhgMd4/95gBmTJOb71wfQ==";

            // Act
            var key = new RsaPublicKey(e, m);

            // Assert
            Assert.Equal(m, key.Modulus);
        }
Пример #15
0
        public void Decrypt_Should_ReturnExpectedResult_When_UsingExplicitKeySizeAndGeneratedKeys()
        {
            // Arrange
            var publicKey  = new RsaPublicKey();
            var privateKey = new RsaPrivateKey();

            var e1 = new RsaEncryption(4096);
            var e2 = new RsaEncryption(4096);

            e1.GenerateNewKeyset(ref publicKey, ref privateKey);

            // Act
            var encryptedData = e1.Encrypt(new EncryptionData(Secret), publicKey);
            var decryptedData = e2.Decrypt(encryptedData, privateKey);

            // Assert
            Assert.Equal(decryptedData.Text, Secret);
        }
Пример #16
0
        public void Verify_Should_ReturnTrue_When_ValidatingUnChangedSignedData()
        {
            // Arrange
            var secretData = new EncryptionData(Secret);

            var publicKey  = new RsaPublicKey();
            var privateKey = new RsaPrivateKey();
            var e1         = new RsaEncryption();

            e1.GenerateNewKeyset(ref publicKey, ref privateKey);

            // Act
            var signature = e1.Sign(secretData, privateKey);
            var actual    = e1.Verify(secretData, signature, publicKey);

            // Assert
            Assert.True(actual);
        }
Пример #17
0
        public void Decrypt_Should_ReturnExpectedResult_When_KeyIsStoredInCertificate()
        {
            // Arrange
            var cert = $"{_assemblyPath}RsaEncrypt";

            var publicKey  = RsaPublicKey.LoadFromCertificateFile(cert + ".cer");
            var privateKey = RsaPrivateKey.LoadFromCertificateFile(cert + ".pfx", "password");

            var e1 = new RsaEncryption();
            var e2 = new RsaEncryption();

            // Act
            var encryptedData = e1.Encrypt(new EncryptionData(Secret), publicKey);
            var decryptedData = e2.Decrypt(encryptedData, privateKey);

            // Assert
            Assert.Equal(decryptedData.Text, Secret);
        }
Пример #18
0
        public void ExportToXmlFile_Should_ThrowException_IfPublicKeyFileExist()
        {
            // Arrange
            var          guid = Guid.NewGuid();
            var          file = $"{_assemblyPath}{guid}.xml";
            const string e    = "AQAB";
            const string m    = "z8FBNlJQrn4rEKhGlNvQDKgKDlHHOVu2hlWkP0pRrxTyp1/h/dJsBN4dfASY2A1"
                                + "r5KBCg1dySSNVFB5bJP9o9ob2GEL0dlbZtg0CiiWCwOFWBgakav3Va1+CUF6DbN"
                                + "g3gw2c/1WQaq73xB/WbKuLp5yk22HP/kVOUaG6H33Muv3s2/GxXClgnw8tOqLYbO"
                                + "A/tb9G9d0MIyhhEG/vOR8kkKrwZTeIECbT8vZl0B952leMKmoBN3AJVdnzmP43H"
                                + "Jvx28N0VJ0teV0emgOGnyhpNMB01KlTqd2Kc6Hls7AQbBJ/bkgmlnSdQA7vipig"
                                + "FKU19rhgMd4/95gBmTJOb71wfQ==";
            var key = new RsaPublicKey(e, m);

            key.ExportToXmlFile(file);

            // Act & Assert
            Assert.Throws <IOException>(() => key.ExportToXmlFile(file));
        }
        public IActionResult AddPublicKey([FromBody] RsaPublicKey theRsaPublicKey)
        {
            if (theRsaPublicKey == null)
            {
                throw new ArgumentNullException(nameof(theRsaPublicKey));
            }

            // initialize the dictionary of public keys using the server name and key
            if (!publicKeysByClient.ContainsKey(theRsaPublicKey.ClientName))
            {
                publicKeysByClient.Add(theRsaPublicKey.ClientName, theRsaPublicKey);
            }
            else
            {
                publicKeysByClient[theRsaPublicKey.ClientName] = theRsaPublicKey;
            }

            return(Ok($"Public Key added to the client {theRsaPublicKey.ClientName}!"));
        }
Пример #20
0
        public void Decrypt_Should_ReturnExpectedResult_When_KeyIsStoredInXml()
        {
            // Arrange
            const string publicKeyXml = "<RSAKeyValue>" +
                                        "<Modulus>0D59Km2Eo9oopcm7Y2wOXx0TRRXQFybl9HHe/ve47Qcf2EoKbs9nkuMmhCJlJ" +
                                        "zrq6ZJzgQSEbpVyaWn8OHq0I50rQ13dJsALEquhlfwVWw6Hit7qRvveKlOAGfj8xdkaXJ" +
                                        "LYS1tA06tKHfYxgt6ysMBZd0DIedYoE1fe3VlLZyE=</Modulus>" +
                                        "<Exponent>AQAB</Exponent>" +
                                        "</RSAKeyValue>";

            const string privateKeyXml = "<RSAKeyValue>" +
                                         "<Modulus>0D59Km2Eo9oopcm7Y2wOXx0TRRXQFybl9HHe/ve47Qcf2EoKbs9nkuMmhCJlJ" +
                                         "zrq6ZJzgQSEbpVyaWn8OHq0I50rQ13dJsALEquhlfwVWw6Hit7qRvveKlOAGfj8xdkaXJ" +
                                         "LYS1tA06tKHfYxgt6ysMBZd0DIedYoE1fe3VlLZyE=</Modulus>" +
                                         "<Exponent>AQAB</Exponent>" +
                                         "<P>/1cvDks8qlF1IXKNwcXW8tjTlhjidjGtbT9k7FCYug+P6ZBDfqhUqfvjgLFF" +
                                         "/+dAkoofNqliv89b8DRy4gS4qQ==</P>" +
                                         "<Q>0Mgq7lyvmVPR1r197wnba1bWbJt8W2Ki8ilUN6lX6Lkk04ds9y3A0txy0ESya7dyg" +
                                         "9NLscfU3NQMH8RRVnJtuQ==</Q>" +
                                         "<DP>+uwfRumyxSDlfSgInFqh/+YKD5+GtGXfKtO4hu4xF+8BGqJ1YXtkL" +
                                         "+Njz2zmADOt5hOr1tigPSQ2EhhIqUnAeQ==</DP>" +
                                         "<DQ>M5Ofd28SOjCIwCHjwG+Q8v1qzz3CBNljI6uuEGoXO3ix" +
                                         "bkggVRfKcMzg2C6AXTfeZE6Ifoy9OyhvLlHTPiXakQ==</DQ>" +
                                         "<InverseQ>yQIJMLdL6kU4VK7M5b5PqWS8XzkgxfnaowRs9mhSEDdwwWPtUXO8aQ9G3" +
                                         "zuiDUqNq9j5jkdt77+c2stBdV97ew==</InverseQ>" +
                                         "<D>HOpQXu/OFyJXuo2EY43BgRt8bX9V4aEZFRQqrqSfHOp8VYASasiJzS+VTYupGAVqUP" +
                                         "xw5V1HNkOyG0kIKJ+BG6BpIwLIbVKQn/ROs7E3/vBdg2+QXKhikMz/4gY" +
                                         "x2oEsXW2kzN1GMRop2lrrJZJNGE/eG6i4lQ1/inj1Tk/sqQE=</D>" +
                                         "</RSAKeyValue>";

            var publicKey  = new RsaPublicKey(publicKeyXml);
            var privateKey = new RsaPrivateKey(privateKeyXml);

            var e1 = new RsaEncryption();
            var e2 = new RsaEncryption();

            // Act
            var encryptedData = e1.Encrypt(new EncryptionData(Secret), publicKey);
            var decryptedData = e2.Decrypt(encryptedData, privateKey);

            // Assert
            Assert.Equal(decryptedData.Text, Secret);
        }
Пример #21
0
        public void Decrypt_Should_ReturnExpectedResult_When_KeyIsStoredInConfig()
        {
            // Arrange
            AddKeysToEnvironment();

            var publicKey  = RsaPublicKey.LoadFromEnvironment();
            var privateKey = RsaPrivateKey.LoadFromEnvironment();

            var e1 = new RsaEncryption();
            var e2 = new RsaEncryption();

            // Act
            var encryptedData = e1.Encrypt(new EncryptionData(Secret), publicKey);
            var decryptedData = e2.Decrypt(encryptedData, privateKey);

            // Assert
            Assert.Equal(decryptedData.Text, Secret);

            RemoveKeysToEnvironment();
        }
        private static byte[] RSAEncryptByteArray(byte[] plaintext, RsaPublicKey publicKey)
        {
            byte[] result = null;
            using (var rsa = RSA.Create())
            {
                RSAParameters rsaParameters = new RSAParameters();
                rsaParameters.Exponent = publicKey.Exponent;
                rsaParameters.Modulus  = publicKey.Modulus;
                rsa.ImportParameters(rsaParameters);

                if (plaintext.Count() > publicKey.Modulus.Length - 11)
                {
                    throw new Exception("The RSA message must be shorter than the length of the public key.");
                }

                result = rsa.Encrypt(plaintext, RSAEncryptionPadding.Pkcs1);
            }

            return(result);
        }
Пример #23
0
            /// <summary>
            /// Imports the X509 certificate.
            /// </summary>
            /// <param name="purpose">The purpose.</param>
            /// <param name="input">The input.</param>
            /// <returns></returns>
            public virtual ImportedKeySet X509Certificate(KeyPurpose purpose, Stream input)
            {
                var parser    = new X509CertificateParser();
                var cert      = parser.ReadCertificate(input);
                var bouncyKey = cert.GetPublicKey();

                Key key;

                if (bouncyKey is RsaKeyParameters)
                {
                    var keyParam = bouncyKey as RsaKeyParameters;
                    key = new RsaPublicKey
                    {
                        Modulus        = keyParam.Modulus.ToSystemBigInteger(),
                        PublicExponent = keyParam.Exponent.ToSystemBigInteger(),
                        Size           = keyParam.Modulus.BitLength,
                    };
                }
                else if (bouncyKey is DsaPublicKeyParameters)
                {
                    var keyParam = bouncyKey as DsaPublicKeyParameters;
                    if (KeyPurpose.Encrypt == purpose)
                    {
                        throw new InvalidKeySetException("DSA key cannot be used for encryption!");
                    }
                    key = new DsaPublicKey
                    {
                        Y    = keyParam.Y.ToSystemBigInteger(),
                        G    = keyParam.Parameters.G.ToSystemBigInteger(),
                        P    = keyParam.Parameters.P.ToSystemBigInteger(),
                        Q    = keyParam.Parameters.Q.ToSystemBigInteger(),
                        Size = keyParam.Parameters.P.BitLength
                    };
                }
                else
                {
                    throw new InvalidKeySetException("Unsupported key type!");
                }
                return(new ImportedKeySet(key, purpose, "imported from certificate"));
            }
Пример #24
0
        public ASymmetricEncryptionTests()
        {
            var fullPath      = Assembly.GetAssembly(typeof(ASymmetricEncryptionTests)).Location;
            var pathDirectory = Path.GetDirectoryName(fullPath);
            var separator     = Path.DirectorySeparatorChar;

            _assemblyPath = $"{pathDirectory}{separator}";

            _targetString = "Did you know that some of the most famous inventions would "
                            + "never have been made if the inventors had stopped at their "
                            + "first failure? For instance, Thomas Edison, inventor of "
                            + "the light bulb had 1,000 failed attempts at creating one "
                            + "light bulb that worked properly. - Vee Freir";

            _targetData = new EncryptionData(_targetString);

            _privateKey = RsaPrivateKey.LoadFromCertificateFile(
                $"{_assemblyPath}ASymmetricEncryption.pfx",
                "password");

            _publicKey = RsaPublicKey.LoadFromCertificateFile(
                $"{_assemblyPath}ASymmetricEncryption.pfx",
                "password");
        }
Пример #25
0
            /// <summary>
            /// Imports the X509 certificate.
            /// </summary>
            /// <param name="purpose">The purpose.</param>
            /// <param name="input">The input.</param>
            /// <returns></returns>
            public virtual ImportedKeySet X509Certificate(KeyPurpose purpose, Stream input)
            {
                var parser = new X509CertificateParser();
                var cert = parser.ReadCertificate(input);
                var bouncyKey = cert.GetPublicKey();

                Key key;
                if (bouncyKey is RsaKeyParameters)
                {
                    var keyParam = bouncyKey as RsaKeyParameters;
                    key = new RsaPublicKey
                              {
                                  Modulus = keyParam.Modulus.ToSystemBigInteger(),
                                  PublicExponent = keyParam.Exponent.ToSystemBigInteger(),
                                  Size = keyParam.Modulus.BitLength,
                              };
                }
                else if (bouncyKey is DsaPublicKeyParameters)
                {
                    var keyParam = bouncyKey as DsaPublicKeyParameters;
                    if (KeyPurpose.Encrypt == purpose)
                    {
                        throw new InvalidKeySetException("DSA key cannot be used for encryption!");
                    }
                    key = new DsaPublicKey
                              {
                                  Y = keyParam.Y.ToSystemBigInteger(),
                                  G = keyParam.Parameters.G.ToSystemBigInteger(),
                                  P = keyParam.Parameters.P.ToSystemBigInteger(),
                                  Q = keyParam.Parameters.Q.ToSystemBigInteger(),
                                  Size = keyParam.Parameters.P.BitLength
                              };
                }
                else
                {
                    throw new InvalidKeySetException("Unsupported key type!");
                }
                return new ImportedKeySet(key, purpose, "imported from certificate");
            }
Пример #26
0
        public IActionResult CreateReviewerAddressAsync([FromBody] CreateReviewerAddressRequest request)
        {
            Guard.NotNull(request, nameof(request));

            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                return(ModelStateErrors.BuildErrorResponse(this.ModelState));
            }

            try
            {
                // calculate the Manager password hash
                byte[] binaryPassword = System.Text.Encoding.ASCII.GetBytes(request.RsaPassword);

                Org.BouncyCastle.Crypto.Digests.Sha512Digest sha = new Org.BouncyCastle.Crypto.Digests.Sha512Digest();
                sha.BlockUpdate(binaryPassword, 0, binaryPassword.Length);

                byte[] shaOutput = new byte[512 / 8];
                sha.DoFinal(shaOutput, 0);

                NBitcoin.DataEncoders.HexEncoder he = new NBitcoin.DataEncoders.HexEncoder();
                string rsaPasswordHashHex           = he.EncodeData(shaOutput);

                // create the multisig address
                PubKey[] groupMemberKeys = request.SignaturePubKeys.Select(pubKeyHex => new PubKey(pubKeyHex)).ToArray();

                var scriptPubKey = PayToMultiSigTemplate
                                   .Instance
                                   .GenerateScriptPubKey(request.RequeiredSignatureCount, groupMemberKeys);

                PublicReviewerAddressModel model = new PublicReviewerAddressModel
                {
                    PublicApiUrl = request.PublicApiUrl
                };

                // check if the API is reachable and the address can be added to the watch list
                Uri apiRequestUri = new Uri(new Uri(model.PublicApiUrl), $"/api/WatchOnlyWallet/watch?address={scriptPubKey.Hash.GetAddress(this.network).ToString()}");
                try
                {
                    HttpWebRequest apiRequest = (HttpWebRequest)WebRequest.Create(apiRequestUri);

                    ASCIIEncoding encoding = new ASCIIEncoding();
                    string        postData = "";
                    byte[]        data     = encoding.GetBytes(postData);

                    apiRequest.Method        = "POST";
                    apiRequest.ContentType   = "application/x-www-form-urlencoded";
                    apiRequest.ContentLength = data.Length;

                    using (Stream stream = apiRequest.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }

                    HttpWebResponse apiResponse = (HttpWebResponse)apiRequest.GetResponse();

                    string responseString = new StreamReader(apiResponse.GetResponseStream()).ReadToEnd();

                    if (apiResponse.StatusCode != HttpStatusCode.OK)
                    {
                        throw new Exception($"The API request '{apiRequestUri.ToString()}' returned the status code '{apiResponse.StatusCode}'.");
                    }
                }
                catch (Exception e)
                {
                    throw new Exception($"The API request '{apiRequestUri.ToString()}' returned an error '{e.Message}'.");
                }


                // generate the RSA keypair for the address
                AsymmetricCipherKeyPair rsaKeyPair = GetRSAKeyPairFromSeed(request.RsaPassword + scriptPubKey.Hash.GetAddress(this.network).ToString());

                RsaKeyParameters rsaPublicKey = rsaKeyPair.Public as RsaKeyParameters;
                RsaPublicKey     pbk          = new RsaPublicKey()
                {
                    Exponent = rsaPublicKey.Exponent.ToByteArrayUnsigned(),
                    Modulus  = rsaPublicKey.Modulus.ToByteArrayUnsigned()
                };

                RsaPrivateCrtKeyParameters rsaPrivateKey = rsaKeyPair.Private as RsaPrivateCrtKeyParameters;
                RsaPrivateKey prk = new RsaPrivateKey()
                {
                    DP             = rsaPrivateKey.DP.ToByteArrayUnsigned(),
                    DQ             = rsaPrivateKey.DQ.ToByteArrayUnsigned(),
                    Exponent       = rsaPrivateKey.Exponent.ToByteArrayUnsigned(),
                    Modulus        = rsaPrivateKey.Modulus.ToByteArrayUnsigned(),
                    P              = rsaPrivateKey.P.ToByteArrayUnsigned(),
                    PublicExponent = rsaPrivateKey.PublicExponent.ToByteArrayUnsigned(),
                    Q              = rsaPrivateKey.Q.ToByteArrayUnsigned(),
                    QInv           = rsaPrivateKey.QInv.ToByteArrayUnsigned()
                };

                // return all the information we have
                model = new PublicReviewerAddressModel
                {
                    Network            = this.network.ToString(),
                    Address            = scriptPubKey.Hash.GetAddress(this.network).ToString(),
                    PublicName         = request.PublicName,
                    GroupName          = request.GroupName,
                    ValidFrom          = request.ValidFrom.ToString("o"),
                    ValidUntil         = request.ValidUntil.ToString("o"),
                    ScriptPubKeyHex    = scriptPubKey.ToHex(),
                    RsaPublicKeyHex    = pbk.ToHex(),
                    RsaPrivateKeyHex   = prk.ToHex(),
                    RsaPasswordHashHex = rsaPasswordHashHex,
                    PublicApiUrl       = request.PublicApiUrl
                };

                ((WalletManager)this.walletManager).AddReviewerAddressToReviewerStore(model);

                return(this.Json(model));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public const int MAX_MESSAGELENGTH_RELAY = 3 + 2 + 16 * 1024; //! bytes (+3 for OP_NOP OP_NOP OP_RETURN, +2 for the pushdata opcodes)

        public Script GenerateScriptPubKey(string message, string messageRecipient, string replyToAddress, string rewardAddress, bool encryptMessage, RsaPublicKey publicKey, RsaPrivateKey privateKey)
        {
            byte[] pushData = null;

            var wsm = new WantedSystemMessage()
            {
                Encryption = (encryptMessage ? MessageEncryption.RSA4096AES256 : MessageEncryption.None),
                Text       = message,
                Metadata   = new WantedSystemMessageMetadata()
                {
                    CreationTimeUtc  = DateTime.UtcNow.ToString(),
                    RecipientAddress = messageRecipient,
                    ReplyToAddress   = replyToAddress,
                    RewardAddress    = rewardAddress
                }
            };

            if (encryptMessage)
            {
                pushData = GenerateWantedSystemMessagePushData(wsm, publicKey);
            }
            else
            {
                pushData = GenerateWantedSystemMessagePushData(wsm);
            }

            return(GenerateScriptPubKey(pushData));
        }
Пример #28
0
 public void LoadFromXmlFile_Should_ThrowException_When_FileDoesNotExists()
 {
     // Assert
     Assert.Throws <ArgumentException>(()
                                       => RsaPublicKey.LoadFromXmlFile($"{_assemblyPath}nonexist.xml"));
 }
        private byte[] GenerateWantedSystemMessagePushData(WantedSystemMessage message, RsaPublicKey publicKey = null)
        {
            byte[] encryptionKey = new byte[0];

            string metadata = JsonConvert.SerializeObject(message.Metadata);

            byte[] uncompressedMetadata = System.Text.Encoding.UTF8.GetBytes(metadata);
            byte[] compressedMetadata   = GZIPCompressByteArray(uncompressedMetadata);

            byte[] uncompressedMessage = System.Text.Encoding.UTF8.GetBytes(message.Text);
            if (message.Encryption == MessageEncryption.RSA4096AES256)
            {
                byte[] aesKey = GetRandomData(256);

                encryptionKey = RSAEncryptByteArray(aesKey, publicKey);
                byte[] encryptedMessage = AESEncryptByteArray(uncompressedMessage, aesKey);

                uncompressedMessage = encryptedMessage;
            }
            byte[] compressedMessage = GZIPCompressByteArray(uncompressedMessage);

            byte[] header              = System.Text.Encoding.UTF8.GetBytes("TWS");
            byte   version             = (byte)message.Version;
            byte   compression         = (byte)message.Compression;
            byte   checksumType        = (byte)message.ChecksumType;
            byte   encryptionType      = (byte)message.Encryption;
            ushort encryptionKeyLength = (ushort)encryptionKey.Length;
            ushort metadataLength      = (ushort)compressedMetadata.Length;
            ushort messageLength       = (ushort)compressedMessage.Length;

            List <byte> pushDataList = new List <byte>();

            pushDataList.AddRange(header);
            pushDataList.Add(version);
            pushDataList.Add(compression);
            pushDataList.Add(checksumType);
            pushDataList.Add(encryptionType);
            pushDataList.AddRange(BitConverter.GetBytes(encryptionKeyLength));
            pushDataList.AddRange(BitConverter.GetBytes(metadataLength));
            pushDataList.AddRange(BitConverter.GetBytes(messageLength));
            pushDataList.AddRange(encryptionKey);
            pushDataList.AddRange(compressedMetadata);
            pushDataList.AddRange(compressedMessage);

            if (pushDataList.Count > 16 * 1024)
            {
                throw new Exception("Push data can't be bigger than 16 kbytes.");
            }

            return(pushDataList.ToArray());
        }
Пример #30
0
 public void LoadFromConfig_Should_ThrowExceptionWhenConfigAppSettingsEmpty() =>
 Assert.Throws <ArgumentException>(() => RsaPublicKey.LoadFromEnvironment());
Пример #31
0
        /// <summary>
        /// Impland a message as PushData into a transaction
        /// </summary>
        /// <returns></returns>
        public TransactionBuilder SendMessage(string message, string messageRecipient, string replyToAddress, string rewardAddress, RsaPublicKey publicKey = null, RsaPrivateKey privateKey = null)
        {
            var output = new TxOut()
            {
                ScriptPubKey = WantedSystemMessageTemplate.Instance.GenerateScriptPubKey(message, messageRecipient, replyToAddress, rewardAddress, (publicKey != null), publicKey, privateKey)
            };

            // change the txout's value dynamically to the smallest amount (the dust threshold)
            output.Value = output.GetDustThreshold(this.StandardTransactionPolicy.MinRelayTxFee);

            var builder = new SendMessageBuilder(output);

            this.CurrentGroup.Builders.Add(builder.Build);
            return(this);
        }
Пример #32
0
        public static byte[] RsaEncrypt(byte[] clearData, RsaPublicKey key)
        {
            Argument.ValidateIsNotNull(clearData, "clearData");
            Argument.ValidateIsNotNull(key, "key");

            // RSA works with integers, not bytes, so transform the bytes into an integer.

            var clearInteger = BytesToBigInteger(clearData);

            // It's as simple as that: c = (s**e) mod n
            var encryptedInteger = BigInteger.ModPow(clearInteger, key.E, key.N);

            return BigIntegerToBytes(encryptedInteger);
        }