コード例 #1
0
ファイル: members.cs プロジェクト: zeromus/dotnet-api-docs
        static void Main(string[] args)
        {
            // Initializes a new instance of the KeySizes class with the
            // specified key values.
            //<Snippet2>
            int      minSize  = 64;
            int      maxSize  = 1024;
            int      skipSize = 64;
            KeySizes keySizes = new KeySizes(minSize, maxSize, skipSize);

            //</Snippet2>

            // Show the values of the keys.
            ShowKeys(new KeySizes[1] {
                keySizes
            }, "Custom Keys");

            // Create a new symmetric algorithm and display its key values.
            SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

            ShowKeys(rijn.LegalKeySizes, rijn.ToString());
            Console.WriteLine("rijn.blocksize:" + rijn.BlockSize);

            // Create a new RSA algorithm and display its key values.
            RSACryptoServiceProvider rsaCSP =
                new RSACryptoServiceProvider(384);

            ShowKeys(rsaCSP.LegalKeySizes, rsaCSP.ToString());
            Console.WriteLine("RSACryptoServiceProvider KeySize = " +
                              rsaCSP.KeySize);

            Console.WriteLine("This sample completed successfully; " +
                              "press Enter to exit.");
            Console.ReadLine();
        }
コード例 #2
0
ファイル: AESInterop.cs プロジェクト: leeholder/Netduino_SDK
    public static bool TestAlgorithms(SymmetricAlgorithm encAlgorithm, SymmetricAlgorithm decAlgorithm, CipherMode[] modes, int maxLength, int iterations)
    {
        Random rand = new Random();

        for (int i = 0; i < iterations; i++)
        {
            // Create random data, key, IV, mode
            //
            byte[] key = new byte[KeySizeBytes[rand.Next(KeySizeBytes.Length)]];
            rand.NextBytes(key);

            byte[] data = new byte[rand.Next(1, maxLength + 1)];
            rand.NextBytes(data);

            byte[] IV = new byte[BlockSizeBytes];
            rand.NextBytes(IV);

            CipherMode  mode    = modes[rand.Next(modes.Length)];
            PaddingMode padding = PaddingModes[new Random().Next(PaddingModes.Length)];

            // Encrypt the data
            //
            byte[] encryptedData;
            encAlgorithm.Key     = key;
            encAlgorithm.IV      = IV;
            encAlgorithm.Mode    = mode;
            encAlgorithm.Padding = padding;

            ICryptoTransform transform = encAlgorithm.CreateEncryptor();
            encryptedData = transform.TransformFinalBlock(data, 0, data.Length);

            // Decrypt the data
            //
            byte[] decryptedData;
            decAlgorithm.Key     = key;
            decAlgorithm.IV      = IV;
            decAlgorithm.Mode    = mode;
            decAlgorithm.Padding = padding;

            transform     = decAlgorithm.CreateDecryptor();
            decryptedData = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

            if (!CompareBytes(data, decryptedData))
            {
                Console.WriteLine("ERROR - roundtrip encrypt/decrypt failed!\n");
                Console.WriteLine("Encryption algorithm: {0}", encAlgorithm.ToString());
                Console.WriteLine("Decryption algorithm: {0}", decAlgorithm.ToString());
                Console.WriteLine("Original data: {0}", ByteArrayToString(data));
                Console.WriteLine("Roundtrip data: {0}", ByteArrayToString(decryptedData));
                Console.WriteLine("Key: {0}", ByteArrayToString(key));
                Console.WriteLine("IV: {0}", ByteArrayToString(IV));
                Console.WriteLine("Cipher mode: {0}", mode.ToString());
                Console.WriteLine("Padding mode: {0}", padding.ToString());
                return(false);
            }
        }

        return(true);
    }
コード例 #3
0
	public static bool TestAlgorithms(SymmetricAlgorithm encAlgorithm, SymmetricAlgorithm decAlgorithm, int maxLength, int iterations)
	{
		Random rand = new Random();
		
		for (int i = 0; i < iterations; i++)
		{
			// Create random data, key, IV, mode
			//
			byte[] key = new byte[KeySizeBytes[rand.Next(KeySizeBytes.Length)]];
			rand.NextBytes(key);
			
			byte[] data = new byte[rand.Next(1, maxLength + 1)];
			rand.NextBytes(data);

			byte[] IV = new byte[BlockSizeBytes];
			rand.NextBytes(IV);
			
			// Encrypt the data
			//
			byte[] encryptedData;
			encAlgorithm.Key = key;
			encAlgorithm.IV = IV;

			ICryptoTransform transform = encAlgorithm.CreateEncryptor();
			encryptedData = transform.TransformFinalBlock(data, 0, data.Length);

			// Decrypt the data
			//
			byte[] decryptedData;
			decAlgorithm.Key = key;
			decAlgorithm.IV = IV;

			transform = decAlgorithm.CreateDecryptor();
			decryptedData = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

			if (!CompareBytes(data, decryptedData))
			{
				Console.WriteLine("ERROR - roundtrip encrypt/decrypt failed!\n");
				Console.WriteLine("Encryption algorithm: {0}", encAlgorithm.ToString());
				Console.WriteLine("Decryption algorithm: {0}", decAlgorithm.ToString());
				Console.WriteLine("Original data: {0}", ByteArrayToString(data));
				Console.WriteLine("Roundtrip data: {0}", ByteArrayToString(decryptedData));
				Console.WriteLine("Key: {0}", ByteArrayToString(key));
				Console.WriteLine("IV: {0}", ByteArrayToString(IV));
				return false;
			}
		}

		return true;
	}
