예제 #1
0
        private static void InitializeEncryption()
        {
            if (ENC_ECDCrypto == null || DEC_ECDCrypto == null)
            {
                ENC_ECDCrypto = new ECDiffieHellmanCng
                {
                    KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash,
                    HashAlgorithm         = CngAlgorithm.Sha256
                };
                ENCpublicKey = ENC_ECDCrypto.PublicKey.ToByteArray();

                DEC_ECDCrypto = new ECDiffieHellmanCng
                {
                    KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash,
                    HashAlgorithm         = CngAlgorithm.Sha256
                };
                DECpublicKey = DEC_ECDCrypto.PublicKey.ToByteArray();

                ENCprivateKey = ENC_ECDCrypto.DeriveKeyMaterial(CngKey.Import(DECpublicKey, CngKeyBlobFormat.EccPublicBlob));
                DECprivateKey = DEC_ECDCrypto.DeriveKeyMaterial(CngKey.Import(ENCpublicKey, CngKeyBlobFormat.EccPublicBlob));
            }
        }
예제 #2
0
        static internal byte[] PerformAssymetricKeyExchangeUsingECDiffieHellmanOnSocket(System.Net.Sockets.Socket socket)
        {
            using (ECDiffieHellmanCng ECDiffieHellmanCngobj = new ECDiffieHellmanCng()) {
                ECDiffieHellmanCngobj.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
                ECDiffieHellmanCngobj.HashAlgorithm         = CngAlgorithm.Sha256;
                byte[] _myPublicKey    = ECDiffieHellmanCngobj.PublicKey.ToByteArray();
                byte[] _otherPublicKey = new byte[140];

                if (NetworkCommunicationManagers.SendByteArrayOverSocket(socket, _myPublicKey) == false)
                {
                    return(null);
                }
                ;
                if (NetworkCommunicationManagers.ReceiveByteArrayOverSocket(socket, out _otherPublicKey, 140) == false)
                {
                    return(null);
                }
                ;

                return(ECDiffieHellmanCngobj.DeriveKeyMaterial(CngKey.Import(_otherPublicKey, CngKeyBlobFormat.EccPublicBlob)));
            }
        }
예제 #3
0
        private byte [] AliceSendData(string message)
        {
            Console.WriteLine("Alice message: {0}", message);

            byte[] rawData = Encoding.UTF8.GetBytes(message);
            byte[] encData = null;

            //Get alice's algorithm (use alice keys)
            ECDiffieHellmanCng aliceAlg = new ECDiffieHellmanCng(aliceKey);

            using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
            {
                //Create symmetric key - using alice's keys and bob's public key
                byte[] symKey = aliceAlg.DeriveKeyMaterial(bobPubKey);

                //Provider for data encryption
                AesCryptoServiceProvider acsp = new AesCryptoServiceProvider();
                acsp.Key = symKey;
                acsp.GenerateIV();

                using (ICryptoTransform encryptor = acsp.CreateEncryptor())
                    using (MemoryStream ms = new MemoryStream())
                    {
                        //Create crypto stream
                        CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
                        //Send initial vector
                        ms.Write(acsp.IV, 0, acsp.IV.Length);
                        //Send encrypted data
                        cs.Write(rawData, 0, rawData.Length);
                        //Important thing!
                        cs.Close();
                        encData = ms.ToArray();
                    }
                acsp.Clear();
            }

            Console.WriteLine("Alice cipher: {0}", Convert.ToBase64String(encData));
            return(encData);
        }
예제 #4
0
        public static void Test()
        {
            ECDiffieHellmanCng alice = new ECDiffieHellmanCng();

            alice.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            alice.HashAlgorithm         = CngAlgorithm.Sha1;


            ECDiffieHellmanCng bob = new ECDiffieHellmanCng();

            bob.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            bob.HashAlgorithm         = CngAlgorithm.Sha1;



            byte[] aliceKey = alice.DeriveKeyMaterial(bob.PublicKey);
            byte[] bobKey   = bob.DeriveKeyMaterial(alice.PublicKey);


            Console.WriteLine(bobKey.SequenceEqual(aliceKey));

            var r = new RijndaelManaged();

            r.GenerateIV();
            var iv = r.IV;

            byte[] encrypted = SymmetricAlgorithmTest.Encrypt <RijndaelManaged>(original, bobKey, iv);
            string roundtrip = SymmetricAlgorithmTest.Decrypt <RijndaelManaged>(encrypted, aliceKey, iv);
            string hex       = Epic.Converters.HexString.Encode(encrypted);
            string base64    = Convert.ToBase64String(encrypted);

            //Display the original data and the decrypted data.
            Console.WriteLine($"ECC:");
            Console.WriteLine("Byte:   {0}", encrypted.Length);
            Console.WriteLine("Hex:   {0}, {1}", hex.Length, hex);
            Console.WriteLine("Base64:   {0}, {1}", base64.Length, base64);
            Console.WriteLine("Decode: {0}", roundtrip);
            Console.WriteLine();
        }
