GenerateIV() public method

public GenerateIV ( ) : void
return void
示例#1
0
        //Copyright (C) 2011, Dextrey (0xDEADDEAD)
        public static byte[] PolyAESEncrypt(byte[] plainText, string Key)
        {
            byte[] salt;
            SymmetricAlgorithm algo = new RijndaelManaged();
            RNGCryptoServiceProvider rngAlgo = new RNGCryptoServiceProvider();
            algo.Mode = CipherMode.CBC;
            byte[] key = System.Text.Encoding.ASCII.GetBytes(Key);

            algo.GenerateIV();
            salt = new byte[32];
            rngAlgo.GetBytes(salt);
            Rfc2898DeriveBytes pwDeriveAlg = new Rfc2898DeriveBytes(key, salt, 2000);
            algo.Key = pwDeriveAlg.GetBytes(32);

            ICryptoTransform encTransform = algo.CreateEncryptor();

            byte[] enced = encTransform.TransformFinalBlock(plainText, 0, plainText.Length);

            int origLength = enced.Length;
            Array.Resize(ref enced, enced.Length + salt.Length);
            Buffer.BlockCopy(salt, 0, enced, origLength, salt.Length);

            origLength = enced.Length;
            Array.Resize(ref enced, enced.Length + algo.IV.Length);
            Buffer.BlockCopy(algo.IV, 0, enced, origLength, algo.IV.Length);

            return enced;
        }
        public AESEncryptStream(byte[] aesKey, Stream data, bool readMode)
        {
            if (readMode && !data.CanRead)
            {
                throw new ArgumentException("Underlying stream is not readable", "data");
            }

            if (!readMode && !data.CanWrite)
            {
                throw new ArgumentException("Underlying stream is not writable", "data");
            }

            _internalStream = data;
            _isRead = readMode;

            var aesProvider = new RijndaelManaged();
            aesProvider.Key = aesKey;
            aesProvider.GenerateIV();
            var encryptor = aesProvider.CreateEncryptor();
            _cryptoStream = new CryptoStream(data, encryptor, _isRead ? CryptoStreamMode.Read : CryptoStreamMode.Write);

            _initialBytesWritten = 0;
            _initialBytes = new byte[aesProvider.IV.Length + 4];
            Buffer.BlockCopy(BitConverter.GetBytes(aesProvider.IV.Length), 0, _initialBytes, 0, 4);
            Buffer.BlockCopy(aesProvider.IV, 0, _initialBytes, 4, aesProvider.IV.Length);
        }
