public IContentResponse HandlePasswordSet(NameValueCollection headers, Stream inputStream)
        {
            INameValueStore store = new RegistryStorage(Settings.RegistryPath);
                
            int contentLen = int.Parse(headers["Content-Length"]);
            if (contentLen == 0)
            {
                using (RSAPrivateKey _temporaryKey = new RSAPrivateKey(2048))
                {
                    store.Write("Transfers", "temp-key", Convert.ToBase64String(_temporaryKey.ToArray()));
                    return new DynamicResponse("application/public-key", _temporaryKey.PublicKey.ToArray());
                }
            }

            string tempkey;
            if (contentLen <= 2048 && store.Read("Transfers", "temp-key", out tempkey))
            {
                byte[] bytes = IOStream.Read(inputStream, contentLen);
                using (RSAPrivateKey _temporaryKey = RSAPrivateKey.FromBytes(Convert.FromBase64String(tempkey)))
                    bytes = _temporaryKey.Decrypt(bytes);

                _content.KeyPair.SetServerPassword(bytes);
            }
            return DynamicResponse.Empty;
        }
            public Stream ToStream(RSAPrivateKey signingKey)
            {
                if (ReferenceEquals(EmptyMessage, this))
                {
                    return(Stream.Null);
                }

                // Next version's data-length
                Write(0);

                byte[] signature = signingKey.SignHash(_hash.FinalizeHash());
                PrimitiveSerializer.Bytes.WriteTo(signature, _payload);
                //_verified = true;

                _hash.Close();
                _payload.Close();
                _protected.Position = 0;

                MemoryStream header = new MemoryStream();

                WriteHeader(header);
                header.Position = 0;

                return(new CombinedStream(header, _protected));
            }
            public Message(Stream input, RSAPrivateKey key, Converter <Guid, Salt> sessionSecret)
            {
                (_protected = new MemoryStream(0)).Dispose();
                _hash    = new HashStream(new SHA256Managed(), input);
                _payload = input;

                ReadHeader(_hash, out _version, out _state, out _transferId, out _salt);

                Salt secret;

                if (!UsesSessionKey)
                {
                    // Begin private key decryption
                    _payload = key.Decrypt(input);
                    _hash.ChangeStream(_payload);
                    // Decrypt the aes key used in this package
                    byte[] keybits = IOStream.Read(_hash, 32);
                    secret = Salt.FromBytes(keybits);
                }
                else
                {
                    secret = sessionSecret(_transferId);
                    Check.IsEqual(32, Check.NotNull(secret).Length);
                }

                AESCryptoKey sessionKey = new AESCryptoKey(
                    // Prefix the key with the message's salt and compute a SHA256 hash to be used as the key
                    Hash.SHA256(_salt.GetData(secret.ToArray()).ToStream()).ToArray(),
                    // Compute an IV for this aes key and salt combination
                    IV(secret, _salt)
                    );

                _payload = sessionKey.Decrypt(_payload);
                _hash.ChangeStream(_payload);
            }
 /// <summary>
 /// Constructed to send one or more files to a remove server identified by serverKey.  The transfer
 /// is a blocking call and returns on success or raises an exception.  If Abort() is called durring
 /// the transfer, or if a ProgressChanged event handler raises the OperationCanceledException, the
 /// transfer is silently terminated.
 /// </summary>
 /// <param name="privateKey">The private key for this client</param>
 /// <param name="serverKey">The public key of the server</param>
 /// <param name="sendMessage">A delegate to transfer data to the server and obtain a response</param>
 public Client(RSAPrivateKey privateKey, RSAPublicKey serverKey, TransmitMessageAction sendMessage)
 {
     _privateKey  = Check.NotNull(privateKey);
     _publicKey   = Check.NotNull(serverKey);
     _sendMessage = Check.NotNull(sendMessage);
     _abort       = new ManualResetEvent(false);
     LimitThreads = 10;
 }
 /// <summary>
 /// Constructed to send one or more files to a remove server identified by serverKey.  The transfer
 /// is a blocking call and returns on success or raises an exception.  If Abort() is called durring
 /// the transfer, or if a ProgressChanged event handler raises the OperationCanceledException, the
 /// transfer is silently terminated.
 /// </summary>
 /// <param name="privateKey">The private key for this client</param>
 /// <param name="serverKey">The public key of the server</param>
 /// <param name="sendMessage">A delegate to transfer data to the server and obtain a response</param>
 public Client(RSAPrivateKey privateKey, RSAPublicKey serverKey, TransmitMessageAction sendMessage)
 {
     _privateKey = Check.NotNull(privateKey);
     _publicKey = Check.NotNull(serverKey);
     _sendMessage = Check.NotNull(sendMessage);
     _abort = new ManualResetEvent(false);
     LimitThreads = 10;
 }
            /// <summary>
            /// Constructs/reconstructs the server-side receiver to process one or more messages.  This class
            /// maintains all state in the INameValueStore so it may be destroyed between requests, or there
            /// may be multiple instances handling requests, provided that all instances have access to the
            /// underlying storage provided by the INameValueStore instance.
            /// </summary>
            /// <param name="privateKey">The private key used for this server</param>
            /// <param name="clientKey">The public key of the client to allow</param>
            /// <param name="storage">The state storage used between requests</param>
            public Server(RSAPrivateKey privateKey, RSAPublicKey clientKey, INameValueStore storage)
            {
                _privateKey = privateKey;
                _clientKey  = clientKey;
                _storage    = storage;

                NonceSize            = 32;
                KeyBytes             = 32;
                MaxInboundFileChunk  = ushort.MaxValue;
                MaxOutboundFileChunk = 1000 * 1024;
            }