예제 #5
0
        public static void Equivalence_Hmac(HashAlgorithmName algorithm, bool useSecretAgreementAsHmac, bool prepend, bool append)
        {
            using (ECDiffieHellmanCng ecdh = NewDefaultECDHCng())
                using (ECDiffieHellmanPublicKey publicKey = ecdh.PublicKey)
                {
                    byte[] secretPrepend = prepend ? new byte[3] : null;
                    byte[] secretAppend  = append ? new byte[4] : null;
                    byte[] hmacKey       = useSecretAgreementAsHmac ? null : new byte[12];

                    byte[] newWay = ecdh.DeriveKeyFromHmac(publicKey, algorithm, hmacKey, secretPrepend, secretAppend);

                    ecdh.HashAlgorithm         = new CngAlgorithm(algorithm.Name);
                    ecdh.HmacKey               = hmacKey;
                    ecdh.SecretPrepend         = secretPrepend;
                    ecdh.SecretAppend          = secretAppend;
                    ecdh.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hmac;

                    byte[] oldWay = ecdh.DeriveKeyMaterial(publicKey);

                    Assert.Equal(newWay, oldWay);
                }
        }
        // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache.
        internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter)
        {
            sqlEnclaveSession = null;
            counter           = 0;
            try
            {
                ThreadRetryCache.Remove(Thread.CurrentThread.ManagedThreadId.ToString());
                sqlEnclaveSession = GetEnclaveSessionFromCache(enclaveSessionParameters, out counter);
                if (sqlEnclaveSession == null)
                {
                    if (!string.IsNullOrEmpty(enclaveSessionParameters.AttestationUrl))
                    {
                        // Deserialize the payload
                        AttestationInfo info = new AttestationInfo(attestationInfo);

                        // Verify enclave policy matches expected policy
                        VerifyEnclavePolicy(info.EnclaveReportPackage);

                        // Perform Attestation per VSM protocol
                        VerifyAttestationInfo(enclaveSessionParameters.AttestationUrl, info.HealthReport, info.EnclaveReportPackage);

                        // Set up shared secret and validate signature
                        byte[] sharedSecret = GetSharedSecret(info.Identity, info.EnclaveDHInfo, clientDHKey);

                        // add session to cache
                        sqlEnclaveSession = AddEnclaveSessionToCache(enclaveSessionParameters, sharedSecret, info.SessionId, out counter);
                    }
                    else
                    {
                        throw new AlwaysEncryptedAttestationException(Strings.FailToCreateEnclaveSession);
                    }
                }
            }
            finally
            {
                UpdateEnclaveSessionLockStatus(sqlEnclaveSession);
            }
        }
        // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache.
        public override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, string attestationUrl, string servername, out SqlEnclaveSession sqlEnclaveSession, out long counter)
        {
            sqlEnclaveSession = null;
            counter           = 0;
            try
            {
                AttestationInfoCacheItem attestationInfoCacheItem = AttestationInfoCache.Remove(Thread.CurrentThread.ManagedThreadId.ToString()) as AttestationInfoCacheItem;
                sqlEnclaveSession = GetEnclaveSessionFromCache(servername, attestationUrl, out counter);
                if (sqlEnclaveSession == null)
                {
                    if (attestationInfoCacheItem != null)
                    {
                        // Deserialize the payload
                        AttestationInfo info = new AttestationInfo(attestationInfo);

                        // Verify enclave policy matches expected policy
                        VerifyEnclavePolicy(info.EnclaveReportPackage);

                        // Perform Attestation per VSM protocol
                        VerifyAttestationInfo(attestationUrl, info.HealthReport, info.EnclaveReportPackage);

                        // Set up shared secret and validate signature
                        byte[] sharedSecret = GetSharedSecret(info.Identity, info.EnclaveDHInfo, clientDHKey);

                        // add session to cache
                        sqlEnclaveSession = AddEnclaveSessionToCache(attestationUrl, servername, sharedSecret, info.SessionId, out counter);
                    }
                    else
                    {
                        throw new AlwaysEncryptedAttestationException(SR.FailToCreateEnclaveSession);
                    }
                }
            }
            finally
            {
                UpdateEnclaveSessionLockStatus(sqlEnclaveSession);
            }
        }
        private async Task <byte[]> AliceSendsDataAsync(string message)
        {
            WriteLine($"Alice sends message: {message}");
            byte[] rawData       = Encoding.UTF8.GetBytes(message);
            byte[] encryptedData = null;

            using (var aliceAlgorithm = new ECDiffieHellmanCng(_aliceKey))
                using (CngKey bobPubKey = CngKey.Import(_bobPubKeyBlob,
                                                        CngKeyBlobFormat.EccPublicBlob))
                {
                    byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey);
                    WriteLine("Alice creates this symmetric key with " +
                              $"Bobs public key information: { Convert.ToBase64String(symmKey)}");

                    using (var aes = new AesCryptoServiceProvider())
                    {
                        aes.Key = symmKey;
                        aes.GenerateIV();
                        using (ICryptoTransform encryptor = aes.CreateEncryptor())
                            using (var ms = new MemoryStream())
                            {
                                // create CryptoStream and encrypt data to send
                                using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                                {
                                    // write initialization vector not encrypted
                                    await ms.WriteAsync(aes.IV, 0, aes.IV.Length);

                                    await cs.WriteAsync(rawData, 0, rawData.Length);
                                }
                                encryptedData = ms.ToArray();
                            }
                        aes.Clear();
                    }
                }
            WriteLine($"Alice: message is encrypted: {Convert.ToBase64String(encryptedData)}");;
            WriteLine();
            return(encryptedData);
        }