示例#3
0
        public IConfigCommand Encrypt(String password) {
            // Hard error if no password is passed through, but the data is requested to be encrypted.
            if (password == null || password.Length <= 0) throw new ArgumentNullException("password");

            using (RijndaelManaged managed = new RijndaelManaged()) {
                // Generate a new salt.
                byte[] salt = this.GenerateSalt();
                this.Salt = Convert.ToBase64String(salt);

                // Generate new vector.
                managed.GenerateIV();
                this.Vector = Convert.ToBase64String(managed.IV);

                // Derive a key
                byte[] key = this.DeriveKey(password, salt);

                using (StringWriter writer = new StringWriter()) {
                    Potato.Core.Shared.Serialization.JsonSerialization.Minimal.Serialize(writer, this.Command);

                    byte[] text = Encoding.UTF8.GetBytes(writer.ToString());

                    using (ICryptoTransform transform = managed.CreateEncryptor(key, managed.IV)) {
                        this.Data = Convert.ToBase64String(this.CryptoTransform(text, transform));
                    }
                }
            }

            // Don't store the unencrypted data.
            this.Command = null;

            return this;
        }
        public static String Cifrar(String contenido, String clave)
        {
            //tipo de codificacion
            var encoding = new UTF8Encoding();
            //determina cual es el algoritmo de cifrado
            var cripto = new RijndaelManaged();
            //texto q yo quiero cifrar
            byte[] cifrado;
            //array que contiene el IV mas el txt cifrado
            byte[] retorno;
            //convierte la clave en array de bytes
            byte[] key = GeyKey(clave);

            cripto.Key = key;
            //genera array de inicializacion
            cripto.GenerateIV();
            //el texto a encriptar lo convierte en array de byte
            byte[] aEncriptar = encoding.GetBytes(contenido);
            //con el IV y la clave crea un encriptador al final del bloque( el q transforma, dnd empieza, dnd termina)
            cifrado = cripto.CreateEncryptor().TransformFinalBlock(aEncriptar, 0, aEncriptar.Length);
            //prepara lo q va a devolver. Array de bytes q esta compuesto de la longitud del IV mas la longitud de lo q he cifrado
            retorno = new byte[cripto.IV.Length + cifrado.Length];
            //me copias el array del IV empezando en la longitud 0
            cripto.IV.CopyTo(retorno, 0);
            cifrado.CopyTo(retorno, cripto.IV.Length);

            return Convert.ToBase64String(retorno);
        }
        public static byte[] GenerateIV()
        {
            RijndaelManaged provider = new RijndaelManaged();
              provider.GenerateIV();

              return provider.IV;
        }
        /// <summary>
        /// Recibe un texto plano  y lo devuelve cifrado
        /// Cifrado Simetrico
        /// </summary>
        /// <param name="contenido"></param>
        /// <param name="clave"></param>
        /// <returns></returns>
        public static String Cifrar(String contenido, String clave)
        {
            var encoding = new UTF8Encoding();
            var cripto = new RijndaelManaged(); // es un algotimo de cifrado, para cifrar
            //var iv = cripto.GenerateIV(); // Vector de inicialización: es un vector que tiene la semilla de inicialización
            // Este IV

            byte[] cifrado;
            byte[] retorno;
            byte[] key = GetKey(clave); // recibo una clave alfanumerica y devuelvo los bytes desde una cadena UTF8

            cripto.Key = key;
            cripto.GenerateIV(); // genera numeros aleatorios (semillas)
            // voy a crear el encriptador
            byte[] aEncriptar = encoding.GetBytes(contenido); // recibo contenido y lo convierto a array de bites

            // ya lo tengo cifrado
            cifrado = cripto.CreateEncryptor().TransformFinalBlock(aEncriptar, 0, aEncriptar.Length); // transforma el contenido desde 0 hasta que termine

            // creo mi retorno
            retorno = new byte[cripto.IV.Length + cifrado.Length]; // longitud del IV + el tamaño del cifrado

            cripto.IV.CopyTo(retorno, 0); // donde quiero copiar, en que posición quiero copiar
            cifrado.CopyTo(retorno, cripto.IV.Length);
            // la mejor forma es convertirlo a base 64, datos binarios, para almacenar array de bytes
            return Convert.ToBase64String(retorno); //  conjunto de bytes transformados en string
            // muy util para guardar imagenes
        }
        public static string Cifrar(String contenido, String clave)
        {
            //para codificar el texto que quiero cifrar
                var encoding = new UTF8Encoding();
                var cripto=new RijndaelManaged();

                byte[] cifrado;
                byte[] retorno;
                //clave generada en bytes
                byte[] key = GetKey(clave);

                //asigno la clave y ek IV
                cripto.Key = key;
                cripto.GenerateIV();
                byte[] aEncriptar = encoding.GetBytes(contenido);

                //Creo un encriptador CreateEncryptor() el array aEncriptar desde posicion 0
                cifrado = cripto.CreateEncryptor().TransformFinalBlock(aEncriptar, 0, aEncriptar.Length);
                //el array retorno sera = la suma del vector mas longitud del cifrado
                retorno = new byte[cripto.IV.Length + cifrado.Length];

                //copias IV desde la posicion 0
                cripto.IV.CopyTo(retorno,0);

                cifrado.CopyTo(retorno,cripto.IV.Length);
                //convierto la cadena en base 64, por ejemplo una imagen, word, etc
                //contienetodo el flujo de datos

                return Convert.ToBase64String(retorno);
        }
        public override SymmetricAlgorithm GetSymmetricAlgorithm(string algorithm)
        {
            SymmetricAlgorithm s = null;

            switch (algorithm)
            {
            case SecurityAlgorithms.Aes128Encryption:
            case SecurityAlgorithms.Aes192Encryption:
            case SecurityAlgorithms.Aes256Encryption:
            case SecurityAlgorithms.Aes128KeyWrap:
            case SecurityAlgorithms.Aes192KeyWrap:
            case SecurityAlgorithms.Aes256KeyWrap:
                s = new AES();
                break;

            case SecurityAlgorithms.TripleDesEncryption:
            case SecurityAlgorithms.TripleDesKeyWrap:
                if (key.Length == 24)
                {
                    throw new CryptographicException("The key size is 24 bytes, which known as vulnerable and thus not allowed.");
                }
                s = TripleDES.Create();
                break;

            default:
                throw new NotSupportedException(String.Format("This symmetric security key does not support specified algorithm '{0}'", algorithm));
            }
            s.Mode = CipherMode.CBC;
            s.GenerateIV();
            s.Key = key;
            return(s);
        }
