public void ExchangeTooBig()
        {
            AsymmetricKeyExchangeFormatter keyex = new RSAOAEPKeyExchangeFormatter(key);

            byte[] M  = new byte [(key.KeySize >> 3) - 10];
            byte[] EM = keyex.CreateKeyExchange(M);
        }
Example #2
0
    // Use the RSAOAEPKeyExchangeDeformatter class to decode the
    // specified message.
    private byte[] EncodeMessage(string message)
    {
        byte[] encodedMessage = null;

        try
        {
            // Construct a formatter with the specified RSA key.
            //<Snippet3>
            RSAOAEPKeyExchangeFormatter keyEncryptor =
                new RSAOAEPKeyExchangeFormatter(rsaKey);
            //</Snippet3>

            // Convert the message to bytes to create the encrypted data.
            //<Snippet4>
            byte[] byteMessage = Encoding.ASCII.GetBytes(message);
            encodedMessage = keyEncryptor.CreateKeyExchange(byteMessage);
            //</Snippet4>
        }
        catch (Exception ex)
        {
            Console.WriteLine("Unexpected exception caught:" + ex.ToString());
        }

        return(encodedMessage);
    }
Example #3
0
        private void EncryptButton_Click(object sender, EventArgs e)
        {
            CspParameters myCspParms = new CspParameters();

            myCspParms.KeyContainerName = KeyContainerEncryptTextBox.Text;
            RSA myRSAProv = new RSACryptoServiceProvider(myCspParms);
            RSAOAEPKeyExchangeFormatter myKeyFormatter = new RSAOAEPKeyExchangeFormatter(myRSAProv);
            Aes mySymmProv = Aes.Create();

            byte[] encrKey = myKeyFormatter.CreateKeyExchange(mySymmProv.Key);
            byte[] data    = File.ReadAllBytes(FileEncryptTextBox.Text);
            using (FileStream fsout = new FileStream(FileEncryptTextBox.Text + ".encrypted", FileMode.Create))
            {
                using (BinaryWriter bw = new BinaryWriter(fsout))
                {
                    bw.Write(encrKey.Length);
                    bw.Write(encrKey, 0, encrKey.Length);
                    bw.Write(mySymmProv.IV.Length);
                    bw.Write(mySymmProv.IV, 0, mySymmProv.IV.Length);
                    bw.Flush();
                    using (CryptoStream cs = new CryptoStream(fsout, mySymmProv.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        using (BinaryWriter sw = new BinaryWriter(cs))
                        {
                            sw.Write(data);
                        }
                    }
                }
            }
            MessageBox.Show("Encryption completed.");
        }
Example #4
0
        public byte[] Encrypt_RSA(byte[] input)
        {
            if (input == null || input.Length == 0)
            {
                ErrorHandler.OccurException(System.Net.HttpStatusCode.BadRequest);
            }

            return(_RSAFormatter.CreateKeyExchange(input, typeof(RijndaelManaged)));
        }
Example #5
0
        /// <summary>
        /// Bobの交換鍵から、
        /// 「暗号化に使用する秘密鍵」と「Bobと交換するAliceの交換鍵」を生成
        /// </summary>
        protected override void CreateKeys()
        {
            RSA rsa = (RSA)this._asa;

            this._aes = new AesCryptoServiceProvider(); // 秘密鍵
            RSAOAEPKeyExchangeFormatter keyExchangeFormatter = new RSAOAEPKeyExchangeFormatter(rsa);

            this._exchangeKey = keyExchangeFormatter.CreateKeyExchange(this._aes.Key, typeof(Aes)); // 交換鍵
        }
Example #6
0
        public void SetKeys(TanksCommon.Encryption.EncryptioinKeys key)
        {
            var aes = new AesCryptoServiceProvider();
            var iv  = aes.IV;

            // Encrypt the session key
            RSAOAEPKeyExchangeFormatter keyFormatter = new RSAOAEPKeyExchangeFormatter(key.RsaKey);
            var encryptedSessionKey = keyFormatter.CreateKeyExchange(aes.Key, typeof(Aes));

            key.SetIvAndSessionKey(iv, encryptedSessionKey);

            this._cryptoTransform = aes.CreateEncryptor();
        }
Example #7
0
        public byte[] EncryptSessionKeyByRSA(byte[] sessionKey, string keyToUse)
        {
            AsymmetricAlgorithm rsa = algo;

            if (!String.IsNullOrEmpty(keyToUse))
            {
                rsa.FromXmlString(keyToUse);
            }
            RSAOAEPKeyExchangeFormatter forma = new RSAOAEPKeyExchangeFormatter();

            forma.SetKey(rsa);
            byte[] exchangeData = forma.CreateKeyExchange(sessionKey);
            return(exchangeData);
        }
        public void ExchangeMin()
        {
            AsymmetricKeyExchangeFormatter keyex = new RSAOAEPKeyExchangeFormatter(key);

            byte[] M = { 0x01 };
            try {
                byte[] EM = keyex.CreateKeyExchange(M);
                AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter(key);
                byte[] Mback = keyback.DecryptKeyExchange(EM);
                AssertEquals("RSAOAEPKeyExchangeFormatter Min", M, Mback);
            }
            catch (CryptographicException ce) {
                // not supported by every version of Windows - Minimum: Windows XP
                Console.WriteLine(ce.Message + " (" + Environment.OSVersion.ToString() + ")");
            }
        }
        public void Exchange128()
        {
            AsymmetricKeyExchangeFormatter keyex = new RSAOAEPKeyExchangeFormatter(key);

            byte[] M = { 0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49 };
            try {
                byte[] EM = keyex.CreateKeyExchange(M, typeof(Rijndael));
                AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter(key);
                byte[] Mback = keyback.DecryptKeyExchange(EM);
                AssertEquals("RSAOAEPKeyExchangeFormatter 128", M, Mback);
            }
            catch (CryptographicException ce) {
                // not supported by every version of Windows - Minimum: Windows XP
                Console.WriteLine(ce.Message + " (" + Environment.OSVersion.ToString() + ")");
            }
        }
        /// <summary>
        /// Encrypts the symmetric key data.
        /// </summary>
        /// <param name="cert">The cert.</param>
        /// <param name="keyData">The key data.</param>
        /// <returns>The encrypted data.</returns>
        public static byte[] EncryptSymmetricKeyData(X509Certificate2 cert, byte[] keyData)
        {
            if (cert == null)
            {
                throw new ArgumentNullException("cert");
            }

            if (keyData == null)
            {
                throw new ArgumentNullException("keyData");
            }

            RSACryptoServiceProvider rsaPublicKey = cert.PublicKey.Key as RSACryptoServiceProvider;

            RSAOAEPKeyExchangeFormatter keyFormatter = new RSAOAEPKeyExchangeFormatter(rsaPublicKey);

            return(keyFormatter.CreateKeyExchange(keyData));
        }
Example #11
0
        public static byte[] EncryptKey(byte[] keyData, RSA rsa, bool useOAEP)
        {
            if (keyData == null)
            {
                throw new ArgumentNullException("keyData");
            }
            if (rsa == null)
            {
                throw new ArgumentNullException("rsa");
            }
            if (useOAEP)
            {
                RSAOAEPKeyExchangeFormatter formatter = new RSAOAEPKeyExchangeFormatter(rsa);
                return(formatter.CreateKeyExchange(keyData));
            }
            RSAPKCS1KeyExchangeFormatter formatter2 = new RSAPKCS1KeyExchangeFormatter(rsa);

            return(formatter2.CreateKeyExchange(keyData));
        }
Example #12
0
        /// <summary>
        /// Creates FairPlay Pfx Password.
        /// </summary>
        /// <param name="keyId">The key id.</param>
        /// <param name="contentKey">The content key data.</param>
        /// <param name="name">The name.</param>
        /// <param name="cert">The cert.</param>
        /// <returns>The content key.</returns>
        internal static ContentKeyData InitializeFairPlayPfxPassword(Guid keyId, byte[] contentKey, string name, X509Certificate2 cert)
        {
            RSACryptoServiceProvider rsaPublicKey = cert.PublicKey.Key as RSACryptoServiceProvider;

            RSAOAEPKeyExchangeFormatter keyFormatter = new RSAOAEPKeyExchangeFormatter(rsaPublicKey);

            byte[] encryptedContentKey = keyFormatter.CreateKeyExchange(contentKey);

            ContentKeyData contentKeyData = new ContentKeyData
            {
                Id = EncryptionUtils.GetKeyIdentifierAsString(keyId),
                EncryptedContentKey = Convert.ToBase64String(encryptedContentKey),
                ContentKeyType      = (int)ContentKeyType.FairPlayPfxPassword,
                ProtectionKeyId     = cert.Thumbprint,
                ProtectionKeyType   = (int)ProtectionKeyType.X509CertificateThumbprint,
                Name = name,
            };

            return(contentKeyData);
        }
Example #13
0
        // encrypts the supplied input key data using an RSA key and specifies whether we want to use OAEP
        // padding or PKCS#1 v1.5 padding as described in the PKCS specification
        public static byte[] EncryptKey(byte[] keyData, RSA rsa, bool useOAEP)
        {
            if (keyData is null)
            {
                throw new ArgumentNullException(nameof(keyData));
            }
            if (rsa is null)
            {
                throw new ArgumentNullException(nameof(rsa));
            }

            if (useOAEP)
            {
                RSAOAEPKeyExchangeFormatter rsaFormatter = new RSAOAEPKeyExchangeFormatter(rsa);
                return(rsaFormatter.CreateKeyExchange(keyData));
            }
            else
            {
                RSAPKCS1KeyExchangeFormatter rsaFormatter = new RSAPKCS1KeyExchangeFormatter(rsa);
                return(rsaFormatter.CreateKeyExchange(keyData));
            }
        }
Example #14
0
    //<Snippet2>
    private static void Send(RSA key, string secretMessage, out byte[] iv, out byte[] encryptedSessionKey, out byte[] encryptedMessage)
    {
        using (Aes aes = new AesCryptoServiceProvider())
        {
            iv = aes.IV;

            // Encrypt the session key
            RSAOAEPKeyExchangeFormatter keyFormatter = new RSAOAEPKeyExchangeFormatter(key);
            encryptedSessionKey = keyFormatter.CreateKeyExchange(aes.Key, typeof(Aes));

            // Encrypt the message
            using (MemoryStream ciphertext = new MemoryStream())
                using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    byte[] plaintextMessage = Encoding.UTF8.GetBytes(secretMessage);
                    cs.Write(plaintextMessage, 0, plaintextMessage.Length);
                    cs.Close();

                    encryptedMessage = ciphertext.ToArray();
                }
        }
    }