예제 #9
0
        protected void Construct(Socket handler)
        {
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }

            if (!handler.Connected)
            {
                throw new ArgumentException("Socket should be connected.");
            }

            _handler = handler;

            _received      = new MemoryStream();
            _buffer        = new byte[BufferSize];
            _packer        = new Packer();
            _diffieHellman = new ECDiffieHellmanCng(KeySize);
            _diffieHellman.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            _diffieHellman.HashAlgorithm         = CngAlgorithm.Sha256;

            _handler.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, OnReceive, null);
        }
예제 #10
0
파일: Connection.cs 프로젝트: zeud/TCPChat
        protected void Construct(Socket socket)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }

            if (!socket.Connected)
            {
                throw new ArgumentException("Socket should be connected.");
            }

            handler  = socket;
            buffer   = new byte[BufferSize];
            received = new MemoryStream();
            packer   = new Packer();

            diffieHellman = new ECDiffieHellmanCng(KeySize);
            diffieHellman.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            diffieHellman.HashAlgorithm         = CngAlgorithm.Sha256;

            handler.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, OnReceive, null);
        }
예제 #11
0
        public (byte[] PublicKey, byte[] PrivateKey) GenerateKeys()
        {
            if (OperatingSystem.IsWindows())
            {
                using (ECDiffieHellmanCng ECD = new ECDiffieHellmanCng(KeySize))
                {
                    var x = ECD.ExportParameters(true);

                    ECD.KeyDerivationFunction = ECDHKDF;

                    ECD.HashAlgorithm = HashingAlgorithm;

                    return(
                        ECD.PublicKey.ToByteArray(),
                        ECD.ExportECPrivateKey()
                        );
                }
            }
            else
            {
                throw new NotSupportedException();
            }
        }
예제 #12
0
        public void TestCngGeneratP256PublicKeysWithBigEndianEncoding()
        {
            ECDiffieHellmanCng aliceCng = new ECDiffieHellmanCng(256)
            {
                HashAlgorithm         = CngAlgorithm.Sha256,
                KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash
            };

            byte[] alicePubKeyBlob = aliceCng.Key.Export(CngKeyBlobFormat.EccPublicBlob);
            Assert.AreEqual(2 * 32 + 8, alicePubKeyBlob.Length);

            var keyType = new byte[] { 0x45, 0x43, 0x4b, 0x31 };
            var keyLength = new byte[] { 0x20, 0x00, 0x00, 0x00 };
            var keyTypeAndLength = new[] { keyType, keyLength }.SelectMany(l => l).ToArray();
            var startOfKey = alicePubKeyBlob.Where((b, i) => i < 8).ToArray();

            Assert.IsTrue(keyTypeAndLength.SequenceEqual(startOfKey));

            byte[] aliceElipticCoordinates = new byte[64];
            Array.Copy(alicePubKeyBlob, 8, aliceElipticCoordinates, 0, aliceElipticCoordinates.Length);

            EllipticCurveHelper.TestKeyBelongsToP256(aliceElipticCoordinates);
        }
예제 #13
0
        private void GenerateKeys()
        {
            using (ECDiffieHellmanCng ecd1 = new ECDiffieHellmanCng())
            {
                ecd1.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
                ecd1.HashAlgorithm         = CngAlgorithm.Sha256;
                person1PublicKey           = ecd1.PublicKey.ToByteArray();
                txt_Kul_1_Public_Key.Text  = Convert.ToBase64String(person1PublicKey);

                /* 2. kişi tarafındaki işlemler, 1. kişinin açık anahtarı biliniyor. */
                using (ECDiffieHellmanCng ecd2 = new ECDiffieHellmanCng())
                {
                    ecd2.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
                    ecd2.HashAlgorithm         = CngAlgorithm.Sha256;

                    person2PublicKey          = ecd2.PublicKey.ToByteArray();
                    txt_Kul_2_Public_Key.Text = Convert.ToBase64String(person2PublicKey);

                    commonKey = ecd2.DeriveKeyMaterial(CngKey.Import(person1PublicKey, CngKeyBlobFormat.EccPublicBlob));
                    txt_Ortak_Anahtar.Text = Convert.ToBase64String(commonKey);
                }
            }
        }
