public async Task SerializeAsync(Stream stream, object data, byte[] key) { _cryptoProvider.Key = key; _cryptoProvider.GenerateIV(); await stream.WriteAsync(_cryptoProvider.IV, 0, _cryptoProvider.IV.Length); await stream.WriteAsync(_hashProvider.ComputeHash(key), 0, HashSize); using (var ms = new MemoryStream()) { new BinaryFormatter().Serialize(ms, data); ms.Seek(0, SeekOrigin.Begin); using (var cs = new CryptoStream(stream, _cryptoProvider.CreateEncryptor(), CryptoStreamMode.Write)) { var buffer = new byte[BufferSize]; int bytesRead = 0; while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) > 0) { await cs.WriteAsync(buffer, 0, bytesRead); } } } }
public byte[] GenerateKey() { ThrowIfDisposed(); _algorithm.GenerateKey(); _algorithm.GenerateIV(); return(_algorithm.Key); }
protected Symmetric(SymmetricAlgorithm symmetricAlgorithm, out byte[] key, out byte[] iv) : this(symmetricAlgorithm) { symmetric.GenerateKey(); symmetric.GenerateIV(); key = symmetric.Key; iv = symmetric.IV; }
public int WriteMessage(Stream input) { lock (_lock) { if (_disposed) { return(-1); } //encrypt message data byte[] encryptedData; using (MemoryStream mS = new MemoryStream()) { _crypto.GenerateIV(); //generate new IV for each message encryption since key is same Encrypt(input, mS); encryptedData = mS.ToArray(); } //authenticated encryption in Encrypt-then-MAC (EtM) mode byte[] aeHmac; using (HMAC hmac = new HMACSHA256(_key)) { aeHmac = hmac.ComputeHash(encryptedData); } //write encrypted message data //seek to end of stream _index.Position = _index.Length; _data.Position = _data.Length; //get message offset uint messageOffset = Convert.ToUInt32(_data.Position); //write data BinaryWriter bW = new BinaryWriter(_data); bW.Write((byte)1); //version bW.WriteBuffer(_crypto.IV); bW.WriteBuffer(encryptedData); bW.WriteBuffer(aeHmac); //write message offset to index stream _index.Write(BitConverter.GetBytes(messageOffset), 0, 4); //return message number return(Convert.ToInt32(_index.Position / 4) - 1); } }
public void Encrypt(byte[] input, byte[] key, out byte[] output) { Initialize(); SetKey(key); _cipher.GenerateIV(); var iv = _cipher.IV; var ctx = _cipher.CreateEncryptor(); var encrypted = ctx.TransformFinalBlock(input, 0, input.Length); InsertIvIntoByteArray(encrypted, iv, out output); Destroy(); }
public static string EncryptData(string ClearData) { // Convert string ClearData to byte array byte[] ClearData_byte_Array = Encoding.UTF8.GetBytes(ClearData); // Now Create The Algorithm SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName); Algorithm.Key = GetKey().GetBytes(Algorithm.KeySize / 8); // Encrypt information MemoryStream Target = new MemoryStream(); // Append IV Algorithm.GenerateIV(); Target.Write(Algorithm.IV, 0, Algorithm.IV.Length); // Encrypt Clear Data CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(ClearData_byte_Array, 0, ClearData_byte_Array.Length); cs.FlushFinalBlock(); // Output byte[] Target_byte_Array = Target.ToArray(); string Target_string = Convert.ToBase64String(Target_byte_Array); return(Target_string); }
/// <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(); }
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(); }
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)); }
public Encryptor() { byte[] masterSalt = Owasp.Esapi.Esapi.SecurityConfiguration().MasterSalt; string masterPassword = Owasp.Esapi.Esapi.SecurityConfiguration().MasterPassword; this.encryptAlgorithm = Owasp.Esapi.Esapi.SecurityConfiguration().EncryptionAlgorithm; this.signatureAlgorithm = Owasp.Esapi.Esapi.SecurityConfiguration().DigitalSignatureAlgorithm; this.randomAlgorithm = Owasp.Esapi.Esapi.SecurityConfiguration().RandomAlgorithm; this.hashAlgorithm = Owasp.Esapi.Esapi.SecurityConfiguration().HashAlgorithm; try { SymmetricAlgorithm symmetricAlgorithm = SymmetricAlgorithm.Create(this.encryptAlgorithm); symmetricAlgorithm.GenerateIV(); this.iv = symmetricAlgorithm.IV; symmetricAlgorithm.Padding = PaddingMode.PKCS7; this.secretKey = new PasswordDeriveBytes(masterPassword, masterSalt).CryptDeriveKey(this.encryptAlgorithm, "SHA1", symmetricAlgorithm.KeySize, this.iv); this.encoding = Owasp.Esapi.Esapi.SecurityConfiguration().CharacterEncoding; this.asymmetricKeyPair = new CspParameters(13); this.asymmetricKeyPair.KeyContainerName = "ESAPI"; RandomNumberGenerator.Create(this.randomAlgorithm); } catch (Exception ex) { EncryptionException encryptionException = new EncryptionException("Encryption failure", "Error creating Encryptor", ex); } }
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); } }
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)); } } } } }
public AES() { _Aes = new AesCryptoServiceProvider(); _Aes.KeySize = AES_KEY_SIZE; _Aes.GenerateKey(); _Aes.GenerateIV(); }
/// <summary> /// Gera o vetor de inicialização IV com 128 bits /// </summary> internal void GerarIV() { //Declaração de variáveis SymmetricAlgorithm objRijndael = null; string strIV = null; try { //Cria o objeto de criptografia default "Rijndael" objRijndael = SymmetricAlgorithm.Create(); //Gera uma nova chave objRijndael.KeySize = 128; objRijndael.GenerateIV(); //Converte a chave para base64 strIV = Convert.ToBase64String(objRijndael.IV); //**************************// // // //**************************// } catch (Exception p_objErro) { throw p_objErro; } }
public static byte[] EncryptData(string data, string keyFile) { // Convert string data to byte array byte[] ClearData = Encoding.UTF8.GetBytes(data); // Now Create the algorithm SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName); ReadKey(Algorithm, keyFile); // Encrypt information MemoryStream Target = new MemoryStream(); // Append IV Algorithm.GenerateIV(); Target.Write(Algorithm.IV, 0, Algorithm.IV.Length); // Encrypt actual data CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(ClearData, 0, ClearData.Length); cs.FlushFinalBlock(); // Output the bytes of the encrypted array to the textbox return(Target.ToArray()); }
public byte[] GenerateIV() { SymmetricAlgorithm algorithm = GetAlgorithm(); algorithm.GenerateIV(); return(algorithm.IV); }
/// <summary> /// 生成向量 /// </summary> /// <returns></returns> public static string GenerateIV() { SymmetricAlgorithm aes = Rijndael.Create(); aes.GenerateIV(); return(Convert.ToBase64String(aes.IV));// ASCIIEncoding.ASCII.GetString(aes.IV); }
private byte[] RandomIV(int choice) { SymmetricAlgorithm crypt = SymmetricAlgorithm.Create(sma[choice]); crypt.GenerateIV(); return(crypt.IV); }
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); }
/// <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; }
/// <summary> /// generates a random Initialization Vector, if one was not provided /// </summary> public Data RandomInitializationVector() { _crypto.GenerateIV(); Data d = new Data(_crypto.IV); return(d); }
/// <summary> /// Creates a stream to write raw data to that will be encrypted on the fly /// </summary> /// <param name="encryptionKey">The secret key used to encrypt the data</param> /// <param name="underlying">The underlying stream to write the encrypted data to</param> /// <returns>Returns a <see cref="CryptographicStream"> object to encrypt data on the fly</returns> public static async Task <CryptographicStream> GetEncryptionStreamAsync(byte[] encryptionKey, Stream underlying) { if (encryptionKey == null) { throw new ArgumentNullException(nameof(encryptionKey)); } if (encryptionKey.Length < 1) { throw new ArgumentOutOfRangeException(nameof(encryptionKey.Length)); } if (underlying == null) { throw new ArgumentNullException(nameof(underlying)); } if (underlying.CanWrite == false) { throw new ArgumentOutOfRangeException(nameof(underlying.CanWrite)); } // Create the algorithm to encrypt and generate a unique initialization vector SymmetricAlgorithm alg = CreateAlgorithm(encryptionKey); alg.GenerateIV(); // Create the encryptor and write the IV to the stream unencrypted byte[] iv = alg.IV; ICryptoTransform encryptor = alg.CreateEncryptor(encryptionKey, iv); await underlying.WriteAsync(iv, 0, iv.Length); CryptoStream crypto = new CryptoStream(underlying, encryptor, CryptoStreamMode.Write); return(new CryptographicStream(alg, encryptor, crypto)); }
public static Stream ProcessOutboundStream( Stream inStream, String algorithm, byte[] encryptionkey, out byte[] encryptionIV) { Stream outStream = new System.IO.MemoryStream(); // setup the encryption properties SymmetricAlgorithm alg = SymmetricAlgorithm.Create(algorithm); alg.Key = encryptionkey; alg.GenerateIV(); encryptionIV = alg.IV; CryptoStream encryptStream = new CryptoStream( outStream, alg.CreateEncryptor(), CryptoStreamMode.Write); // write the whole contents through the new streams byte[] buf = new Byte[1000]; int cnt = inStream.Read(buf, 0, 1000); while (cnt > 0) { encryptStream.Write(buf, 0, cnt); cnt = inStream.Read(buf, 0, 1000); } encryptStream.FlushFinalBlock(); outStream.Seek(0, SeekOrigin.Begin); return(outStream); }
/// <summary> /// ''' Creates an instance with a specified algorithm and key. /// ''' /// </summary> /// ''' /// <param name="algorithm">The algorithm to use for cryptographic functions.</param> /// ''' /// <param name="key">The key to use for this algorithm.</param> public SymmetricAlgorithmProvider(SymmetricAlgorithm algorithm, byte[] key) { _algorithm = algorithm; algorithm.Key = key; algorithm.GenerateIV(); _ivSize = algorithm.IV.Length; }
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); } } } } }
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); } } } } }
/// <summary> /// Performs the encryption using the specified encryption algorithm. /// </summary> /// <param name="plaintext">The data to encrypt as a byte array.</param> /// <returns>The encrypte data as a byte array.</returns> public override byte[] Encrypt(byte[] plaintext) { if (algorithm == null) { GetCryptoAlgorithm(); } using (MemoryStream dataStream = new MemoryStream()) { byte[] salt = GetSalt(); dataStream.Write(salt, 0, salt.Length); algorithm.GenerateIV(); dataStream.Write(algorithm.IV, 0, algorithm.IV.Length); algorithm.Key = GetKey(salt); using (ICryptoTransform transform = algorithm.CreateEncryptor()) { using (CryptoStream crypto = new CryptoStream(dataStream, transform, CryptoStreamMode.Write)) { crypto.Write(plaintext, 0, plaintext.Length); crypto.FlushFinalBlock(); dataStream.Flush(); byte[] encData = dataStream.ToArray(); crypto.Close(); return(encData); } } } }
public NetCryptoProviderBase(NetPeer peer, SymmetricAlgorithm algo) : base(peer) { m_algorithm = algo; m_algorithm.GenerateKey(); m_algorithm.GenerateIV(); }
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"); } } }
/// <summary> /// generates a random Initialization Vector, if one was not provided /// </summary> public ByteArray RandomInitializationVector() { m_SymmAlgorithm.GenerateIV(); ByteArray iv = new ByteArray(m_SymmAlgorithm.IV); return(iv); }