Example #15
0
        private void EncryptButton_Click(object sender, EventArgs e)
        {
            RSACng myRSAProv;

            if (CngKey.Exists(KeyContainerEncryptTextBox.Text))
            {
                myRSAProv = new RSACng(CngKey.Open(KeyContainerEncryptTextBox.Text));
            }
            else
            {
                myRSAProv = new RSACng(CngKey.Create(CngAlgorithm.Rsa, KeyContainerEncryptTextBox.Text));
            }


            RSAOAEPKeyExchangeFormatter myKeyFormatter = new RSAOAEPKeyExchangeFormatter(myRSAProv);
            AesCng mySymmProv = new AesCng();

            byte[] encrKey = myKeyFormatter.CreateKeyExchange(mySymmProv.Key);
            byte[] data    = File.ReadAllBytes(FileEncryptTextBox.Text);
            using (FileStream fsout = new FileStream(FileEncryptTextBox.Text + ".encrypted", FileMode.Create))
            {
                using (BinaryWriter bw = new BinaryWriter(fsout))
                {
                    bw.Write(encrKey.Length);
                    bw.Write(encrKey, 0, encrKey.Length);
                    bw.Write(mySymmProv.IV.Length);
                    bw.Write(mySymmProv.IV, 0, mySymmProv.IV.Length);
                    bw.Flush();
                    using (CryptoStream cs = new CryptoStream(fsout, mySymmProv.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        using (BinaryWriter sw = new BinaryWriter(cs))
                        {
                            sw.Write(data);
                        }
                    }
                }
            }
            MessageBox.Show("Encryption completed.");
        }
        public void ExchangeNoKey()
        {
            AsymmetricKeyExchangeFormatter keyex = new RSAOAEPKeyExchangeFormatter();

            byte[] M = keyex.CreateKeyExchange(new byte [16]);
        }
Example #17
0
        static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: -e/-d Filename KeyContainer");
                return;
            }
            if (args[0] == "-e")
            {
                CspParameters myCspParms = new CspParameters {
                    KeyContainerName = args[2]
                };

                RSACryptoServiceProvider    myRSAProv      = new RSACryptoServiceProvider(myCspParms);
                RSAOAEPKeyExchangeFormatter myKeyFormatter = new RSAOAEPKeyExchangeFormatter(myRSAProv);

                Aes    mySymmProv = Aes.Create();
                byte[] encrKey    = myKeyFormatter.CreateKeyExchange(mySymmProv.Key);
                byte[] data       = File.ReadAllBytes(args[1]);
                using (FileStream fsout = new FileStream(args[1] + ".encrypted", FileMode.Create))
                {
                    using (BinaryWriter bw = new BinaryWriter(fsout))
                    {
                        bw.Write(encrKey.Length);
                        bw.Write(encrKey, 0, encrKey.Length);
                        bw.Write(mySymmProv.IV.Length);
                        bw.Write(mySymmProv.IV, 0, mySymmProv.IV.Length);
                        bw.Flush();
                        using (CryptoStream cs = new CryptoStream(fsout, mySymmProv.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            using (BinaryWriter sw = new BinaryWriter(cs))
                            {
                                sw.Write(data);
                                sw.Flush();
                            }
                        }
                    }
                }
            }
            else if (args[0] == "-d")
            {
                CspParameters myCspParms = new CspParameters {
                    KeyContainerName = args[2]
                };

                RSACryptoServiceProvider      myRSAProv        = new RSACryptoServiceProvider(myCspParms);
                RSAOAEPKeyExchangeDeformatter myKeyDeformatter = new RSAOAEPKeyExchangeDeformatter(myRSAProv);

                Aes mySymmProv = Aes.Create();
                using (FileStream fs = new FileStream(args[1], FileMode.Open))
                {
                    using (BinaryReader br = new BinaryReader(fs))
                    {
                        int    keyLength = br.ReadInt32();
                        byte[] encrKey   = new byte[keyLength];
                        br.Read(encrKey, 0, keyLength);
                        int    ivLength = br.ReadInt32();
                        byte[] IV       = new byte[ivLength];
                        br.Read(IV, 0, ivLength);
                        byte[] Key = myKeyDeformatter.DecryptKeyExchange(encrKey);
                        mySymmProv.Key = Key;
                        mySymmProv.IV  = IV;
                        using (CryptoStream cs = new CryptoStream(fs, mySymmProv.CreateDecryptor(), CryptoStreamMode.Read))
                        {
                            int    dataLen = (int)fs.Length - 4 - keyLength - 4 - ivLength;
                            byte[] data    = new byte[dataLen];
                            int    len     = cs.Read(data, 0, dataLen);
                            using (FileStream outStream = File.Open(args[1].Replace("encrypted", "decrypted"), FileMode.OpenOrCreate))
                            {
                                outStream.Write(data, 0, len);
                                outStream.Flush();
                            }
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("Usage: -e/-d Filename KeyContainer");
                return;
            }
        }
Example #18
0
 public byte[] Encrypt_RSA(byte[] input)
 {
     return(_RSAFormatter.CreateKeyExchange(input, typeof(RijndaelManaged)));
 }
Example #19
0
            // FIXME	[KeyContainerPermission (SecurityAction.Assert, KeyContainerName = "DAPI",
            //			Flags = KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Create)]
            public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope)
            {
                if (userData == null)
                {
                    throw new ArgumentNullException("userData");
                }

                Rijndael aes = Rijndael.Create();

                aes.KeySize = 128;

                byte[] encdata = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    ICryptoTransform t = aes.CreateEncryptor();
                    using (CryptoStream cs = new CryptoStream(ms, t, CryptoStreamMode.Write))
                    {
                        cs.Write(userData, 0, userData.Length);
                        cs.Close();
                        encdata = ms.ToArray();
                    }
                }

                byte[] key    = null;
                byte[] iv     = null;
                byte[] secret = null;
                byte[] header = null;
                SHA256 hash   = SHA256.Create();

                try
                {
                    key    = aes.Key;
                    iv     = aes.IV;
                    secret = new byte[1 + 1 + 16 + 1 + 16 + 1 + 32];

                    byte[] digest = hash.ComputeHash(userData);
                    if ((optionalEntropy != null) && (optionalEntropy.Length > 0))
                    {
                        // the same optionalEntropy will be required to get the data back
                        byte[] mask = hash.ComputeHash(optionalEntropy);
                        for (int i = 0; i < 16; i++)
                        {
                            key[i] ^= mask[i];
                            iv[i]  ^= mask[i + 16];
                        }
                        secret[0] = 2; // entropy
                    }
                    else
                    {
                        secret[0] = 1; // without entropy
                    }

                    secret[1] = 16;  // key size
                    Buffer.BlockCopy(key, 0, secret, 2, 16);
                    secret[18] = 16; // iv size
                    Buffer.BlockCopy(iv, 0, secret, 19, 16);
                    secret[35] = 32; // digest size
                    Buffer.BlockCopy(digest, 0, secret, 36, 32);

                    RSAOAEPKeyExchangeFormatter formatter = new RSAOAEPKeyExchangeFormatter(GetKey(scope));
                    header = formatter.CreateKeyExchange(secret);
                }
                finally
                {
                    if (key != null)
                    {
                        Array.Clear(key, 0, key.Length);
                        key = null;
                    }
                    if (secret != null)
                    {
                        Array.Clear(secret, 0, secret.Length);
                        secret = null;
                    }
                    if (iv != null)
                    {
                        Array.Clear(iv, 0, iv.Length);
                        iv = null;
                    }
                    aes.Clear();
                    hash.Clear();
                }

                byte[] result = new byte[header.Length + encdata.Length];
                Buffer.BlockCopy(header, 0, result, 0, header.Length);
                Buffer.BlockCopy(encdata, 0, result, header.Length, encdata.Length);
                return(result);
            }
Example #20
0
        public void Start()
        {
            RijndaelManaged  CryRijnd;
            ICryptoTransform Decryptor, Encryptor;

            byte[] CryKey;
            byte[] CryIV;

            CryRijnd = new RijndaelManaged();

            Console.WriteLine("Клиент соединен");
            ConLog.WriteLine("Клиент соединен");


            //получаем открытый ключ от клиента.
            //создаём сеансовый открытый и закрытый ключ
            //шифруем их при помощи открытого ключа от клиента
            //отсылаем клиенту
            //для дальнейшей передачи данных используем сеановый ключ

            try
            {
                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {
                    byte[] publicKey = ReadMessageNoCry();   //получили публичный ключ
                    rsa.ImportCspBlob(publicKey);

                    CryRijnd.GenerateKey();       //создали сессионный ключ

                    //этот класс специально предназначен для зашифрованного обмена ключами,
                    //  потому им и воспользуемся
                    RSAOAEPKeyExchangeFormatter keyFormatter = new RSAOAEPKeyExchangeFormatter(rsa);
                    byte[] crySessionKey = keyFormatter.CreateKeyExchange(CryRijnd.Key); //зашифровали ключ
                    byte[] mess          = new byte[4 + crySessionKey.Length];
                    ToAByte(crySessionKey.Length).CopyTo(mess, 0);
                    crySessionKey.CopyTo(mess, 4);
                    Client.GetStream().Write(mess, 0, mess.Length);  //отправили клиенту сессионый ключ

                    CryRijnd.GenerateIV();

                    byte[] IV = CryRijnd.IV;
                    mess = new byte[4 + IV.Length];
                    ToAByte(IV.Length).CopyTo(mess, 0);
                    IV.CopyTo(mess, 4);
                    Client.GetStream().Write(mess, 0, mess.Length);     //отправили клиенту вектор инициализации

                    CryKey = CryRijnd.Key;
                    CryIV  = CryRijnd.IV;

                    Encryptor = CryRijnd.CreateEncryptor(CryRijnd.Key, CryRijnd.IV);
                    Decryptor = CryRijnd.CreateDecryptor(CryRijnd.Key, CryRijnd.IV);

                    CryWr = new CryptoStream(Client.GetStream(), Encryptor, CryptoStreamMode.Write);
                    CryRd = new CryptoStream(Client.GetStream(), Decryptor, CryptoStreamMode.Read);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
                ConLog.WriteLine("Error: {0}", e.Message);
            }


            while (Client.Connected)
            {
                byte[] received = ReadMessage(CryRd); //ждём сообщения

                if (received == null)                 //если вернулся null, то клиент разорвал соединение
                {
                    Console.WriteLine("{0}: Неожиданное завершение работы с клиентом", Login);
                    ConLog.WriteLine("{0}: Неожиданное завершение работы с клиентом", Login);
                    UsrRec.RemoveUser(Login);
                    Client.Close();
                    break;
                }

                int tmpSize = 10 * 2;           //берём первые 10 символов и из них получаем комманду
                if (tmpSize > received.Length)
                {
                    tmpSize = received.Length;                            //если сообщение короче, чем 10 символов, то берём всё сообщение
                }
                string tmpStr  = Encoding.Unicode.GetString(received, 0, tmpSize);
                string command = tmpStr.Split(' ')[0];  //либо команда - это всё сообщение, либо оно
                                                        //отделяется пробелом от данных

                //Console.WriteLine("Received: {0}", command);
                //ConLog.WriteLine("Received: {0}", command);

                if (command == "LOGIN")
                {
                    Login = GetPasString(received, 6 * 2);

                    if (UsrRec.NewUser(Login, CryWr))
                    {
                        Console.WriteLine("Login: {0}", Login);
                        ConLog.WriteLine("Login: {0}", Login);
                        SendResponse(CryWr, "LOG_OK");
                    }
                    else
                    {
                        Console.WriteLine("Ошибка входа с логином {0}. Пользователь уже вошёл", Login);
                        ConLog.WriteLine("Ошибка входа с логином {0}. Пользователь уже вошёл", Login);
                        SendResponse(CryWr, "LOG_ERR");
                        Client.Close();
                        break;
                    }
                }
                else if (command == "LOGOUT")
                {
                    Console.WriteLine("Logout: {0}", Login);
                    ConLog.WriteLine("Logout: {0}", Login);
                    UsrRec.RemoveUser(Login);
                    Client.Close();
                }
                else if (command == "FILE")
                {
                    AddFile(received);
                    received = null;
                }
                else if (command == "GETOTHERF")
                {
                    GetOtherFiles(received);
                }
                else if (command == "GETUSERF")
                {
                    GetUserFiles(received);
                }
                else if (command == "GET")
                {
                    SendFile(received);
                }
                else if (command == "DELETE")
                {
                    DeleteFile(received);
                }
                else if (command == "PSWD")
                {
                    byte[] Key = new byte[0x20];
                    for (int i = 0; i < 0x20; i++)
                    {
                        Key[i] = received[5 * 2 + i];
                    }
                    UsrRec.SetLastAccessKey(Login, Key);
                }
                else if (command == "ERROR")
                {
                    UsrRec.SetLastAccessDenied(Login);
                }

                received = null;
                GC.Collect();
            }
        }
Example #21
0
        /// <inheritdoc />
        protected internal override byte[] Encrypt(byte[] data, byte[] iv)
        {
            var keyExchange = new RSAOAEPKeyExchangeFormatter(this.Rsa);

            return(keyExchange.CreateKeyExchange(data));
        }