예제 #14
0
        protected override void Read(BinaryReader reader)
        {
            base.Read(reader);

            _parentID = reader.ReadInt32();
            _name     = reader.ReadSrfsString();

            KeyThumbprint encryptionKeyThumbprint = reader.ReadKeyThumbprint();

            if (!encryptionKeyThumbprint.Equals(_decryptionKey.Thumbprint))
            {
                throw new System.IO.IOException();
            }

            CngKey publicSourceKey = reader.ReadPublicKey().Key;

            reader.ReadBytes(PaddingLength);
            byte[] encryptedData = reader.ReadBytes(_plainTextData.Length);

            using (ECDiffieHellmanCng destinationKey = new ECDiffieHellmanCng(_decryptionKey.Key)) {
                _plainTextData = Decrypt(destinationKey, publicSourceKey, encryptedData, 0, encryptedData.Length);
            }
        }
        private void Listen()
        {
            if (Proxy == null)
            {
                Proxy = new Publisher(PrivateSpace, Space, ConcealedSpace);
            }
            Proxy.Running = true;
            while (true)
            {
                var request     = Space.Get("Request", typeof(HubRequestType), typeof(string), typeof(string));
                var identifier  = request.Get <string>(2);
                var requestType = request.Get <HubRequestType>(1);
                var secret      = request.Get <string>(3);

                if (requestType == HubRequestType.EstablishSession)
                {
                    var t = PrivateSpace.QueryP("SessionSecret", typeof(string), identifier);
                    if (t != null)
                    {
                        PrivateSpace.GetAll("SessionSecret", typeof(string), identifier);
                    }
                    using (var me = new ECDiffieHellmanCng())
                    {
                        var herKey = CngKey.Import(Convert.FromBase64String(secret), CngKeyBlobFormat.EccPublicBlob);
                        var ourKey = Convert.ToBase64String(me.DeriveKeyMaterial(herKey));
                        PrivateSpace.Put("SessionSecret", ourKey, identifier);
                        var myKey = Convert.ToBase64String(me.PublicKey.ToByteArray());
                        Space.Put("Response", identifier, HubRequestType.EstablishSession, myKey);
                    }
                    Proxy.SyncIncomingUser(identifier);
                }
                else if (requestType == HubRequestType.TerminateSession)
                {
                    PrivateSpace.GetP("SessionSecret", typeof(string), identifier);
                }
            }
        }
예제 #16
0
        /*Bob receives encrypted data in the argument of the method BobReceivesData() . First, the
         * unencrypted initialization vector must be read. The BlockSize property of the class
         * AesCryptoServiceProvider returns the number of bits for a block. The number of bytes can be
         * calculated by doing a divide by 8, and the fastest way to do this is by doing a bit shift of 3 bits. Shifting
         * by 1 bit is a division by 2, 2 bits by 4, and 3 bits by 8. With the for loop, the first bytes of the raw bytes
         * that contain the IV unencrypted are written to the array iv . Next, an ECDiffieHellmanCng object is
         * instantiated with the key pair from Bob. Using the public key from Alice, the symmetric key is returned
         * from the method DeriveKeyMaterial() . Comparing the symmetric keys created from Alice and Bob
         * shows that the same key value gets created. Using this symmetric key and the initialization vector, the
         * message from Alice can be decrypted with the AesCryptoServiceProvider class.
         */
        private static void BobReceivesData(byte[] encryptedData)
        {
            ReturnString += String.Format("\n\nBob receives encrypted data");
            byte[] rawData = null;
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            int nBytes = aes.BlockSize >> 3;

            byte[] iv = new byte[nBytes];
            for (int i = 0; i < iv.Length; i++)
            {
                iv[i] = encryptedData[i];
            }
            ECDiffieHellmanCng bobAlgorithm = new ECDiffieHellmanCng(bobKey);

            using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob,
                                                      CngKeyBlobFormat.EccPublicBlob))
            {
                byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey);
                ReturnString += String.Format("\nBob creates this symmetric key with " +
                                              "Alice's public key information: {0}",
                                              Convert.ToBase64String(symmKey));
                aes.Key = symmKey;
                aes.IV  = iv;
                using (ICryptoTransform decryptor = aes.CreateDecryptor())
                    using (MemoryStream ms = new MemoryStream())
                    {
                        CryptoStream cs = new CryptoStream(ms, decryptor,
                                                           CryptoStreamMode.Write);
                        cs.Write(encryptedData, nBytes, encryptedData.Length - nBytes);
                        cs.Close();
                        rawData       = ms.ToArray();
                        ReturnString += String.Format("\nBob decrypts message to: {0}",
                                                      Encoding.UTF8.GetString(rawData));
                    }
                aes.Clear();
            }
        }