示例#7
0
        public void TestPrivateKeyExport()
        {
            RSAPrivateKey pk = new RSAPrivateKey();
            string xml = pk.ToXml();

            RSAPrivateKey copy = RSAPrivateKey.FromXml(xml);
            Assert.AreEqual(xml, copy.ToXml());

            byte[] bytes = pk.ToArray();
            Assert.AreEqual(596, bytes.Length);

            copy = RSAPrivateKey.FromBytes(bytes);
            Assert.AreEqual(bytes, copy.ToArray());

            copy = RSAPrivateKey.FromParameters(pk.ExportParameters());
            Assert.AreEqual(bytes, copy.ToArray());
        }
            public Stream ToStream(RSAPrivateKey signingKey)
            {
                if (ReferenceEquals(EmptyMessage, this))
                    return Stream.Null;

                // Next version's data-length
                Write(0);

                byte[] signature = signingKey.SignHash(_hash.FinalizeHash());
                PrimitiveSerializer.Bytes.WriteTo(signature, _payload);
                //_verified = true;

                _hash.Close();
                _payload.Close();
                _protected.Position = 0;

                MemoryStream header = new MemoryStream();
                WriteHeader(header);
                header.Position = 0;

                return new CombinedStream(header, _protected);
            }
            public Message(Stream input, RSAPrivateKey key, Converter<Guid, Salt> sessionSecret)
            {
                (_protected = new MemoryStream(0)).Dispose();
                _hash = new HashStream(new SHA256Managed(), input);
                _payload = input;

                ReadHeader(_hash, out _version, out _state, out _transferId, out _salt);
                
                Salt secret;
                if (!UsesSessionKey)
                {
                    // Begin private key decryption
                    _payload = key.Decrypt(input);
                    _hash.ChangeStream(_payload);
                    // Decrypt the aes key used in this package
                    byte[] keybits = IOStream.Read(_hash, 32);
                    secret = Salt.FromBytes(keybits);
                }
                else
                {
                    secret = sessionSecret(_transferId);
                    Check.IsEqual(32, Check.NotNull(secret).Length);
                }

                AESCryptoKey sessionKey = new AESCryptoKey(
                    // Prefix the key with the message's salt and compute a SHA256 hash to be used as the key
                    Hash.SHA256(_salt.GetData(secret.ToArray()).ToStream()).ToArray(),
                    // Compute an IV for this aes key and salt combination
                    IV(secret, _salt)
                );
                
                _payload = sessionKey.Decrypt(_payload);
                _hash.ChangeStream(_payload);
            }
