コード例 #1
0
        public void SymetricAlgorithmCreateEncryptor()
        {
            var initializationVectorConstant = new byte[16];

            using (SymmetricAlgorithm sa = SymmetricAlgorithm.Create("AES"))
            {
                ICryptoTransform noParams = sa.CreateEncryptor();              // Compliant - IV is automatically generated
                var defaultKeyAndIV       = sa.CreateEncryptor(sa.Key, sa.IV); // Compliant

                sa.GenerateKey();
                var generateIVNotCalled = sa.CreateEncryptor(sa.Key, sa.IV);
                var constantVector      = sa.CreateEncryptor(sa.Key, initializationVectorConstant); // Noncompliant {{Use a dynamically-generated, random IV.}}
//                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

                sa.GenerateIV();
                var defaultConstructor = sa.CreateEncryptor(); // Compliant
                var compliant          = sa.CreateEncryptor(sa.Key, sa.IV);

                sa.KeySize = 12;
                sa.CreateEncryptor(); // Compliant - updating key size does not change the status
                sa.CreateEncryptor(sa.Key, new CustomAlg().IV);
                sa.CreateEncryptor(sa.Key, new CustomAlg().Key);

                sa.IV = initializationVectorConstant;
                sa.GenerateKey();

                var ivReplacedDefaultConstructor = sa.CreateEncryptor(); // Noncompliant
                var ivReplaced = sa.CreateEncryptor(sa.Key, sa.IV);      // Noncompliant
            }
        }
コード例 #2
0
ファイル: Symmetric.cs プロジェクト: yousky/BWYouCore
        protected Symmetric(SymmetricAlgorithm symmetricAlgorithm, out byte[] key, out byte[] iv)
            : this(symmetricAlgorithm)
        {
            symmetric.GenerateKey();
            symmetric.GenerateIV();

            key = symmetric.Key;
            iv  = symmetric.IV;
        }
コード例 #3
0
        public static byte[] GenerateKey(string symmetricAlgorithmName)
        {
            SymmetricAlgorithm s = SymmetricAlgorithm.Create(symmetricAlgorithmName);

            s.GenerateKey();
            return(s.Key);
        }
コード例 #4
0
        /// <summary>
        /// 设置加密算法
        /// </summary>
        private void SetEncryptor()
        {
            switch (_mbytEncryptionType)
            {
            case SymmetricEncryptType.DES:
                _mCSP = new DESCryptoServiceProvider();
                break;

            case SymmetricEncryptType.RC2:
                _mCSP = new RC2CryptoServiceProvider();
                break;

            case SymmetricEncryptType.Rijndael:
                _mCSP = new RijndaelManaged();
                break;

            case SymmetricEncryptType.TripleDES:
                _mCSP = new TripleDESCryptoServiceProvider();
                break;
            }

            // Generate Key
            _mCSP.GenerateKey();

            // Generate IV
            _mCSP.GenerateIV();
        }
コード例 #5
0
 void encrypt(Stream inStream, Stream outStream)
 {
     using (SymmetricAlgorithm algorithm = AesCryptoServiceProvider.Create())
     {
         algorithm.GenerateKey();
         algorithm.GenerateIV();
         byte[] iv  = algorithm.IV;
         byte[] key = algorithm.Key;
         using (ICryptoTransform encryptor = algorithm.CreateEncryptor(key, iv))
         {
             using (CryptoStream cs = new CryptoStream(outStream, encryptor, CryptoStreamMode.Write))
             {
                 BinaryWriter bw = new BinaryWriter(outStream);
                 bw.Write(iv);
                 byte[]       readBuffer = new byte[1];
                 BinaryReader br         = new BinaryReader(inStream);
                 while (br.Read(readBuffer, 0, readBuffer.Length) != 0)
                 {
                     cs.Write(readBuffer, 0, 1);
                 }
             }
         }
     }
     inStream.Close();
     outStream.Close();
 }
コード例 #6
0
ファイル: MainPage.xaml.cs プロジェクト: TudorMutiu1/cripto
        private async void CryptoButton_Click(object sender, RoutedEventArgs e)
        {
            if (algorithm == null)
            {
                await new MessageDialog("You haven't selected an algorithm!").ShowAsync();
                return;
            }


            clearTextBox.Document.GetText(Windows.UI.Text.TextGetOptions.None, out string clearText);
            if (clearText.Trim() == string.Empty)
            {
                await new MessageDialog("No clear text :( ").ShowAsync();
                return;
            }


            view = new CryptoView();
            algorithm.GenerateKey();
            algorithm.GenerateIV();
            try
            {
                model = new CryptoModel(algorithm, cipherMode);
            }catch (InCompatibleFormatException ex)
            {
                await new MessageDialog("Incompatable").ShowAsync();
                return;
            }
            controller = new CryptoController(model, view);

            controller.ClearText = clearText;
            controller.UpdateView(CryptoController.Operation.Encryption,
                                  (result) => cryptedTextBox.Document.SetText(Windows.UI.Text.TextSetOptions.None, result));
        }