예제 #17
0
        public static void SendLoginRequest(LoginArgsContainer Args)
        {
            PacketStream InitialPacket = new PacketStream((byte)PacketType.LOGIN_REQUEST, 0);

            InitialPacket.WriteHeader();

            ECDiffieHellmanCng PrivateKey = Args.Client.ClientEncryptor.GetDecryptionArgsContainer()
                                            .AESDecryptArgs.PrivateKey;

            //IMPORTANT: Public key must derive from the private key!
            byte[] ClientPublicKey = PrivateKey.PublicKey.ToByteArray();

            byte[] NOnce = Args.Client.ClientEncryptor.GetDecryptionArgsContainer().AESDecryptArgs.NOnce;

            InitialPacket.WriteInt32(((byte)PacketHeaders.UNENCRYPTED +
                                      /*4 is for version*/ 4 + (ClientPublicKey.Length + 1) + (NOnce.Length + 1)));

            SaltedHash Hash = new SaltedHash(new SHA512Managed(), Args.Username.Length);

            byte[] HashBuf = Hash.ComputePasswordHash(Args.Username, Args.Password);
            PlayerAccount.Hash = HashBuf;

            string[] Version = GlobalSettings.Default.ClientVersion.Split('.');

            InitialPacket.WriteByte((byte)int.Parse(Version[0])); //Version 1
            InitialPacket.WriteByte((byte)int.Parse(Version[1])); //Version 2
            InitialPacket.WriteByte((byte)int.Parse(Version[2])); //Version 3
            InitialPacket.WriteByte((byte)int.Parse(Version[3])); //Version 4

            InitialPacket.WriteByte((byte)ClientPublicKey.Length);
            InitialPacket.WriteBytes(ClientPublicKey);

            InitialPacket.WriteByte((byte)NOnce.Length);
            InitialPacket.WriteBytes(NOnce);

            Args.Client.Send(InitialPacket.ToArray());
        }
예제 #18
0
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private async Task <byte[]> AliceSendsDataAsync(string message)
        {
            Console.WriteLine("Alice sends message:" + message);
            byte[] rawData       = Encoding.UTF8.GetBytes(message);
            byte[] encryptedData = null;
            //创建ECDiffieHellmanCng对象,并使用Alice的密钥对初始化它
            using (ECDiffieHellmanCng aliceAlgorithm = new ECDiffieHellmanCng(_aliceKey))
                using (CngKey bobPubKey = CngKey.Import(_bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
                {
                    //使用Alice的密钥对和Bob的公钥创建一个对称密钥,返回的对称密钥使用对称算法AES加密数据
                    byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey);
                    Console.WriteLine("Alice creates thsi symmetric key with Bobs public key Information:" + Convert.ToBase64String(symmKey));
                    //
                    using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
                    {
                        aes.Key = symmKey;
                        aes.GenerateIV();
                        using (ICryptoTransform encryptor = aes.CreateEncryptor())
                            using (MemoryStream ms = new MemoryStream())
                            {
                                using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                                {
                                    await ms.WriteAsync(aes.IV, 0, aes.IV.Length);

                                    cs.Write(rawData, 0, rawData.Length);
                                }
                                encryptedData = ms.ToArray();
                            }
                        //在访问内存流中的加密数据之前,必须关闭加密流,否则加密数据就会丢失最后的位
                        aes.Clear();
                    }
                }

            Console.WriteLine("Alice:message is encrypted:" + Convert.ToBase64String(encryptedData));
            Console.WriteLine();
            return(encryptedData);
        }
예제 #19
0
        public static EncryptionResult Encrypt(byte[] userKey, byte[] userSecret, byte[] payload
                                               //, ushort padding = 0, bool randomisePadding = false // not implemented yet
                                               )
        {
            var salt = GenerateSalt(16);

            byte[] serverPublicKey = null;
            byte[] key             = null;
            var    cgnKey          = ImportCngKeyFromPublicKey(userKey);

            using (ECDiffieHellmanCng alice = new ECDiffieHellmanCng(256))
            {
                alice.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hmac;
                alice.HashAlgorithm         = CngAlgorithm.Sha256;
                alice.HmacKey = userSecret;

                serverPublicKey = ImportPublicKeyFromCngKey(alice.PublicKey.ToByteArray());
                key             = alice.DeriveKeyMaterial(cgnKey);
            }

            var prk = HKDFSecondStep(key, Encoding.UTF8.GetBytes("Content-Encoding: auth\0"), 32);

            byte[] cek   = HKDF(salt, prk, CreateInfoChunk("aesgcm", userKey, serverPublicKey), 16);
            byte[] nonce = HKDF(salt, prk, CreateInfoChunk("nonce", userKey, serverPublicKey), 12);

            var input = AddPaddingToInput(payload);

            var encryptedMessage = EncryptAes(nonce, cek, input);

            return(new EncryptionResult
            {
                Salt = salt,
                Payload = encryptedMessage,
                PublicKey = serverPublicKey
            });
        }
예제 #20
0
        public ECDiffieHellman(int keySize, KeyAgreementKeyDerivationFunction kdFunc, KeyAgreementKeyDerivationHashAlgorithm hashAlgo)
            : base(kdFunc, hashAlgo)
        {
            _ecdh = new ECDiffieHellmanCng(keySize);
            _ecdh.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;

            switch (hashAlgo)
            {
            case KeyAgreementKeyDerivationHashAlgorithm.SHA256:
                _ecdh.HashAlgorithm = CngAlgorithm.Sha256;
                break;

            case KeyAgreementKeyDerivationHashAlgorithm.SHA384:
                _ecdh.HashAlgorithm = CngAlgorithm.Sha384;
                break;

            case KeyAgreementKeyDerivationHashAlgorithm.SHA512:
                _ecdh.HashAlgorithm = CngAlgorithm.Sha512;
                break;

            default:
                throw new CryptoException("Key derivation hash algorithm not supported.");
            }
        }
예제 #21
0
        public void TestJWTHandling()
        {
            var newKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP384, null, new CngKeyCreationParameters()
            {
                ExportPolicy = CngExportPolicies.AllowPlaintextExport, KeyUsage = CngKeyUsages.AllUsages
            });

            var t  = CryptoUtils.ImportECDsaCngKeyFromCngKey(newKey.Export(CngKeyBlobFormat.EccPrivateBlob));
            var tk = CngKey.Import(t, CngKeyBlobFormat.EccPrivateBlob);

            Assert.AreEqual(CngAlgorithmGroup.ECDsa, tk.AlgorithmGroup);

            ECDiffieHellmanCng ecKey = new ECDiffieHellmanCng(newKey);

            ecKey.HashAlgorithm         = CngAlgorithm.Sha256;
            ecKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;

            var    b64key = Convert.ToBase64String(ecKey.PublicKey.GetDerEncoded());
            string test   = $@"
{{ 
	""exp"": 1464983845, 
	""extraData"": {{ 
		""displayName"": ""gurunx"",	
		""identity"": ""af6f7c5e -fcea-3e43-bf3a-e005e400e578""	
	}},	
	""identityPublicKey"": ""{b64key}""
	""nbf"": 1464983844
}}";
            string val    = JWT.Encode(test, tk, JwsAlgorithm.ES384, new Dictionary <string, object> {
                { "x5u", b64key }
            });

            Assert.AreEqual(b64key, JWT.Headers(val)["x5u"]);
            //Assert.AreEqual("", string.Join(";", JWT.Headers(val)));
            Assert.AreEqual(test, JWT.Payload(val));
        }