示例#10
0
        public void TestSignAndVerifyHash()
        {
            byte[] data = new byte[100];
            new Random().NextBytes(data);

            foreach (HashAlgorithm ha in new HashAlgorithm[] { MD5.Create(), SHA1.Create(), SHA256.Create(), SHA384.Create(), SHA512.Create() })
            {
                Hash hash = Hash.FromBytes(ha.ComputeHash(data));
                Assert.AreEqual(CryptoConfig.MapNameToOID(ha.GetType().FullName), hash.AlgorithmOID);

                using (RSAPrivateKey key = new RSAPrivateKey())
                {
                    byte[] sig = key.SignHash(hash);

                    using (RSAPublicKey pub = key.PublicKey)
                    {
                        Assert.IsTrue(pub.VerifyHash(sig, Hash.FromBytes(ha.ComputeHash(data))));
                        data[0] = (byte)~data[0];
                        Assert.IsFalse(pub.VerifyHash(sig, Hash.FromBytes(ha.ComputeHash(data))));
                    }
                }
            }
        }
示例#11
0
        public void TestKeyStoreAddRemove()
        {
            string keyname = this.GetType().FullName + ".TestKeyCreateAndDelete";
            using (RSAPrivateKey key = new RSAPrivateKey())
            {
                Assert.IsFalse(key.DeleteFromStore());

                key.WriteToStore(keyname);

				CspParameters cp = new CspParameters();
				cp.KeyContainerName = keyname;
				cp.Flags = CspProviderFlags.UseExistingKey;

				using (RSAPrivateKey key2 = RSAPrivateKey.FromStore(cp))
					Assert.AreEqual(key.ToXml(), key2.ToXml());

				using (RSAPrivateKey key2 = RSAPrivateKey.FromStore(keyname))
                {
                    Assert.AreEqual(key.ToXml(), key2.ToXml());
                    Assert.IsTrue(key2.DeleteFromStore());
                    key2.Dispose();
                }
            }
        }
示例#12
0
        public void TestPKICertificate()
        {
            byte[] rawdata = new byte[8001];
            new Random().NextBytes(rawdata);

            byte[] cypher;
            using (RSAPublicKey publicKey = new RSAPublicKey(TestCertPublicKey()))
                cypher = publicKey.Encrypt(rawdata);

            using (RSAPrivateKey privateKey = new RSAPrivateKey(TestCertPrivateKey()))
                Assert.AreEqual(rawdata, privateKey.Decrypt(cypher));
        }
            /// <summary>
            /// Constructs/reconstructs the server-side receiver to process one or more messages.  This class 
            /// maintains all state in the INameValueStore so it may be destroyed between requests, or there 
            /// may be multiple instances handling requests, provided that all instances have access to the
            /// underlying storage provided by the INameValueStore instance.
            /// </summary>
            /// <param name="privateKey">The private key used for this server</param>
            /// <param name="clientKey">The public key of the client to allow</param>
            /// <param name="storage">The state storage used between requests</param>
            public Server(RSAPrivateKey privateKey, RSAPublicKey clientKey, INameValueStore storage)
            {
                _privateKey = privateKey;
                _clientKey = clientKey;
                _storage = storage;

                NonceSize = 32;
                KeyBytes = 32;
                MaxInboundFileChunk = ushort.MaxValue;
                MaxOutboundFileChunk = 1000*1024;
            }
示例#14
0
 /// <summary> Creates the key from the information provided </summary>
 public new static RSAPrivateKey FromXml(string xml)
 {
     return(RSAPrivateKey.FromXml(new XmlTextReader(new StringReader(xml))));
 }