public static void TestShims() { using (var alg = new AesManaged()) { alg.BlockSize = 128; Assert.Equal(128, alg.BlockSize); var emptyIV = new byte[alg.BlockSize / 8]; alg.IV = emptyIV; Assert.Equal(emptyIV, alg.IV); alg.GenerateIV(); Assert.NotEqual(emptyIV, alg.IV); var emptyKey = new byte[alg.KeySize / 8]; alg.Key = emptyKey; Assert.Equal(emptyKey, alg.Key); alg.GenerateKey(); Assert.NotEqual(emptyKey, alg.Key); alg.KeySize = 128; Assert.Equal(128, alg.KeySize); alg.Mode = CipherMode.ECB; Assert.Equal(CipherMode.ECB, alg.Mode); alg.Padding = PaddingMode.PKCS7; Assert.Equal(PaddingMode.PKCS7, alg.Padding); } }
/// <summary> /// Encrypt the specified bytes using the given key. /// </summary> /// <param name="bytes">Bytes to encrypt.</param> /// <param name="key">Key to use for encryption.</param> public byte[] Encrypt(byte[] bytes, byte[] key) { using (var aes = new AesManaged()) { aes.KeySize = aes.LegalKeySizes.Max(keySize => keySize.MaxSize); aes.GenerateIV(); aes.Key = key; var cipher = Transform(bytes, aes.CreateEncryptor); return(new EncryptedCipher { Keysize = aes.KeySize, Cipher = cipher, IV = aes.IV }.ToBytes()); } }
static void ProduceLengthCSVFile() { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); SwitchOAEP sc = new SwitchOAEP(); AesManaged aes128 = new AesManaged(); aes128.KeySize = 128; aes128.BlockSize = 128; aes128.GenerateIV(); aes128.GenerateKey(); RijndaelManaged rijndael256 = new RijndaelManaged(); rijndael256.KeySize = 256; rijndael256.BlockSize = 256; rijndael256.GenerateIV(); rijndael256.GenerateKey(); //int[] lengths = new int[] { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 }; //int[] lengths = new int[] { 10, 100, 1000, 10000, 100000, 1000000, 1000001 }; int x = 256; int[] lengths = new int[] { x - 1, x, x + 1, x + 2, x + 3, x + 4, x + 5, x + 6, x + 7, x + 8, x + 9, x + 10, x + 11, x + 12, x + 13, x + 14, x + 15, x + 16 }; string SwitchOAEPInputOutputLengths = "Message Length, SwitchOAEP Ciphertext Length, AES128 Ciphertext Length, RIJ256 Ciphertext Length" + Environment.NewLine; for (int i = 0; i < lengths.Length; i++) { // Create message of appropriate length byte[] message = new byte[lengths[i]]; rng.GetBytes(message); byte[] ciphertextSwitchOAEP = sc.CreateEncryptor().TransformFinalBlock(message, 0, message.Length); byte[] ciphertextAes128 = aes128.CreateEncryptor().TransformFinalBlock(message, 0, message.Length); byte[] ciphertextAes256 = rijndael256.CreateEncryptor().TransformFinalBlock(message, 0, message.Length); string output = message.Length + "," + ciphertextSwitchOAEP.Length + "," + (aes128.IV.Length + ciphertextAes128.Length + 32) + "," + (rijndael256.IV.Length + ciphertextAes256.Length + 32); Console.WriteLine(output); SwitchOAEPInputOutputLengths += output + Environment.NewLine; } File.WriteAllText("CipherLengths.csv", SwitchOAEPInputOutputLengths); }
protected string Encrypt(string blob, string externalKey) { var self = new ECDiffieHellmanCng(); self.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; self.HashAlgorithm = CngAlgorithm.Sha256; publicKey = Convert.ToBase64String(self.PublicKey.ToByteArray()); var externalKeyBytes = Convert.FromBase64String(externalKey); var externalKeyObject = ECDiffieHellmanCngPublicKey.FromByteArray(externalKeyBytes, CngKeyBlobFormat.GenericPublicBlob); var sharedSecret = self.DeriveKeyMaterial(externalKeyObject); var aes = new AesManaged(); aes.Key = sharedSecret; aes.GenerateIV(); var transform = aes.CreateEncryptor(); using (var memoryStream = new MemoryStream()) { var cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write); var data = Encoding.ASCII.GetBytes(blob); cryptoStream.Write(data, 0, data.Length); cryptoStream.Close(); var encryptedData = memoryStream.ToArray(); blob = Convert.ToBase64String(encryptedData); self.Dispose(); aes.Dispose(); return(AddEncryptionHeaders(blob)); } }
public void SetEncodedPassword(string password, string master) { var aes = new AesManaged(); aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.GenerateIV(); aes.Key = Encoding.UTF8.GetBytes(master); byte[] password_binary = Encoding.UTF8.GetBytes(password); this.InitialVector = Convert.ToBase64String(aes.IV); using (var ms = new MemoryStream()) using (var encryptor = aes.CreateEncryptor()) using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) using (var writer = new StreamWriter(cs)) { writer.Write(password); this.Password = Convert.ToBase64String(ms.ToArray()); } }
/// <summary> /// 暗号化 /// </summary> /// <param name="inByte"></param> /// <param name="aesKey"></param> /// <param name="outByte"></param> /// <param name="outIv"></param> private static void Encrypt(byte[] inByte, byte[] aesKey, out byte[] outByte, out byte[] outIv) { using (AesManaged aes = new AesManaged()) { aes.KeySize = 128; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.GenerateIV(); aes.Key = aesKey; using (ICryptoTransform transform = aes.CreateEncryptor()) { byte[] encryptedByte = transform.TransformFinalBlock(inByte, 0, inByte.Length); outByte = encryptedByte; outIv = aes.IV; } }; }
public static (byte[] result, byte[] iv) Encrypt(byte[] value, byte[] key) { if (key == null) { return(value, null); } using (AesManaged aes = new AesManaged()) { aes.KeySize = KEY_SIZE; aes.BlockSize = BLOCK_SIZE; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = key; aes.GenerateIV(); byte[] result = aes.CreateEncryptor().TransformFinalBlock(value, 0, value.Length); return(result, aes.IV); } }
public static Stream EncryptStream(Stream outStream, string password) { using (var am = new AesManaged()) { am.BlockSize = 128; am.KeySize = 128; am.Mode = CipherMode.CBC; am.Padding = PaddingMode.PKCS7; var deriveBytes = new Rfc2898DeriveBytes(password, 16); am.Key = deriveBytes.GetBytes(16); am.GenerateIV(); outStream.Write(deriveBytes.Salt, 0, 16); // !!! outStream.Write(am.IV, 0, 16); var crypter = am.CreateEncryptor(am.Key, am.IV); return(new CryptoStream(outStream, crypter, CryptoStreamMode.Write)); } }
/// <summary> /// ファイルを暗号化する /// </summary> /// <param name="ifs"></param> /// <param name="ofs"></param> /// <param name="password"></param> public static void Encrypt(Stream ifs, Stream ofs, string password) { var keyBytes = FileEncryptor.GetKeyBytes(password); using var aes = new AesManaged() { BlockSize = 128, KeySize = 128, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7, Key = keyBytes, }; aes.GenerateIV(); ofs.Write(aes.IV, 0, aes.IV.Length); using var enc = aes.CreateEncryptor(); using var cs = new CryptoStream(ofs, enc, CryptoStreamMode.Write, true); ifs.CopyTo(cs, 32 * 1024); }
public virtual void Serialize <T>(Stream output, T graph) { Logger.Verbose(Messages.SerializingGraph, typeof(T)); using (var aes = new AesManaged()) { aes.Key = _encryptionKey; aes.Mode = CipherMode.CBC; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (var wrappedOutput = new IndisposableStream(output)) using (var encryptionStream = new CryptoStream(wrappedOutput, encryptor, CryptoStreamMode.Write)) { wrappedOutput.Write(aes.IV, 0, aes.IV.Length); _inner.Serialize(encryptionStream, graph); encryptionStream.Flush(); encryptionStream.FlushFinalBlock(); } } }
public object Serialize <_T>(_T dataToSerialize) { object result; { byte[][] array = new byte[3][]; AesManaged aesManaged = new AesManaged(); aesManaged.KeySize = this.myAesBitSize; aesManaged.GenerateIV(); aesManaged.GenerateKey(); AesSerializer aesSerializer = new AesSerializer(aesManaged.Key, aesManaged.IV, this.myUnderlyingSerializer); array[2] = (byte[])aesSerializer.Serialize <_T>(dataToSerialize); RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider(); rSACryptoServiceProvider.ImportParameters(this.myPublicKey); array[0] = rSACryptoServiceProvider.Encrypt(aesManaged.Key, false); array[1] = rSACryptoServiceProvider.Encrypt(aesManaged.IV, false); object obj = this.myUnderlyingSerializer.Serialize <byte[][]>(array); result = obj; } return(result); }
public static String encrypt(String data, String key) { try { if (key.Length > 32) { throw new System.Security.Cryptography.CryptographicException("Key can't be longer than 32 characters"); } key = key.PadRight(32); AesManaged aes = new AesManaged(); //aes.BlockSize = 256; aes.Key = Encoding.ASCII.GetBytes(key); aes.Mode = CipherMode.CBC; aes.GenerateIV(); ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); byte[] encrypted; using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(data); } encrypted = msEncrypt.ToArray(); } } String main_enc_data = base64_encode(encrypted); String enc_iv = base64_encode(aes.IV); return(main_enc_data + "$" + enc_iv + "$" + checksum(main_enc_data + enc_iv)); } catch (System.Security.Cryptography.CryptographicException e) { return("a Cryptographic exception has occured : " + e.Message); } catch (System.Exception e) { return("an exception has occured : " + e.Message); } }
private static byte[] Encrypt(TlsConnection connection, byte type, ref byte[] data) { byte[] toHash = new byte[13 + data.Length]; toHash[0] = (byte)(connection.TlsSequence >> 56); toHash[1] = (byte)(connection.TlsSequence >> 48); toHash[2] = (byte)(connection.TlsSequence >> 40); toHash[3] = (byte)(connection.TlsSequence >> 32); toHash[4] = (byte)(connection.TlsSequence >> 24); toHash[5] = (byte)(connection.TlsSequence >> 16); toHash[6] = (byte)(connection.TlsSequence >> 8); toHash[7] = (byte)connection.TlsSequence; connection.TlsSequence++; toHash[8] = type; toHash[9] = 3; toHash[10] = 3; toHash[11] = (byte)(data.Length >> 8); toHash[12] = (byte)data.Length; Buffer.BlockCopy(data, 0, toHash, 13, data.Length); var mac = new HMACSHA1(connection.ServerWriteMacKey); byte[] hash = mac.ComputeHash(toHash, 0, toHash.Length); var aes = new AesManaged(); aes.GenerateIV(); aes.Key = connection.ServerWriteKey; aes.Padding = PaddingMode.PKCS7; byte padding = (byte)(((((data.Length + 20) >> 4) + 1) << 4) - data.Length - 21); byte[] toCipher = data.Concat(hash).Concat(new[] { padding }).ToArray(); byte[] encrypted = aes.CreateEncryptor().TransformFinalBlock(toCipher, 0, toCipher.Length); return(aes.IV.Concat(encrypted).ToArray()); }
/// <summary> /// Encrypt the specified bytes using the password as encryption key. /// </summary> /// <param name="bytes">Bytes to encrypt.</param> /// <param name="password">Password to use as encryption key.</param> public byte[] Encrypt(byte[] bytes, string password) { using (var aes = new AesManaged()) { aes.KeySize = aes.LegalKeySizes.Max(keySize => keySize.MaxSize); var saltLength = aes.KeySize / 8; var cryptoKey = CreateSaltAndKey(password, saltLength); aes.GenerateIV(); aes.Key = cryptoKey.Key; var cipher = Transform(bytes, aes.CreateEncryptor); return(new EncryptedCipherWithSalt { Keysize = aes.KeySize, Cipher = cipher, CryptoSalt = cryptoKey.Salt, IV = aes.IV }.ToBytes()); } }
public ActionResult Create(Login login) { if (ModelState.IsValid) { AesManaged aes = new AesManaged(); aes.GenerateKey(); aes.GenerateIV(); string hash, salt; GenerateSaltedHash(login.Password, out hash, out salt); login.Hash = hash; login.Salt = salt; db.Logins.Add(login); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(login)); }
private static string GenerateKey() { AesManaged aesEncryption = new AesManaged(); aesEncryption.KeySize = 192; aesEncryption.GenerateIV(); string ivStr = Convert.ToBase64String(aesEncryption.IV); aesEncryption.GenerateKey(); string keyStr = Convert.ToBase64String(aesEncryption.Key); //Console.WriteLine(ivStr); Console.WriteLine(keyStr); var hmac = new HMACSHA512(); var key = Convert.ToBase64String(hmac.Key); Console.WriteLine("---------"); Console.WriteLine(key); return("ok"); }
/// <summary>加密</summary> /// <param name="plainText"></param> /// <returns></returns> public static string Encrypt(string plainText) { if (string.IsNullOrWhiteSpace(plainText)) { return(string.Empty); } byte[] encrypted; var keyBytes = encoding.GetBytes(_encKey); var encodeBytes = encoding.GetBytes(plainText); using (AesManaged aes = new AesManaged()) { aes.BlockSize = _blockSize; aes.KeySize = _keySize; aes.GenerateIV(); aes.Key = keyBytes; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.ANSIX923; using (var enc = aes.CreateEncryptor()) using (MemoryStream ms = new MemoryStream()) using (CryptoStream writer = new CryptoStream(ms, enc, CryptoStreamMode.Write)) { writer.Write(encodeBytes, 0, encodeBytes.Length); writer.FlushFinalBlock(); var crypto = ms.ToArray(); encrypted = new byte[crypto.Length + aes.IV.Length]; Array.Copy(crypto, encrypted, crypto.Length); Array.Copy(aes.IV, 0, encrypted, crypto.Length, aes.IV.Length); } aes.Clear(); return(Convert.ToBase64String(encrypted)); } }
public static EncryptedString Encrypt(Base64String publicKey, byte[] bytesToEncrypt) { if (string.IsNullOrWhiteSpace(publicKey?.ToString())) { throw new ArgumentException("Should be not empty string", nameof(publicKey)); } if (bytesToEncrypt == null) { return(null); } using (var aes = new AesManaged()) { aes.GenerateKey(); aes.GenerateIV(); var aesKeys = new AesKeysEnvelope(aes.Key.EncodeToBase64(), aes.IV.EncodeToBase64()); var serializedAesKeys = JsonConvert.SerializeObject(aesKeys).ToBase64(); var encryptedAesKeys = RsaEncryption.Encrypt(serializedAesKeys.DecodeToBytes(), publicKey.DecodeToBytes()); using (var encryptor = aes.CreateEncryptor()) using (var encryptedStream = new MemoryStream()) using (var cryptoStream = new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(bytesToEncrypt, 0, bytesToEncrypt.Length); cryptoStream.Flush(); cryptoStream.Close(); var encryptedBody = encryptedStream.ToArray(); var encryptedMessage = new EncryptedMessage(encryptedAesKeys.EncodeToBase64(), encryptedBody.EncodeToBase64()); var serializedEncryptedMessage = JsonConvert.SerializeObject(encryptedMessage).ToBase64(); return(new EncryptedString(serializedEncryptedMessage)); } } }
/// <summary> /// Encrypts <see cref="Credential"/> using AES128-CBC with <see cref="Task.Guid"/> as password for PBKDF2. /// </summary> /// <param name="guid"><see cref="Task.Guid"/> to be used as PBKDF2 password.</param> /// <param name="credential"><see cref="Credential"/> to be encrypted.</param> /// <returns><see cref="string"/> with encrypted <see cref="Credential"/>.</returns> /// This is really more obfuscation than encryption as all compounds are in the config, but it's still good enough as a defense against prying eyes. /// Security-wise this isn't worse than using native Windows Credential Manager as anyone can read passwords from that one too. public static string Encrypt(string guid, Credential credential) { if (string.IsNullOrEmpty(credential.Username) && string.IsNullOrEmpty(credential.Password)) { return(null); } using (AesManaged aes = new AesManaged() { KeySize = 128 }) { aes.GenerateIV(); using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(guid, 16, 1024)) using (ICryptoTransform encryptor = aes.CreateEncryptor(pbkdf2.GetBytes(16), aes.IV)) using (MemoryStream memoryStream = new MemoryStream()) using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) using (BinaryWriter writer = new BinaryWriter(cryptoStream)) { writer.Write(Encoding.UTF8.GetBytes(Serialize(credential))); cryptoStream.FlushFinalBlock(); return(Convert.ToBase64String(pbkdf2.Salt.Concat(aes.IV).Concat(memoryStream.ToArray()).ToArray())); } } }
/// <summary> /// Creates a CryptoStream that encrypts the given input when written to. /// </summary> /// <param name="input">Input stream to encrypt</param> /// <param name="key">Key to use for encryption.</param> public CryptoStream Encrypt(Stream input, byte[] key) { using (var aes = new AesManaged()) { aes.KeySize = aes.LegalKeySizes.Max(keySize => keySize.MaxSize); aes.GenerateIV(); aes.Key = key; var encryptedCipherHeader = new EncryptedCipher { Keysize = aes.KeySize, Cipher = new byte[0], IV = aes.IV }; var headerBytes = encryptedCipherHeader.ToBytes(); input.Write(headerBytes, 0, headerBytes.Length); return(new CryptoStream(input, aes.CreateEncryptor(), CryptoStreamMode.Write)); } }
protected void EncryptMessage(BufferValueWriter writer, ref int headerLength) { AesManaged am = AES; if (am == null) { return; } ICryptoTransform encryptor = null; byte[] iv = null; lock (am) { am.GenerateIV(); iv = am.IV; encryptor = am.CreateEncryptor(); } const int workingHeaderLength = LengthOffset + sizeof(int); // right after length int r = ((writer.Length - workingHeaderLength) % encryptor.OutputBlockSize); if (r != 0) { writer.Pad(encryptor.OutputBlockSize - r); } byte[] payload = encryptor.TransformFinalBlock(writer.Buffer, workingHeaderLength, writer.Length - workingHeaderLength); writer.Length = workingHeaderLength; writer.InsertBytes(workingHeaderLength, BitConverter.GetBytes(iv.Length), 0, sizeof(int)); writer.InsertBytes(workingHeaderLength + sizeof(int), iv, 0, iv.Length); writer.WriteInt32(payload.Length); writer.InsertBytes(writer.Length, payload, 0, payload.Length); headerLength += iv.Length + sizeof(int); }
public void AddNewPoll(Poll p, List <string> mails) { foreach (var login in mails) { if (!String.IsNullOrWhiteSpace(login)) { var v = database.Voters.Where(x => x.Login == login.Trim()).FirstOrDefault(); if (v != null) { p.Voters.Add(v); } } } var timeToEnd = p.EndDate - DateTime.Now; if (timeToEnd <= TimeSpan.Zero) { return; } else { var timer = new System.Timers.Timer(Convert.ToInt64(timeToEnd.TotalMilliseconds)); pollsTimers.Add(timer); timer.AutoReset = false; timer.Elapsed += (sender, e) => PollFinished(p); timer.Start(); } AesManaged aes = new AesManaged(); aes.GenerateIV(); aes.GenerateKey(); p.AesIV = aes.IV; p.AesKey = aes.Key; EncryptPollKey(p, JsonConvert.DeserializeObject <byte[]>("\"f3em5GbGPXYrSuakqSuxIDk31JKoJQNBDzsHqA60gkE=\""), JsonConvert.DeserializeObject <byte[]>("\"7Pe/z8mtaiUD7wa/Mdw2gw==\"")); database.Polls.Add(p); database.SaveChanges(); }
private static void RetrieveOrCreateEncDataToDefaultBlob() { CloudBlob keyBlob = StorageSupport.CurrActiveContainer.GetBlob(KeyBlobName); try { CurrProvider.Key = keyBlob.DownloadByteArray(); } catch (StorageException storageException) { if (storageException.ErrorCode == StorageErrorCode.BlobNotFound) { CurrProvider.KeySize = 128; CurrProvider.GenerateKey(); keyBlob.UploadByteArray(CurrProvider.Key); } else { throw; } } CloudBlob ivBlob = StorageSupport.CurrActiveContainer.GetBlob(IVBlobName); try { CurrProvider.IV = ivBlob.DownloadByteArray(); } catch (StorageException storageException) { if (storageException.ErrorCode == StorageErrorCode.BlobNotFound) { CurrProvider.GenerateIV(); ivBlob.UploadByteArray(CurrProvider.IV); } else { throw; } } }
/// <summary> /// Encrypts a file /// </summary> /// <param name="inputFilePath">Original file path</param> /// <param name="outputFilePath">Encrypted file path</param> /// <param name="password">Password</param> public static void Encrypt(string inputFilePath, string outputFilePath, string password) { var key = GenerateKey(password); var cipher = new AesManaged { KeySize = KeySize, Key = key, BlockSize = BlockSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }; cipher.GenerateIV(); /** * 1. Reads the ogrinal data. (FileStream) * 2. Writes a initial vector. (FileStream) * 3. Compresses the encrypted data. (DeflateStream) * 4. Encrypts the data. (CryptoStream) * 5. Writes the compressed data. (FileStream) */ using (var ifs = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read)) { using (var ofs = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write)) { ofs.Write(cipher.IV, 0, cipher.IV.Length); using (var encryptor = cipher.CreateEncryptor()) { using (var ocfs = new CryptoStream(ofs, encryptor, CryptoStreamMode.Write)) { using (var odcfs = new DeflateStream(ocfs, CompressionMode.Compress, true)) { var buf = new byte[BufferSize]; for (int size = ifs.Read(buf, 0, buf.Length); size > 0; size = ifs.Read(buf, 0, buf.Length)) { odcfs.Write(buf, 0, size); } } } } } } }
public static string Encrypt(string text) { try { var v = Key(); byte[] encrypted; using (AesManaged myAes = new AesManaged()) { myAes.GenerateKey(); myAes.GenerateIV(); var k = myAes.Key; var iv = myAes.IV; encrypted = EncryptStringToBytes_Aes(text, myAes.Key, myAes.IV); string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV); } } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } return(text); }
private Stream Encrypt(Stream data, byte[] encryptionKey, out byte[] initializationVector) { var encryptedData = new MemoryStream(); logger.Debug("Encrypting data..."); using (var algorithm = new AesManaged { KeySize = KEY_SIZE * 8, BlockSize = BLOCK_SIZE * 8, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { algorithm.GenerateIV(); data.Seek(0, SeekOrigin.Begin); initializationVector = algorithm.IV; using (var encryptor = algorithm.CreateEncryptor(encryptionKey, initializationVector)) using (var cryptoStream = new CryptoStream(data, encryptor, CryptoStreamMode.Read)) { cryptoStream.CopyTo(encryptedData); } return(encryptedData); } }
void SettingsChanged(object sender, EventArgs e) { Settings.Default.DownloadUrl = downloadUrlTextBox.Text; Settings.Default.UploadUrl = uploadUrlTextBox.Text; Settings.Default.UploadUserName = uploadUserNameTextBox.Text; if (string.IsNullOrEmpty(Settings.Default.UploadPasswordEntropy)) { using (var crypto = new AesManaged()) { crypto.GenerateIV(); Settings.Default.UploadPasswordEntropy = Convert.ToBase64String(crypto.IV); } } var entropy = Convert.FromBase64String(Settings.Default.UploadPasswordEntropy); var passwordBytes = Encoding.UTF8.GetBytes(uploadPasswordTextBox.Text); var encryptedPasswordBytes = ProtectedData.Protect(passwordBytes, entropy, DataProtectionScope.CurrentUser); Settings.Default.UploadPassword = Convert.ToBase64String(encryptedPasswordBytes); Settings.Default.Save(); }
public static Stream EncryptStream(Stream outStream, byte[] key) { if (key.Length != 16) { throw new ArgumentException(); } using (var am = new AesManaged()) { am.BlockSize = 128; am.KeySize = 128; am.Mode = CipherMode.CBC; am.Padding = PaddingMode.PKCS7; am.Key = key; am.GenerateIV(); outStream.Write(am.IV, 0, 16); var crypter = am.CreateEncryptor(am.Key, am.IV); return(new CryptoStream(outStream, crypter, CryptoStreamMode.Write)); } }
public static string EncryptAsymmetric(byte[] exponent, byte[] modulus, string data) { var bytes = Encoding.UTF8.GetBytes(data); var results = new List <byte>(); using (var aesKeyGen = new AesManaged { KeySize = 256, }) { aesKeyGen.GenerateKey(); aesKeyGen.GenerateIV(); results.AddRange(AddEncryptedKeyAndIv(exponent, modulus, aesKeyGen)); using (var encryptor = aesKeyGen.CreateEncryptor()) { var encryptedBytes = encryptor.TransformEntireBlock(bytes); results.AddRange(encryptedBytes); } } return(BytesToString(results.ToArray())); }
public string Encrypt(string toEncrypt) { using var aesManaged = new AesManaged { KeySize = KeyBitSize, BlockSize = BlockBitSize }; aesManaged.GenerateIV(); var keyBytes = _encryptionKey.HexStringToByteArray(); var ivBytes = aesManaged.IV; using var encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes); using var memoryStream = new MemoryStream(); using var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); using (var streamWriter = new StreamWriter(cryptoStream)) { streamWriter.Write(toEncrypt); } var cipherTextBytes = memoryStream.ToArray(); Array.Resize(ref ivBytes, ivBytes.Length + cipherTextBytes.Length); Array.Copy(cipherTextBytes, 0, ivBytes, BlockBitSize / 8, cipherTextBytes.Length); return(Convert.ToBase64String(ivBytes)); }
/// <summary> /// Encrypts a string of data and converts it to Base64. /// </summary> /// <param name="keyName">The AES key to use to encrypt data.</param> /// <param name="data">The string to encrypt.</param> /// <returns>An encrypted base64 string with the IV attached.</returns> public static EncryptedData Encrypt(string keyName, string data) { byte[] key = null; if (aesKeys.ContainsKey(keyName)) { key = aesKeys[keyName]; } if (key == null) { throw new Exception($"Failed to find a key that matched '{keyName}'"); } AesManaged aes = new AesManaged(); aes.Key = key; aes.GenerateIV(); // Generate a unique IV that can be shared but should "never" be reused. byte[] encrypted; // Encrypt the data ICryptoTransform encryptor = aes.CreateEncryptor(); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { using (StreamWriter sw = new StreamWriter(cs)) { sw.Write(data); } encrypted = ms.ToArray(); } } return(new EncryptedData(encrypted, aes.IV)); }