예제 #22
0
    static void KeysExchenge()
    {
        byte[] inputBuffer = new byte[1024];
        Stream inputStream = Console.OpenStandardInput(inputBuffer.Length);

        Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length));

        byte[] OurPublicKey;
        byte[] TheirPublicKey;

        using (var ec = new ECDiffieHellmanCng())
        {
            ec.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            ec.HashAlgorithm         = CngAlgorithm.Sha256;
            OurPublicKey             = ec.PublicKey.ToByteArray();
            Console.WriteLine("Our public key: {0}", BitConverter.ToString(OurPublicKey).Replace("-", "").ToLowerInvariant());

            Console.Write("Input their public key:");
            string str = Console.ReadLine();
            TheirPublicKey = StringToByteArray(str);
            byte[] sendKey = ec.DeriveKeyMaterial(CngKey.Import(TheirPublicKey, CngKeyBlobFormat.EccPublicBlob));
            Console.WriteLine("Our secret key: {0}", BitConverter.ToString(OurPublicKey).Replace("-", "").ToLowerInvariant());
        }
    }
예제 #23
0
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="encrytpedData"></param>
        /// <returns></returns>

        private async Task BobReceivesDataAsync(byte[] encrytpedData)
        {
            Console.WriteLine("Bob receives encrypted data");
            byte[] rawData = null;
            //读取未加密的初始化矢量
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            //BlockSize属性返回块的位数,除以8就可以计算出字节数。
            int nBytes = aes.BlockSize / 8;

            byte[] iv = new byte[nBytes];
            for (int i = 0; i < iv.Length; i++)
            {
                iv[i] = encrytpedData[i];
            }
            //实例化一个ECDiffieHellmanCng对象,使用Alice的公钥,从DeriveKeyMaterial()方法中返回对称密钥
            using (ECDiffieHellmanCng bobAlgorithm = new ECDiffieHellmanCng(_bobKey))
                using (CngKey alicePubKey = CngKey.Import(_alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
                {
                    byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey);
                    Console.WriteLine("Bob creates this symmetric key with Alices public key information:" + Convert.ToBase64String(symmKey));

                    aes.Key = symmKey;
                    aes.IV  = iv;
                    using (ICryptoTransform decryptor = aes.CreateDecryptor())
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
                            {
                                await cs.WriteAsync(encrytpedData, nBytes, encrytpedData.Length - nBytes);
                            }
                            rawData = ms.ToArray();
                            Console.WriteLine("Bob decrypts mesage to:" + Encoding.UTF8.GetString(rawData));
                        }
                    aes.Clear();
                }
        }