コード例 #4
0
ファイル: AesSelector.cs プロジェクト: huaan21/crimson
 public override string ToString()
 {
     return(cipher.ToString());
 }
コード例 #5
0
ファイル: AgileCrypto.cs プロジェクト: x509cert/AgileCrypto
        /// <summary>
        /// Encrypts and MACs some plaintext with a passphrase
        /// </summary>
        /// <param name="passphrase">Password to encrypt/MAC</param>
        /// <param name="plaintext">Text to protect</param>
        /// <returns>Base64 ciphertext blob</returns>
        public string EncryptAndMac(string passphrase, string plaintext)
        {
            if (passphrase.Length == 0 || plaintext.Length == 0)
            {
                throw new ArgumentException();
            }

            // generate a salt from random data (24 bytes) + system tick count (8 bytes)
            byte[] ticks    = BitConverter.GetBytes(DateTime.Now.Ticks);
            var    tempSalt = new byte[_salt.Length - ticks.Length];

            new RNGCryptoServiceProvider().GetBytes(tempSalt);
            Array.Copy(tempSalt, _salt, tempSalt.Length);
            Array.Copy(ticks, 0, _salt, tempSalt.Length, ticks.Length);

            // get PBKDF  info and create object (salt is ignored from config file)
            string  s    = _configData[LinePbkdfsettings].Split(Delim)[1];
            dynamic dp   = new JavaScriptSerializer().DeserializeObject(s);
            int     iter = int.Parse(dp["IterationCount"].ToString());

            _pbkdf = new Rfc2898DeriveBytes(passphrase, _salt, iter);

            // get symmetric cipher info and create object
            _sym = SymmetricAlgorithm.Create(_configData[LineSymalgsettings].Split(Delim)[0]);
            dynamic ds = new JavaScriptSerializer().
                         DeserializeObject(_configData[LineSymalgsettings].Split(Delim)[1]);

            _sym.BlockSize = ds["BlockSize"];
            _sym.KeySize   = ds["KeySize"];
            _sym.Mode      = (CipherMode)ds["Mode"];
            _sym.Padding   = (PaddingMode)ds["Padding"];

            // get HMAC settings and create object
            // TODO: currently uses default alg (SHA-256), need to make it configurable, too
            _hmac = HMAC.Create(_configData[LineHmacsettings].Split(Delim)[0]);

            //
            // Do the dirty work
            //

            // generate symmetric key and HMAC key
            _sym.Key  = _pbkdf.GetBytes(_sym.KeySize >> 3);
            _hmac.Key = _pbkdf.GetBytes(_hmac.HashSize >> 3);

            // perform the crypto opertions
            string ciphertext = Encrypt(plaintext);

            // encrypt then MAC - this MACs the ciphertext
            string hmac = CalculateHmac(ciphertext);

            // serialize the symmetric alg, but strip out the key
            var oSerializer = new JavaScriptSerializer();

            // clear all keys
            //_sym.Key = new byte[_sym.Key.Length];
            //_hmac.Key = new byte[_hmac.Key.Length];

            // serialize the ciphertext/HMAC/PKBDF
            string sJsonSym   = RemoveJunkFromJson(oSerializer.Serialize(_sym));
            string sJsonHmac  = RemoveJunkFromJson(oSerializer.Serialize(_hmac));
            string sJsonPbkdf = oSerializer.Serialize(_pbkdf);

            // build the resulting cipherblob string
            var sb = new StringBuilder();

            sb.Append(_pbkdf.ToString() + Delim + sJsonPbkdf + Crlf);
            sb.Append(_sym.ToString() + Delim + sJsonSym + Crlf);
            sb.Append(_hmac.ToString() + Delim + sJsonHmac + Crlf);
            sb.Append(ciphertext + Crlf);
            sb.Append(hmac);

            return(sb.ToString());
        }