コード例 #7
0
ファイル: EncryptAESHelper.cs プロジェクト: aceunlonely/Nurse
        /// <summary>
        /// 生成秘钥
        /// </summary>
        /// <returns></returns>
        public static string GenerateKey()
        {
            SymmetricAlgorithm aes = Rijndael.Create();

            aes.GenerateKey();
            return(Convert.ToBase64String(aes.Key)); // ASCIIEncoding.ASCII.GetString(aes.Key);
        }
コード例 #8
0
        /// <summary>
        /// generates a random Key, if one was not provided
        /// </summary>
        public ByteArray RandomKey()
        {
            m_SymmAlgorithm.GenerateKey();
            ByteArray key = new ByteArray(m_SymmAlgorithm.Key);

            return(key);
        }
コード例 #9
0
        public static void Encrypt(X509Certificate2 certificate, string sourceFile, string encryptedFile)
        {
            RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PublicKey.Key;

            using (SymmetricAlgorithm cipher = GetCipher())
            {
                cipher.Mode    = Mode;
                cipher.Padding = Padding;
                cipher.GenerateKey();
                cipher.GenerateIV();

                using (FileStream fOut = new FileStream(encryptedFile, FileMode.Create, FileAccess.Write))
                {
                    using (CryptoStream cs = new CryptoStream(fOut, cipher.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        BinaryWriter bw = new BinaryWriter(fOut);
                        bw.Write(MAGIC_BYTES);
                        byte[] encKey = rsa.Encrypt(cipher.Key, false);
                        bw.Write((short)encKey.Length);
                        bw.Write(encKey);

                        bw.Write((short)cipher.IV.Length);
                        bw.Write(cipher.IV);

                        using (FileStream fIn = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
                        {
                            ZipHelper.CopyStream(fIn, cs);
                        }
                    }
                }
            }
        }
コード例 #10
0
        public NativeSymmetricEncryption(string algorithm, int keySize)
        {
            switch (algorithm)
            {
            case "AES":
                _symAlg = Aes.Create();
                break;

            default:
                _symAlg = SymmetricAlgorithm.Create(algorithm);
                break;
            }
            if (_symAlg != null)
            {
                _symAlg.Padding = PaddingMode.PKCS7;
                _symAlg.Mode    = CipherMode.CBC;
                if (keySize > 0)
                {
                    _symAlg.KeySize = keySize;
                }
                _symAlg.GenerateKey();
                _symAlg.GenerateIV();
                _key = _symAlg.Key;
                _iv  = _symAlg.IV;
            }
            else
            {
                throw new AlgorithmNotSupportedException();
            }
        }
コード例 #11
0
        /// <summary>
        /// Generates the symmetric key.
        /// </summary>
        /// <returns></returns>
        public static byte[] GenerateSymmetricKey()
        {
            SymmetricAlgorithm rijaendel = Rijndael.Create();

            rijaendel.GenerateKey();
            return(rijaendel.Key);
        }
コード例 #12
0
        /****************************************************************************/
        public static void GenerateNewKey(SymmetricAlgorithm algorithm)
        {
            algorithm.GenerateKey();
            algorithm.GenerateIV();

            string strWrite = "byte[] key  = {";

            foreach (byte b in algorithm.Key)
            {
                strWrite += b.ToString() + ", ";
            }

            strWrite = strWrite.Substring(0, strWrite.Length - 2) + "};\r\n";

            strWrite += "byte[] IV  = {";

            foreach (byte c in algorithm.IV)
            {
                strWrite += c.ToString() + ", ";
            }

            strWrite = strWrite.Substring(0, strWrite.Length - 2) + "};\r\n";

            strWrite += "\r\n\r\n";
            strWrite += Convert.ToBase64String(algorithm.Key) + "\r\n";
            strWrite += Convert.ToBase64String(algorithm.IV) + "\r\n";

            cDebug.ToFile(strWrite, "Common.Crypto\\keys.txt");
        }
コード例 #13
0
        public void Generate(string cipher)
        {
            switch (cipher)
            {
            case "DES":
                mySymmetricAlg = DES.Create();
                break;

            case "3DES":
                mySymmetricAlg = TripleDES.Create();
                break;

            case "Rijndael":
                mySymmetricAlg = Rijndael.Create();
                break;

            case "AES":
                mySymmetricAlg         = Aes.Create();
                mySymmetricAlg.Mode    = CipherMode.CBC;
                mySymmetricAlg.KeySize = 128;
                break;
            }
            mySymmetricAlg.GenerateIV();
            mySymmetricAlg.GenerateKey();
        }
コード例 #14
0
        private void Initialize(byte[] key, byte[] iv)
        {
            symAlg           = new Threefish();
            symAlg.KeySize   = key.Length * 8;
            symAlg.BlockSize = key.Length * 8;
            symAlg.Mode      = CryptoCommon.CipherMode;
            symAlg.Padding   = PaddingMode.None;
            if (key == null)
            {
                symAlg.GenerateKey();
            }
            else
            {
                symAlg.Key = key;
            }

            if (iv == null)
            {
                symAlg.GenerateIV();
            }
            else
            {
                symAlg.IV = iv;
            }
            this.encryptor = this.symAlg.CreateEncryptor();
            this.decryptor = this.symAlg.CreateDecryptor();

            /*symAlg = new RijndaelManaged();
             * symAlg.KeySize = 256;
             * symAlg.BlockSize = 256;
             * symAlg.Key = key.Take(256 / 8).ToArray();
             * symAlg.IV = iv.Take(256 / 8).ToArray();*/
        }
コード例 #15
0
 /// <summary>
 /// 生成用于SymmetricCrypt对象的随机密钥 (Key)与IV值。
 /// </summary>
 /// <param name="key">以out方式返回SymmetricCrypt对象生成的随机密钥key值</param>
 /// <param name="iv">以out方式返回SymmetricCrypt对象生成的随机IV值</param>
 public void GenKey(out byte[] key, out byte[] iv)
 {
     _symmetricAlgorithm.GenerateKey();
     _symmetricAlgorithm.GenerateIV();
     key = _symmetricAlgorithm.Key;
     iv  = _symmetricAlgorithm.IV;
 }
コード例 #16
0
        /// <summary>
        /// 随机生成字符串key,hash出适合AES加密的密钥(兼容JavaAES加密)
        /// </summary>
        /// <param name="algorithm"></param>
        /// <param name="sourceLength">原始密钥长度(最大长度32)</param>
        /// <param name="finalLength">最终密钥长度</param>
        /// <returns>原始密钥</returns>
        public static string GenerateKey(this SymmetricAlgorithm algorithm, int sourceLength, int finalLength = 16)
        {
            var key = string.Join("", Guid.NewGuid().ToString("N").Take(sourceLength));

            algorithm.GenerateKey(key, finalLength);
            return(key);
        }
コード例 #17
0
 public Crypt(int keySize)
 {
     if (keySize == 0)
     {
         AES = new RijndaelManaged
         {
             BlockSize = s_defaultKey.Length * 8,
             KeySize   = s_defaultKey.Length * 8,
             Padding   = PaddingMode.None,
             Mode      = CipherMode.ECB,
             Key       = s_defaultKey
         };
     }
     else
     {
         AES = new RijndaelManaged
         {
             BlockSize = keySize,
             KeySize   = keySize,
             Padding   = PaddingMode.None,
             Mode      = CipherMode.ECB,
         };
         AES.GenerateKey();
     }
 }
コード例 #18
0
        public static void ImplementKeyManagementMethod()
        {
            //Symmetric encryption
            //key management for symmetricEncryption

            SymmetricAlgorithm algorithm = SymmetricAlgorithm.Create();

            algorithm.GenerateKey();
            algorithm.GenerateIV();

            //In general, there is no reason to use this method, because CreateEncryptor() or CreateEncryptor(null, null) automatically generates both an initialization vector and a key.

            //Assymetric Encryption
            //To store the private key in a secute way, you can use a container, since it you can store, delete or read the private key

            //1.-Create the container.
            CspParameters container = new CspParameters();

            container.KeyContainerName = "myContainer";

            //2.- Create the algorithm object
            RSACryptoServiceProvider rsa        = new RSACryptoServiceProvider(container);
            RSAParameters            RSAKeyInfo = rsa.ExportParameters(false);

            //3.- Create the private key, and automatically save the private key
            string PrivateKey = rsa.ToXmlString(true);

            Console.WriteLine("private key is stored in the container {0}", PrivateKey);
        }
コード例 #19
0
 public NetCryptoProviderBase(NetPeer peer, SymmetricAlgorithm algo)
     : base(peer)
 {
     m_algorithm = algo;
     m_algorithm.GenerateKey();
     m_algorithm.GenerateIV();
 }
コード例 #20
0
        /// <summary>
        /// Gera chave de criptografia Key com 128 bits
        /// </summary>
        internal void GerarKey()
        {
            //Declaração de variáveis
            SymmetricAlgorithm objRijndael = null;
            string             strKey      = null;

            try
            {
                //Cria o objeto de criptografia default "Rijndael"
                objRijndael = SymmetricAlgorithm.Create();

                //Gera uma nova chave
                objRijndael.KeySize = 128;
                objRijndael.GenerateKey();

                //Converte a chave para base64
                strKey = Convert.ToBase64String(objRijndael.Key);
                //**************************//
                //							//
                //**************************//
            }
            catch (Exception p_objErro)
            {
                throw p_objErro;
            }
        }
コード例 #21
0
    public byte[] GenerateKey()
    {
        SymmetricAlgorithm algorithm = GetAlgorithm();

        algorithm.GenerateKey();
        return(algorithm.Key);
    }
コード例 #22
0
 public AES()
 {
     _Aes         = new AesCryptoServiceProvider();
     _Aes.KeySize = AES_KEY_SIZE;
     _Aes.GenerateKey();
     _Aes.GenerateIV();
 }
コード例 #23
0
        public static void TestSymmetricAlgorithmProperties(SymmetricAlgorithm alg, int blockSize, int keySize, byte[] key = null)
        {
            alg.BlockSize = blockSize;
            Assert.Equal(blockSize, alg.BlockSize);

            var emptyIV = new byte[alg.BlockSize / 8];

            alg.IV = emptyIV;
            Assert.Equal(emptyIV, alg.IV);
            alg.GenerateIV();
            Assert.NotEqual(emptyIV, alg.IV);

            if (key == null)
            {
                key = new byte[alg.KeySize / 8];
            }
            alg.Key = key;
            Assert.Equal(key, alg.Key);
            Assert.NotSame(key, alg.Key);
            alg.GenerateKey();
            Assert.NotEqual(key, alg.Key);

            alg.KeySize = keySize;
            Assert.Equal(keySize, alg.KeySize);

            alg.Mode = CipherMode.ECB;
            Assert.Equal(CipherMode.ECB, alg.Mode);

            alg.Padding = PaddingMode.PKCS7;
            Assert.Equal(PaddingMode.PKCS7, alg.Padding);
        }
コード例 #24
0
 private void Encrypt(CommandLineParser parser)
 {
     using (_algorithm = ChooseEncryptAlg(parser.Algorithm))
     {
         _algorithm.GenerateIV();
         _algorithm.GenerateKey();
         using (FileStream inputFileStream = new FileStream(parser.InputFileName, FileMode.Open, FileAccess.Read)
                )
         {
             using (
                 FileStream outputFileStream = new FileStream(parser.OutputFileName, FileMode.Create,
                                                              FileAccess.Write))
             {
                 using (ICryptoTransform encryptor = _algorithm.CreateEncryptor())
                 {
                     using (
                         CryptoStream cryptoStream = new CryptoStream(outputFileStream, encryptor,
                                                                      CryptoStreamMode.Write))
                     {
                         inputFileStream.CopyTo(cryptoStream);
                     }
                 }
                 using (
                     BinaryWriter keyWriter =
                         new BinaryWriter(File.Open(parser.KeyFileName, FileMode.Create, FileAccess.Write)))
                 {
                     keyWriter.Write(Convert.ToBase64String(_algorithm.Key));
                     keyWriter.Write(Convert.ToBase64String(_algorithm.IV));
                 }
             }
         }
     }
 }
コード例 #25
0
        /// <summary>
        /// generates a random Key, if one was not provided
        /// </summary>
        public Data RandomKey()
        {
            _crypto.GenerateKey();
            Data d = new Data(_crypto.Key);

            return(d);
        }
コード例 #26
0
        public override void DoWork()
        {
            FileStream   fileToStream, fileFromStream, fileKeyStream;
            CryptoStream cryptoStream;

            try
            {
                _symmetricAlgorithm.GenerateKey();
                _symmetricAlgorithm.GenerateIV();
                using (fileToStream = new FileStream(_fileToName, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (fileFromStream = new FileStream(_fileFromName, FileMode.Open, FileAccess.Read))
                    {
                        using (cryptoStream = new CryptoStream(fileToStream, _symmetricAlgorithm.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            fileFromStream.CopyTo(cryptoStream);
                        }
                    }

                    FileInfo currentFile = new FileInfo(_fileFromName);
                    using (fileKeyStream = new FileStream(Path.GetFileNameWithoutExtension(currentFile.FullName) + ".key" + currentFile.Extension, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter(fileKeyStream))
                        {
                            streamWriter.WriteLine(Convert.ToBase64String(_symmetricAlgorithm.Key));
                            streamWriter.WriteLine(Convert.ToBase64String(_symmetricAlgorithm.IV));
                        }
                    }
                }
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine(e.Message);
            }
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: Silvade/nsudotnet
        private static void EncryptFile(SymmetricAlgorithm algorithm)
        {
            string iv, key;

            algorithm.GenerateIV();
            algorithm.GenerateKey();

            iv  = Convert.ToBase64String(algorithm.IV);
            key = Convert.ToBase64String(algorithm.Key);

            using (StreamWriter keyStream = new StreamWriter(keyFile))
            {
                keyStream.WriteLine(key);
                keyStream.WriteLine(iv);
            }

            using (Stream inStream = new FileStream(inFile, FileMode.Open))
            {
                using (Stream outputStream = new FileStream(outFile, FileMode.OpenOrCreate))
                {
                    using (ICryptoTransform cryptoTransform = algorithm.CreateEncryptor())
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(outputStream, cryptoTransform, CryptoStreamMode.Write))
                        {
                            inStream.CopyTo(cryptoStream);
                        }
                    }
                }
            }
        }
コード例 #28
0
ファイル: AppDataProtect.cs プロジェクト: sundysj/Hongkun
        //随机产生对称加密的钥匙KEY和向量IV
        private byte[] RandomKey(int choice)
        {
            SymmetricAlgorithm crypt = SymmetricAlgorithm.Create(sma[choice]);

            crypt.GenerateKey();
            return(crypt.Key);
        }
コード例 #29
0
        public override void Crypt()
        {
            using (SymmetricAlgorithm algorithm = GetAlgorithm(_algorithm))
            {
                algorithm.GenerateKey();
                algorithm.GenerateIV();

                String fileKey = Path.GetFileNameWithoutExtension(_fileFrom) + ".key.txt";

                using (FileStream keyStream = new FileStream(fileKey, FileMode.Create))
                {
                    using (StreamWriter keyWriter = new StreamWriter(keyStream))
                    {
                        keyWriter.WriteLine(Convert.ToBase64String(algorithm.Key));
                        keyWriter.WriteLine(Convert.ToBase64String(algorithm.IV));
                    }

                    using (FileStream fileToStream = new FileStream(_fileTo, FileMode.Create, FileAccess.Write))
                    {
                        using (FileStream fileFromStream = new FileStream(_fileFrom, FileMode.Open, FileAccess.Read))
                        {
                            using (CryptoStream cryptoStream =
                                       new CryptoStream(fileToStream, algorithm.CreateEncryptor(), CryptoStreamMode.Write))
                            {
                                fileFromStream.CopyTo(cryptoStream);
                            }
                        }
                    }
                    Console.WriteLine("Encyption done");
                }
            }
        }
コード例 #30
0
        /// <summary>
        ///     Constructs using the specified symmetric algorithm. Remember to store the Key and IV somewhere or you ain't gettin'
        ///     yo' data back!
        /// </summary>
        /// <param name="algorithm">The symmetric algorithm to use</param>
        public SymmetricCryptoProvider(SymmetricCryptoAlgorithm algorithm)
        {
            switch (algorithm)
            {
            case SymmetricCryptoAlgorithm.AES:
                _algorithm = new AesCryptoServiceProvider();
                break;

            case SymmetricCryptoAlgorithm.Rijndael:
                _algorithm = new RijndaelManaged();
                break;

            case SymmetricCryptoAlgorithm.TripleDES:
                _algorithm = new TripleDESCryptoServiceProvider();
                break;

            case SymmetricCryptoAlgorithm.RC2:
                _algorithm = new RC2CryptoServiceProvider();
                break;

            default:
                _algorithm = new RijndaelManaged();
                break;
            }

            _algorithm.Mode = CipherMode.CBC;

            _algorithm.GenerateIV();
            _algorithm.GenerateKey();

            Key = _algorithm.Key;
            IV  = _algorithm.IV;
        }