예제 #24
0
파일: Server.cs 프로젝트: zhouzu/nlcfs
        private void BeginEncrypting(ref sClient sC)
        {
            byte[] sSymKey;
            CngKey sCngKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521);

            byte[] sPublic = sCngKey.Export(CngKeyBlobFormat.EccPublicBlob);

            BlockingSend(sC, Headers.HEADER_HANDSHAKE, sPublic);

            object[] oRecv = BlockingReceive(sC);

            if (!oRecv[0].Equals(Headers.HEADER_HANDSHAKE))
            {
                sC.cSocket.Disconnect(true);
            }

            byte[] cBuf = oRecv[1] as byte[];

            using (var sAlgo = new ECDiffieHellmanCng(sCngKey))
                using (CngKey cPubKey = CngKey.Import(cBuf, CngKeyBlobFormat.EccPublicBlob))
                    sSymKey = sAlgo.DeriveKeyMaterial(cPubKey);

            sC.eCls = new Encryption(sSymKey, HASH_STRENGTH.MINIMAL);
        }
예제 #25
0
        public async Task BobReceivesDataAsync(byte[] encryptedData)
        {
            Console.WriteLine("Bob receives encrypted data");
            byte[] rawData = null;
            var    aes     = new AesCryptoServiceProvider();
            int    nBytes  = aes.BlockSize;

            byte[] iv = new byte[nBytes];
            for (int i = 0; i < iv.Length; i++)
            {
                iv[i] = encryptedData[i];
            }
            using (var bobAlgorithm = new ECDiffieHellmanCng(bobKey))
            {
                using (CngKey alicePubKey = CngKey.Import(_alicePubKeyBlob, CngKeyBlobFormat.EccFullPublicBlob))
                {
                    byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey);
                    Console.WriteLine(Convert.ToBase64String(symmKey));
                    aes.Key = symmKey;
                    aes.IV  = iv;
                    using (ICryptoTransform decryptor = aes.CreateDecryptor())
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
                            {
                                await cs.WriteAsync(encryptedData, nBytes, encryptedData.Length - nBytes);
                            }
                            rawData = ms.ToArray();
                            Console.WriteLine(Encoding.UTF8.GetString(rawData));
                        }
                        aes.Clear();
                    }
                }
            }
        }
예제 #26
0
        public static ByteString DecryptString(Hash em, ECKeyPair keyPair)
        {
            ECParameters parameters = new ECParameters();

            byte[] ems = em;
            parameters.Q.X   = ems.Skip(1).Take(32).ToArray();
            parameters.Q.Y   = ems.Skip(33).Take(32).ToArray();
            parameters.D     = keyPair.D;
            parameters.Curve = keyPair.ECParameters.Curve;
            parameters.Validate();
            using (var ecDiffieHellmanCng = new ECDiffieHellmanCng())
            {
                ecDiffieHellmanCng.ImportParameters(parameters);
                var ek = ecDiffieHellmanCng.DeriveKeyFromHash(ecDiffieHellmanCng.PublicKey, HashAlgorithmName.SHA256, null, new byte[] { 0, 0, 0, 1 });
                using (RijndaelManaged aes = new RijndaelManaged())
                {
                    aes.Padding = PaddingMode.PKCS7;
                    var d  = aes.CreateDecryptor(ek, new byte[16]);
                    var bs = d.TransformFinalBlock(ems.Skip(65).Take(ems.Length - 65 - 32).ToArray(), 0,
                                                   ems.Length - 65 - 32);
                    return(bs);
                }
            }
        }
예제 #27
0
        public ICertificatePal CopyWithPrivateKey(ECDiffieHellman ecdh)
        {
            ECDiffieHellmanCng?ecdhCng = ecdh as ECDiffieHellmanCng;

            if (ecdhCng != null)
            {
                ICertificatePal?clone = CopyWithPersistedCngKey(ecdhCng.Key);

                if (clone != null)
                {
                    return(clone);
                }
            }

            ECParameters privateParameters = ecdh.ExportParameters(true);

            using (PinAndClear.Track(privateParameters.D !))
                using (ECDiffieHellmanCng clonedKey = new ECDiffieHellmanCng())
                {
                    clonedKey.ImportParameters(privateParameters);

                    return(CopyWithEphemeralKey(clonedKey.Key));
                }
        }