示例#9
0
        public static byte[] Encrypt(byte[] input)
        {
            if (_key == null || _key.Length == 0) throw new Exception("Key can not be empty.");
            if (input == null || input.Length == 0) throw new ArgumentException("Input can not be empty.");

            byte[] data = input, encdata = new byte[0];

            try
            {
                using (var ms = new MemoryStream())
                {
                    using (var rd = new RijndaelManaged { Key = _key })
                    {
                        rd.GenerateIV();

                        using (var cs = new CryptoStream(ms, rd.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            ms.Write(rd.IV, 0, rd.IV.Length); // write first 16 bytes IV, followed by encrypted message
                            cs.Write(data, 0, data.Length);
                        }
                    }

                    encdata = ms.ToArray();
                }
            }
            catch
            {
            }
            return encdata;
        }
示例#10
0
        /// encrypt a string message using a secret key that is known to both sender and recipient only;
        /// need to give the initialization vector to the recipient as well;
        static public bool Encrypt(byte[] ASecretKey, string AMessage, out string AEncryptedMessage, out string AInitializationVector)
        {
            Rijndael alg = new RijndaelManaged();

            alg.Key = ASecretKey;

            alg.GenerateIV();

            MemoryStream ms = new MemoryStream();

            CryptoStream encryptStream = new CryptoStream(
                ms,
                alg.CreateEncryptor(),
                CryptoStreamMode.Write);

            System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
            byte[] toEncryptBytes = enc.GetBytes(AMessage);
            encryptStream.Write(toEncryptBytes, 0, toEncryptBytes.Length);
            encryptStream.Close();

            AEncryptedMessage = Convert.ToBase64String(ms.ToArray());
            AInitializationVector = Convert.ToBase64String(alg.IV);

            return true;
        }
示例#11
0
文件: AES.cs 项目: nicoriff/NinoJS
 /// Generates a unique encryption vector
 public static byte[] GenerateEncryptionVector()
 {
     //Generate a Vector
     RijndaelManaged rm = new RijndaelManaged();
     rm.GenerateIV();
     return rm.IV;
 }
        public static String Cifrar(String contenido, String clave)
        {
            var encoding = new UTF8Encoding();
            var cripto = new RijndaelManaged();
            //contenido cifrado
            byte[] cifrado;

            //array que contiene IV + texto cifrado
            byte[] retorno;
            byte[] key = GetKey(clave);

            cripto.Key = key;
            //IV es el patron a partir del cual el algoritmo genera el cifrado
            cripto.GenerateIV();
            byte[] aEncriptar = encoding.GetBytes(contenido);

            cifrado = cripto.CreateEncryptor().TransformFinalBlock(aEncriptar, 0, aEncriptar.Length);

            retorno = new byte[cripto.IV.Length + cifrado.Length];

            cripto.IV.CopyTo(retorno, 0);
            cifrado.CopyTo(retorno, cripto.IV.Length);

            return Convert.ToBase64String(retorno);
        }
示例#13
0
        public static IVCryptoStream Save(string path, byte[] key, byte[] iv)
        {
            FileStream file = new FileStream(path, FileMode.Create);

            RijndaelManaged crypt = new RijndaelManaged();
            crypt.Key = key;

            if (iv == null)
                crypt.GenerateIV();
            else
            {
                Debug.Assert(iv.Length == crypt.IV.Length);
                crypt.IV = iv;
            }

            try
            {
                file.Write(crypt.IV, 0, crypt.IV.Length);
            }
            catch
            {
                file.Dispose();
            }

            return new IVCryptoStream(file, crypt.CreateEncryptor(), CryptoStreamMode.Write);
        }
        EncryptedValue IEncryptionService.Encrypt(string value)
        {
            if (Key == null)
                throw new InvalidOperationException("Cannot encrypt because a Key was not configured. Please specify 'RijndaelEncryptionServiceConfig' in your application's configuration file.");

            using (var rijndael = new RijndaelManaged())
            {
                rijndael.Key = Key;
                rijndael.Mode = CipherMode.CBC;
                rijndael.GenerateIV();

                using (var encryptor = rijndael.CreateEncryptor())
                using (var memoryStream = new MemoryStream())
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                using (var writer = new StreamWriter(cryptoStream))
                {
                    writer.Write(value);
                    writer.Flush();
                    cryptoStream.Flush();
                    cryptoStream.FlushFinalBlock();
                    return new EncryptedValue
                    {
                        EncryptedBase64Value = Convert.ToBase64String(memoryStream.ToArray()),
                        Base64Iv = Convert.ToBase64String(rijndael.IV)
                    };
                }
            }
        }
        public static string Cifrar(string contenido, string clave)
        {
            var encoding=new UTF8Encoding();
            //cifrado asimetrico: se usa cuando se quiera compartir con otros, cuando vaya a viajar
            //y/o tenga que cifrar o descifrar con otra persona (en un trabajo en equipo)
            //cifrado simetrico: yo mismo conmigo mismo.
            var cripto=new RijndaelManaged();

            byte[] cifrado;
            byte[] retorno;
            //la key es un valor fijo, que se define (por ej en el webconfig )
            //y de una clave alfanumerica obtenemos su transformación en un array de bytes
            var key = GetKey(clave);
            //La clave se crea con la key que contiene el array de datos
            cripto.Key = key;
            //El IV es a partir de lo que genera la encriptaciópn. Es un array de bytes
            cripto.GenerateIV();
            byte[] aEncriptar = encoding.GetBytes(contenido);
            //Crea toda la encriptación desde la posición 0 hasta toda la longitud.
            cifrado = cripto.CreateEncryptor().TransformFinalBlock(aEncriptar, 0, aEncriptar.Length);
            //El tamaño del array de retorno es la suma del tamaño de IV + tamaño del cifrado
            retorno=new byte[cripto.IV.Length + cifrado.Length];
            //Estas dos lineas son para copiar el contenido de IV y cifrado.
            //CopyTo tiene dos argumentos, que son qué copiar y desde que posición
            cripto.IV.CopyTo(retorno,0);
            cifrado.CopyTo(retorno,cripto.IV.Length);
            //Se devuelve el array de bytes de cifrado en forma de cadena de texto aunque se puede
            //dejar en bytes para guardarlo en la base de datos
            return Convert.ToBase64String(retorno);
        }
示例#16
0
 public CryptoIV()
 {
     RijndaelManaged symmetricAlgorithm = new RijndaelManaged();
     symmetricAlgorithm.GenerateIV();
     _protectedIV = CryptoUtils.ProtectString(Convert.ToBase64String(symmetricAlgorithm.IV));
     KeySize = symmetricAlgorithm.BlockSize / 8;
 }
		public EncryptedValue Encrypt(string value)
		{
			using (var rijndael = new RijndaelManaged())
			{
				rijndael.Key = Key;
				rijndael.Mode = CipherMode.CBC;
				rijndael.GenerateIV();

				using (var encryptor = rijndael.CreateEncryptor())
				using (var memoryStream = new MemoryStream())
				using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
				using (var writer = new StreamWriter(cryptoStream))
				{
					writer.Write(value);
					writer.Flush();
					cryptoStream.Flush();
					cryptoStream.FlushFinalBlock();
					return new EncryptedValue
					{
                        EncryptedBase64Value = Convert.ToBase64String(memoryStream.ToArray()),
						Base64Iv = Convert.ToBase64String(rijndael.IV)
					};
				}
			}
		}
示例#18
0
 public byte[] CreateIV()
 {
     var r = new RijndaelManaged();
     r.GenerateIV();
     var result = r.IV;
     r.Dispose();
     return result;
 }
示例#19
0
 public static string Encrypt(string unencrypted)
 {
     var rm = new RijndaelManaged();
     rm.GenerateIV();
     var IV = rm.IV;
     var cryptogram = IV.Concat(Encrypt(_encoder.GetBytes(unencrypted), IV));
     return Convert.ToBase64String(cryptogram.ToArray());
 }
 public Base64EncodedRijndaelKeyVectorPair()
 {
     RijndaelManaged rm = new RijndaelManaged();
     rm.GenerateKey();
     rm.GenerateIV();
     this.Key = Convert.ToBase64String(rm.Key);
     this.IV = Convert.ToBase64String(rm.IV);
 }
示例#21
0
 static void Main(string[] args)
 {
     RijndaelManaged rm = new RijndaelManaged();
     rm.GenerateKey();
     rm.GenerateIV();
     string key = Convert.ToBase64String(rm.Key);
     string iv = Convert.ToBase64String(rm.IV);
 }
示例#22
0
        public static byte[] Encrypt(string unencryptedString) {
            using (var myRijndael = new RijndaelManaged()) {
                myRijndael.GenerateKey();
                myRijndael.GenerateIV();

                return EncryptStringToBytes(unencryptedString, myRijndael.Key, myRijndael.IV);
            }
        }
示例#23
0
 /// <summary>
 /// Genera un vettore iniziale compatibile per la trasmissione in URL che deve essere utilizzato per poter decifrare un messaggio cifrato.
 /// </summary>
 /// <returns>Segreto</returns>
 public string GeneraVettore()
 {
     using (var myRijndael = new RijndaelManaged())
     {
         myRijndael.GenerateIV();
         return HttpServerUtility.UrlTokenEncode(myRijndael.IV);
     }
 }
示例#24
0
        public static string Decrypt(byte[] encryptedString) {
            using (var myRijndael = new RijndaelManaged()) {
                myRijndael.GenerateKey();
                myRijndael.GenerateIV();

                return DecryptStringFromBytes(encryptedString, myRijndael.Key, myRijndael.IV);
            }
        }
示例#25
0
 private System.Security.Cryptography.RijndaelManaged GetCryptographer()
 {
     System.Security.Cryptography.RijndaelManaged rijndaelManaged = new System.Security.Cryptography.RijndaelManaged();
     rijndaelManaged.KeySize = 128;
     rijndaelManaged.GenerateIV();
     rijndaelManaged.GenerateKey();
     return(rijndaelManaged);
 }
		public AESKeyAndIVGenerator ()
		{
            rijndaelManaged = new RijndaelManaged();
            rijndaelManaged.KeySize = 256;

			rijndaelManaged.GenerateKey ();
			rijndaelManaged.GenerateIV ();

			aesKey = rijndaelManaged.Key;
			aesIV = rijndaelManaged.IV;
		}
示例#27
0
 public String Encrypt(String StringToEncrypt, String Key32)
 {
     if (Key32.Length != 32) return String.Empty;
     if (StringToEncrypt == String.Empty) return String.Empty;
     RijndaelManaged myRijndael = new RijndaelManaged();
     myRijndael.Key = str_to_bytes(Key32);
     myRijndael.GenerateIV();
     String encrypted = Convert.ToBase64String(encryptStringToBytes_AES(StringToEncrypt, myRijndael.Key, myRijndael.IV), Base64FormattingOptions.None);
     String iv = Convert.ToBase64String(myRijndael.IV, Base64FormattingOptions.None);
     return iv + "|" + encrypted;
 }
示例#28
0
        /// <summary>
        /// Generates a new salt
        /// </summary>
        public string GenerateNewIv()
        {
            var rijndael = new RijndaelManaged
                {
                    Key = key
                };

            rijndael.GenerateIV();

            return Convert.ToBase64String(rijndael.IV);
        }
    //[MenuItem("Hugula AES/GenerateIV", false, 13)]
    public static void GenerateIV()
    {
        using (System.Security.Cryptography.RijndaelManaged myRijndael = new System.Security.Cryptography.RijndaelManaged()) {
            myRijndael.GenerateIV();
            byte[] IV = myRijndael.IV;

            KeyVData KeyScri = ScriptableObject.CreateInstance <KeyVData>();
            KeyScri.IV = IV;
            AssetDatabase.CreateAsset(KeyScri, "Assets/Config/K81.asset");
            Debug.Log("IV Generate " + IV.Length);
        }
    }
示例#30
0
        /// <summary>
        /// 共通キーと初期化ベクトルを返す
        /// </summary>
        /// <param name="key">作成された共通キー</param>
        /// <param name="IV">作成された初期化ベクトル</param>
        public static void CreateKeys(out byte[] key, out byte[] IV)
        {
            using (RijndaelManaged aes = new RijndaelManaged())
            {
                aes.KeySize = 256;

                aes.GenerateKey();
                aes.GenerateIV();

                key = aes.Key;
                IV = aes.IV;
            }
        }
示例#31
0
    //[MenuItem("Hugula AES/GenerateIV", false, 13)]
	public static void GenerateIV() 
	{ 
		using (System.Security.Cryptography.RijndaelManaged myRijndael = new System.Security.Cryptography.RijndaelManaged()) {
			
			myRijndael.GenerateIV ();
			byte[]  IV=myRijndael.IV;

			KeyVData KeyScri=ScriptableObject.CreateInstance<KeyVData>();
			KeyScri.IV=IV;
			AssetDatabase.CreateAsset(KeyScri,"Assets/Config/K81.asset");
			Debug.Log("IV Generate "+IV.Length);
		}
	}
示例#32
0
 byte[] GenerateIv()
 {
     using (var c = new RijndaelManaged()
     {
         KeySize = 256, // defaults to 256, it's better to be explicit.
         BlockSize = 256, // defaults to 128 bits, so let's set this to 256 for better security
         Mode = CipherMode.CBC,
         Padding = PaddingMode.ISO10126, // adds random padding bytes which reduces the predictability of the plain text
     })
     {
         c.GenerateIV();
         return c.IV;
     }
 }
示例#33
0
        public static IV GenerateRandomIv(AllowedBlockSizes blockSize)
        {
            byte[] ivBytes = new byte[(int)blockSize / 8];

            using (var rijndael = new RijndaelManaged())
            {
                rijndael.BlockSize = (int)blockSize;

                rijndael.GenerateIV();

                rijndael.IV.CopyTo(ivBytes, 0);
            }

            return new IV(ivBytes);
        }
示例#34
0
        public static byte[] smethod_4(byte[] byte_0, string string_0)
        {
            System.Security.Cryptography.SymmetricAlgorithm       symmetricAlgorithm       = new System.Security.Cryptography.RijndaelManaged();
            System.Security.Cryptography.RNGCryptoServiceProvider rNGCryptoServiceProvider = new System.Security.Cryptography.RNGCryptoServiceProvider();
            symmetricAlgorithm.Mode = System.Security.Cryptography.CipherMode.CBC;
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(string_0);
            symmetricAlgorithm.GenerateIV();
            byte[] array = new byte[32];
            rNGCryptoServiceProvider.GetBytes(array);
            System.Security.Cryptography.Rfc2898DeriveBytes rfc2898DeriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(bytes, array, 2000);
            symmetricAlgorithm.Key = rfc2898DeriveBytes.GetBytes(32);
            System.Security.Cryptography.ICryptoTransform cryptoTransform = symmetricAlgorithm.CreateEncryptor();
            byte[] array2    = cryptoTransform.TransformFinalBlock(byte_0, 0, byte_0.Length);
            int    dstOffset = array2.Length;

            System.Array.Resize <byte>(ref array2, array2.Length + array.Length);
            System.Buffer.BlockCopy(array, 0, array2, dstOffset, array.Length);
            dstOffset = array2.Length;
            System.Array.Resize <byte>(ref array2, array2.Length + symmetricAlgorithm.IV.Length);
            System.Buffer.BlockCopy(symmetricAlgorithm.IV, 0, array2, dstOffset, symmetricAlgorithm.IV.Length);
            return(array2);
        }
 public override void GenerateIV()
 {
     m_rijndael.GenerateIV();
 }