예제 #28
0
        //First packet sent from client to server.
        public static void SendInitialConnectPacket(NetworkClient Client, string Username)
        {
            PacketStream InitialPacket = new PacketStream(0x01, 0);

            InitialPacket.WriteHeader();

            ECDiffieHellmanCng PrivateKey = Client.ClientEncryptor.GetDecryptionArgsContainer().AESDecryptArgs.PrivateKey;

            //IMPORTANT: Public key must derive from the private key!
            PacketHandlers.ClientPublicKey = PrivateKey.PublicKey.ToByteArray();

            byte[] NOnce = Client.ClientEncryptor.GetDecryptionArgsContainer().AESDecryptArgs.NOnce;

            InitialPacket.WriteUInt16((ushort)((byte)PacketHeaders.UNENCRYPTED +
                                               (PacketHandlers.ClientPublicKey.Length + 1) + (NOnce.Length + 1)));

            InitialPacket.WriteByte((byte)PacketHandlers.ClientPublicKey.Length);
            InitialPacket.WriteBytes(PacketHandlers.ClientPublicKey);

            InitialPacket.WriteByte((byte)NOnce.Length);
            InitialPacket.WriteBytes(NOnce);

            Client.Send(InitialPacket.ToArray());
        }
예제 #29
0
        public static byte[] EncodeSkinJwt(CngKey newKey)
        {
            byte[] t  = ImportECDsaCngKeyFromCngKey(newKey.Export(CngKeyBlobFormat.EccPrivateBlob));
            CngKey tk = CngKey.Import(t, CngKeyBlobFormat.EccPrivateBlob);

            ECDiffieHellmanCng ecKey = new ECDiffieHellmanCng(newKey);

            ecKey.HashAlgorithm         = CngAlgorithm.Sha256;
            ecKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;

            var b64Key = Base64Url.Encode(ecKey.PublicKey.GetDerEncoded());

            Skin skin = new Skin
            {
                Slim     = false, Texture = Encoding.Default.GetBytes(new string('Z', 8192)),
                SkinType = "Standard_Custom"
            };

            string skin64 = Convert.ToBase64String(skin.Texture);

            string skinData = $@"
{{
	""AdRole"": 2,
	""ClientRandomId"": {new Random().Next()},
	""ServerAddress"": ""pe.mineplex.com:19132"",
	""SkinData"": ""{skin64}"",
	""SkinId"": ""{skin.SkinType}"",
	""TenantId"": """"
}}";

            string val = JWT.Encode(skinData, tk, JwsAlgorithm.ES384, new Dictionary <string, object> {
                { "x5u", b64Key }
            });

            return(Encoding.UTF8.GetBytes(val));
        }
예제 #30
0
        public static byte[] DeriveKey(CngKey externalPubKey, CngKey privateKey, int keyBitLength, byte[] algorithmId, byte[] partyVInfo, byte[] partyUInfo, byte[] suppPubInfo)
        {
            using (var cng = new ECDiffieHellmanCng(privateKey))
            {
                using (SafeNCryptSecretHandle hSecretAgreement = cng.DeriveSecretAgreementHandle(externalPubKey))
                {
                    using (var algIdBuffer = new NCrypt.NCryptBuffer(NCrypt.KDF_ALGORITHMID, algorithmId))
                        using (var pviBuffer = new NCrypt.NCryptBuffer(NCrypt.KDF_PARTYVINFO, partyVInfo))
                            using (var pvuBuffer = new NCrypt.NCryptBuffer(NCrypt.KDF_PARTYUINFO, partyUInfo))
                                using (var spiBuffer = new NCrypt.NCryptBuffer(NCrypt.KDF_SUPPPUBINFO, suppPubInfo))
                                {
                                    using (var parameters = new NCrypt.NCryptBufferDesc(algIdBuffer, pviBuffer, pvuBuffer, spiBuffer))
                                    {
                                        uint derivedSecretByteSize;
                                        uint status = NCrypt.NCryptDeriveKey(hSecretAgreement, "SP800_56A_CONCAT", parameters, null, 0, out derivedSecretByteSize, 0);

                                        if (status != BCrypt.ERROR_SUCCESS)
                                        {
                                            throw new CryptographicException(string.Format("NCrypt.NCryptDeriveKey() failed with status code:{0}", status));
                                        }

                                        var secretKey = new byte[derivedSecretByteSize];

                                        status = NCrypt.NCryptDeriveKey(hSecretAgreement, "SP800_56A_CONCAT", parameters, secretKey, derivedSecretByteSize, out derivedSecretByteSize, 0);

                                        if (status != BCrypt.ERROR_SUCCESS)
                                        {
                                            throw new CryptographicException(string.Format("NCrypt.NCryptDeriveKey() failed with status code:{0}", status));
                                        }

                                        return(Arrays.LeftmostBits(secretKey, keyBitLength));
                                    }
                                }
                }
            }
        }