/// <summary> /// Creates a symmetric key. See this link for more information behind the numbers /// http://blogs.msdn.com/b/shawnfa/archive/2006/10/09/the-differences-between-rijndael-and-aes.aspx /// </summary> /// <returns></returns> private SymmetricKey CreateNewAESSymmetricKeyset() { if (cert == null) { throw new InvalidOperationException("Unable to create new AES keyset; Certificate not loaded."); } byte[] symmKey, iv; using (AesManaged aes = new AesManaged()) { aes.GenerateIV(); aes.GenerateKey(); symmKey = aes.Key; iv = aes.IV; aes.Clear(); } // Encrypt the Symmetric Key for storage byte[] encryptedKey = EncryptRSA(symmKey, cert); SymmetricKey symmKeySet = new SymmetricKey() { iv = iv, Key = encryptedKey, CertificateThumbprint = cert.Thumbprint }; return symmKeySet; }
public void DecryptsToOriginalPlainText() { byte[] plaintextBytes = Encoding.UTF8.GetBytes("This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least."); byte[] decryptedBytes; using (SymmetricAlgorithm algorithm = new AesManaged()) { byte[] wrongDecryptionKey = algorithm.Key; algorithm.GenerateKey(); byte[] encryptionKey = algorithm.Key; Assert.AreNotEqual(encryptionKey, wrongDecryptionKey); byte[] ciphertextBytes, iv; using (Encryptor encryptor = algorithm.CreateEncryptor(encryptionKey, out iv)) { Assert.AreEqual(encryptionKey, encryptor.Algorithm.Key); Assert.AreEqual(iv, encryptor.Algorithm.IV); ciphertextBytes = encryptor.Encrypt(plaintextBytes); } using (Decryptor decryptor = new Decryptor(algorithm, encryptionKey, iv, Encryption.DefaultOptions)) { Assert.AreEqual(encryptionKey, decryptor.Algorithm.Key); Assert.AreEqual(iv, decryptor.Algorithm.IV); decryptedBytes = decryptor.Decrypt(ciphertextBytes); } } Assert.AreEqual(plaintextBytes, decryptedBytes); }
public EncryptedMessage Encrypt(byte[] input) { var em = new EncryptedMessage(); using (var aes = new AesManaged()) { aes.KeySize = 256; aes.GenerateIV(); aes.GenerateKey(); em.IV = aes.IV; em.Key = aes.Key; em.EncryptionType = MessageEncryptionType.Aes; using (var encryptor = aes.CreateEncryptor()) { using (var msOutput = new MemoryStream()) { using (var cryptoStream = new CryptoStream(msOutput, encryptor, CryptoStreamMode.Write)) { using (var msInput = new MemoryStream(input)) { msInput.CopyTo(cryptoStream); } } em.CipherBytes = msOutput.ToArray(); } } return em; } }
/// <summary> /// Create a new encryption key with the specified key size /// </summary> public static byte[] GenerateKey() { var aes = new System.Security.Cryptography.AesManaged(); aes.KeySize = 256; aes.GenerateKey(); return(aes.Key); }
public AESEncryption() { Algorithm = new AesManaged(); Algorithm.KeySize = 256; Algorithm.Mode = CipherMode.CBC; Algorithm.GenerateIV(); Algorithm.GenerateKey(); Algorithm.Padding = PaddingMode.PKCS7; }
public static byte[] GenerateAESKey() { using (var provider = new AesManaged()) { provider.KeySize = 256; provider.GenerateKey(); return provider.Key; } }
/// <summary> /// Generates a new random 256bit AES key. /// This can be used for the encryption of keys in the HOTP/TOTP classes /// </summary> /// <returns>256bit AES key</returns> public static byte[] GenerateNewAesKey() { using (AesManaged aesAlg = new AesManaged()) { aesAlg.KeySize = 256; aesAlg.GenerateKey(); return aesAlg.Key; } }
private void GenerateEncryptionParameters(X509Certificate2 certificate) { var aesManaged = new AesManaged(); aesManaged.GenerateIV(); aesManaged.GenerateKey(); string ivToStoreInConfig = Convert.ToBase64String(aesManaged.IV); string encryptionKeyAsString = Convert.ToBase64String(aesManaged.Key); string keyToStoreInConfig = RsaEncrypt(certificate, encryptionKeyAsString); ConfigurationManager.AppSettings["EncryptionIV"] = ivToStoreInConfig; ConfigurationManager.AppSettings["EncryptionKey"] = keyToStoreInConfig; }
private static void GenerateAESKeys() { var sw = Stopwatch.StartNew(); var aesM = new AesManaged(); for (int i = 0; i < NUM_AES_KEYS; i++) { aesM.GenerateKey(); byte[] result = aesM.Key; string hexString = ConvertToHexString(result); //Console.WriteLine("AES KEY{0}",hexString); } // Console.WriteLine("AES KEY:" + sw.Elapsed.ToString()); }
public SymmetricKey CreateNewAesSymmetricKeyset() { var aes = new AesManaged(); aes.GenerateIV(); aes.GenerateKey(); var symmKeySet = new SymmetricKey() { Iv = RsaEncryptBytes(aes.IV), Key = RsaEncryptBytes(aes.Key) }; return symmKeySet; }
static TokenCrypt() { try { CryptKey = JsonHelper.ParseJson<AesKey>(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, KeyFile)).Trim()); } catch(FileNotFoundException) { using(var aes = new AesManaged()) { aes.GenerateKey(); aes.GenerateIV(); CryptKey = new AesKey { Key = aes.Key, IV = aes.IV }; File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, KeyFile), CryptKey.ToJsonString()); } } }
public UnityCryptoManager() { m_RSA_Exch_Formatter = new RiaWebSoftRu.Cryptography.Crypto.Formater.RSAESPKCSFormater(); m_RSA = new RiaWebSoftRu.Cryptography.Crypto.RsaManaged(m_KeySize); m_SHA = new SHA256Managed(); m_RIJ = new AesManaged(); //m_RSA.GenerateKey(); Not necessary in unity. Unity clients gets a public key from server and uses that to encrypt the Rijndael key m_SHA = new SHA256Managed(); m_RIJ.Padding = PaddingMode.PKCS7; m_RIJ.Mode = CipherMode.CBC; m_RIJ.IV = new byte[16]; m_RIJ.BlockSize = 128; m_RIJ.KeySize = 256; m_RIJ.GenerateKey(); m_PublicKey = Encoding.UTF8.GetBytes(m_RSA.ToXmlString(false).ToString()); m_PrivateKey = Encoding.UTF8.GetBytes(m_RSA.ToXmlString(true).ToString()); }
public AESCipher() { this.utf8Encoding = new System.Text.UTF8Encoding(); this.aes = new AesManaged(); this.aes.Mode = CipherMode.CBC; this.aes.Padding = PaddingMode.PKCS7; this.aes.KeySize = 128; this.aes.BlockSize = 128; aes.GenerateKey(); aes.GenerateIV(); if (File.Exists(@"C:\Users\Chris\Documents\Cambridge\Part II Project\Code\Encryption Example\EncryptionExample\AESkey.xml") == true) File.Delete(@"C:\Users\Chris\Documents\Cambridge\Part II Project\Code\Encryption Example\EncryptionExample\AESkey.xml"); //provide AES encryption key params FileStream fs = new FileStream(@"C:\Users\Chris\Documents\Cambridge\Part II Project\Code\Encryption Example\EncryptionExample\AESkey.xml", FileMode.CreateNew, FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(fs); string aesKeyXML = byte2Hex(aes.Key); sw.Write("<AESkey>"+ aesKeyXML + "</AESkey>"); sw.Close(); fs.Close(); }
/** * Encrypts a specified string using AES encryption and returns * the encrypted string and key used. */ public static string[] Encrypt(string str) { byte[] bytes = Encoding.UTF8.GetBytes(str); var manager = new AesManaged { KeySize = 256, Padding = PaddingMode.PKCS7 }; manager.GenerateKey(); manager.GenerateIV(); ICryptoTransform c = manager.CreateEncryptor(); bytes = c.TransformFinalBlock(bytes, 0, bytes.Length); string hash = BitConverter.ToString(manager.IV).Replace("-", ""); hash += BitConverter.ToString(bytes).Replace("-", ""); string key = BitConverter.ToString(manager.Key).Replace("-", ""); return new[] {hash, key}; }
public static byte[] EncryptStringToByte(string sourceText,ref byte[] key,ref byte[] IV) { if (sourceText == null || sourceText == "") { return null; } byte[] result; AesManaged aesAlg = new AesManaged(); if (key == null || key.Length <= 0 || IV == null || IV.Length <= 0) { aesAlg.GenerateKey(); aesAlg.GenerateIV(); key = aesAlg.Key; IV = aesAlg.IV; } else { aesAlg.Key = key; aesAlg.IV = IV; } ICryptoTransform encryptor = aesAlg.CreateEncryptor(); MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt,encryptor, CryptoStreamMode.Write); StreamWriter swEncrypt = new StreamWriter(csEncrypt); swEncrypt.Write(sourceText); swEncrypt.Close(); csEncrypt.Close(); result = msEncrypt.ToArray(); return result; }
public static string EncryptAssymetric(Tuple<byte[], byte[]> parameters, 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(parameters, aesKeyGen)); using (var encryptor = aesKeyGen.CreateEncryptor()) { var encryptedBytes = encryptor.TransformEntireBlock(bytes); results.AddRange(encryptedBytes); } } return BytesToString(results.ToArray()); }
public void RsaHelperBytesShouldSucceed() { var directory = TestContext.DeploymentDirectory; var helper = new RsaHelper(Path.Combine(directory, "TestCertificate.pfx"), CertificatePassword); var aes = new AesManaged(); aes.GenerateIV(); aes.GenerateKey(); var originalKey = aes.Key; var originalIv = aes.IV; var encryptedKeyBytes = helper.RsaEncryptBytes(aes.Key); var encryptedIvBytes = helper.RsaEncryptBytes(aes.IV); encryptedIvBytes.Should().NotBeNull("IV failed to encrypt"); encryptedKeyBytes.Should().NotBeNull("Key failed to encrypt"); var decryptedKeyBytes = helper.RsaDecryptToBytes(encryptedKeyBytes); var decryptedIvBytes = helper.RsaDecryptToBytes(encryptedIvBytes); originalKey.ShouldBeEquivalentTo(decryptedKeyBytes); originalIv.ShouldBeEquivalentTo(decryptedIvBytes); }
internal static void GenerateKey(this Settings s, ref AesManaged AES) { AES.GenerateIV(); AES.GenerateKey(); s.Key = AES.Key; s.IV = AES.IV; s.IsFirst = false; }
private void EncryptToFile(string data, string filepath) { // Gets the bytes from the string. byte[] binData = Encoding.UTF8.GetBytes(data); // AES encryption of the source file. byte[] aesKey, aesIv; byte[] aesEncData; using (AesManaged aes = new AesManaged()) { // Generates a random AES key and IV. aes.GenerateKey(); aes.GenerateIV(); aesKey = aes.Key; aesIv = aes.IV; // Encrypts the data. ICryptoTransform ct = aes.CreateEncryptor(); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write)) { using (BinaryWriter bw = new BinaryWriter(cs)) { bw.Write(binData); } } aesEncData = ms.ToArray(); } } // Loads the RSA public key. RSAParameters rsaPublicKey = LoadRSAPublicKey(); // RSA encryption of the AES key+iv. byte[] rsaEncAesKey, rsaEncAesIv; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { // Imports the key. rsa.ImportParameters(rsaPublicKey); // Performs encryption. rsaEncAesKey = rsa.Encrypt(aesKey, false); rsaEncAesIv = rsa.Encrypt(aesIv, false); } // Writes the encrypted data. using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream fs = isf.OpenFile(filepath, FileMode.Create)) { using (BinaryWriter bw = new BinaryWriter(fs)) { // Key length + data. bw.Write(rsaEncAesKey.Length); bw.Write(rsaEncAesKey); // IV length + data. bw.Write(rsaEncAesIv.Length); bw.Write(rsaEncAesIv); // AES encrypted length + data bw.Write(aesEncData.Length); bw.Write(aesEncData); } } } }
static void Main(string[] args) { try { string original = "aaaaaaaaaaaaaaa"; char result; using (AesManaged myAes = new AesManaged()) { myAes.KeySize = 256; myAes.BlockSize = 128; myAes.GenerateIV(); myAes.GenerateKey(); //myAes.Key = GetBytes("chave"); // transformar em bytes //myAes.IV = GetBytes("Sal"); // transformar em bytes byte[] encrypted = EncryptedStringToBytes_Aes(original, myAes.Key, myAes.IV); string criptb64 = System.Convert.ToBase64String(encrypted, 0, encrypted.Length); string cript = GetString(encrypted); string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV); Console.WriteLine($"1 Original: {original} tamanho: {original.Length}"); Console.WriteLine($"2 encryped: {cript} tamanho: {cript.Length}"); foreach(byte number in encrypted) { result = Convert.ToChar(number); Console.WriteLine($"number: {number} convert: {result}"); } Console.WriteLine($"3 cript64: {criptb64} tamanho: {criptb64.Length}"); Console.WriteLine($"4 roundtrip: {roundtrip} tamanho: {roundtrip.Length}"); } } catch (Exception e) { Console.WriteLine($"Erro: {e.Message}"); } Console.ReadKey(); }
private void Load() { string companyAcronym; // Try to populate defaults for subscriber acronym and name using company information from the host application configuration file if (TryGetCompanyAcronym(out companyAcronym)) { SubscriberAcronym = companyAcronym; SubscriberName = string.Format("{0} Subscription Authorization", companyAcronym); } // Connect to database to retrieve company information for current node using (AdoDataConnection database = new AdoDataConnection(CommonFunctions.DefaultSettingsCategory)) { try { string query = database.ParameterizedQueryString("SELECT Company.Acronym, Company.Name FROM Company, Node WHERE Company.ID = Node.CompanyID AND Node.ID = {0}", "id"); DataRow row = database.Connection.RetrieveRow(database.AdapterType, query, database.CurrentNodeID()); PublisherAcronym = row.Field<string>("Acronym"); PublisherName = row.Field<string>("Name"); // Generate a default shared secret password for subscriber key and initialization vector byte[] buffer = new byte[4]; Random.GetBytes(buffer); string generatedSecret = Convert.ToBase64String(buffer).RemoveCrLfs(); if (generatedSecret.Contains("=")) generatedSecret = generatedSecret.Split('=')[0]; SharedKey = generatedSecret; // Generate an identity for this subscriber AesManaged sa = new AesManaged(); sa.GenerateKey(); IdentityCertificate = Convert.ToBase64String(sa.Key); // Generate valid local IP addresses for this connection IEnumerable<IPAddress> addresses = Dns.GetHostAddresses(Dns.GetHostName()).OrderBy(key => key.AddressFamily); ValidIPAddresses = addresses.ToDelimitedString("; "); } catch (Exception ex) { MessageBox.Show("ERROR: " + ex.Message, "Subscriber Request", MessageBoxButton.OK); } try { Dictionary<string, string> settings; string server; string[] splitServer; int dataPublisherPort; //IPAddress[] hostIPs = null; //IEnumerable<IPAddress> localIPs; settings = database.DataPublisherConnectionString().ToNonNullString().ParseKeyValuePairs(); //localIPs = Dns.GetHostAddresses("localhost").Concat(Dns.GetHostAddresses(Dns.GetHostName())); if (settings.TryGetValue("server", out server)) { splitServer = server.Split(':'); //hostIPs = Dns.GetHostAddresses(splitServer[0]); if (splitServer.Length > 1 && int.TryParse(splitServer[1], out dataPublisherPort)) InternalDataPublisherPort = dataPublisherPort; } // These messages show up when not desired and are not very useful anymore... //// Check to see if entered host name corresponds to a local IP address //if (hostIPs == null) // MessageBox.Show("Failed to find service host address. If using Gateway security, secure key exchange may not succeed." + Environment.NewLine + "Please make sure to run manager application with administrative privileges on the server where service is hosted.", "Subscription Request", MessageBoxButton.OK, MessageBoxImage.Warning); //else if (!hostIPs.Any(ip => localIPs.Contains(ip))) // MessageBox.Show("If using Gateway security, secure key exchange may not succeed." + Environment.NewLine + "Please make sure to run manager application with administrative privileges on the server where service is hosted.", "Subscription Request", MessageBoxButton.OK, MessageBoxImage.Warning); } catch { MessageBox.Show("Please make sure to run manager application with administrative privileges on the server where service is hosted.", "Subscription Request", MessageBoxButton.OK, MessageBoxImage.Warning); } } }
/// <summary> /// Generate a new random AES key for symmetric encryption /// </summary> /// <returns>Returns a byte array containing the key</returns> public static byte[] GenerateAESPrivateKey() { AesManaged AES = new AesManaged(); AES.KeySize = 128; AES.GenerateKey(); return AES.Key; }
/// <summary> /// Generates a random key to use for the symmetric algorithm. /// </summary> /// <returns>The secret key used for the symmetric algorithm.</returns> public static byte[] GenerateKey() { byte[] key; using (var aes = new AesManaged()) { aes.GenerateKey(); key = aes.Key; } return key; }
/// <summary> /// Encrypts a value using the requested certificate. /// The certificate must have a valid RSA public key. /// </summary> /// <param name="value">The value to be encrypted.</param> /// <param name="certificate">The certificate used to encrypt the value.</param> /// <remarks> /// First a cryptographically random AES key is generated. /// The value is encrypted using that AES key. /// The AES key is then encrypted using the RSA key from the certificate. /// Then the encrypted value is joined with the encrypted AES key. /// That result is base 64 encoded and returned. /// /// The format of the result in binary (before base 64 encoding) is the following: /// [AES key length in bytes] - Length: 4 bytes /// [AES block size in bytes] - Length: 4 bytes /// [AES key encrypted length in bytes] - Length: 4 bytes /// [AES initialization vector encrypted length in bytes] - Length: 4 bytes /// [Certificate public key length in bytes] - Length: 4 bytes /// [Certificate public key] - Length: Public key length /// [Encrypted AES key] - Length: AES key encrypted length bytes /// [Encrypted AES initialization vector] - Length: AES Block size bytes /// [Encrypted value] - Length: remaining data length /// </remarks> /// <returns>The encrypted, base64-encoded value.</returns> public static string Encrypt(string value, X509Certificate2 certificate) { const int keySizeBits = 256; const int keySizeBytes = keySizeBits / 8; const int blockSizeBits = 128; const int blockSizeBytes = blockSizeBits / 8; // Get the RSA key from the certificate var rsa = certificate.PublicKey.Key as RSACryptoServiceProvider; if (rsa == null) { throw new InvalidOperationException("Certificate does not contain an RSA public key."); } // Get the public key as a byte array var publicKey = certificate.GetPublicKey(); using (var aes = new AesManaged { KeySize = keySizeBits, BlockSize = blockSizeBits, Mode = CipherMode.CBC }) { // Generate a cryptographically random initialization vector and key aes.GenerateIV(); aes.GenerateKey(); if (aes.IV.Length != blockSizeBytes) { throw new InvalidOperationException("AES IV size is not equal to the block size."); } // Encrypt the AES key and initialization vector var keyBytes = rsa.Encrypt(aes.Key, false); var ivBytes = rsa.Encrypt(aes.IV, false); using (var memory = new MemoryStream()) { // Write the AES key length and block size memory.WriteInt(keySizeBytes); memory.WriteInt(blockSizeBytes); // Write the sizes of the encrypted AES key and initialization vector memory.WriteInt(keyBytes.Length); memory.WriteInt(ivBytes.Length); // Write the size of the certificate public key memory.WriteInt(publicKey.Length); // Write the public key memory.Write(publicKey, 0, publicKey.Length); // Write the encrypted AES key and initialization vector memory.Write(keyBytes, 0, keyBytes.Length); memory.Write(ivBytes, 0, ivBytes.Length); // Encrypt and write the actual value using the aes encryption using (var transform = aes.CreateEncryptor()) using (var crypto = new CryptoStream(memory, transform, CryptoStreamMode.Write)) { var bytes = Encoding.UTF8.GetBytes(value); crypto.Write(bytes, 0, bytes.Length); crypto.FlushFinalBlock(); } // Return the base 64 encoded result return Convert.ToBase64String(memory.ToArray(), Base64FormattingOptions.InsertLineBreaks); } } }
public static Byte[] GenFreshAESKeys() { AesManaged aes = new AesManaged(); aes.GenerateKey(); return aes.Key; }
protected override void OnTempestMessageReceived(MessageEventArgs e) { switch (e.Message.MessageType) { case (ushort)TempestMessageType.Ping: var ping = (PingMessage)e.Message; if (PingFrequency == 0 || this.activityTimer == null) { if (this.activityTimer != null) this.activityTimer.Dispose(); if (ping.Interval != 0) { this.activityTimer = new Tempest.Timer (100); this.activityTimer.TimesUp += OnActivityTimer; this.activityTimer.Start(); } } else if (ping.Interval != PingFrequency) this.activityTimer.Interval = ping.Interval; base.OnTempestMessageReceived (e); break; case (ushort)TempestMessageType.AcknowledgeConnect: var msg = (AcknowledgeConnectMessage)e.Message; this.protocols = this.protocols.Values.Intersect (msg.EnabledProtocols).ToDictionary (pr => pr.id); ConnectionId = msg.ConnectionId; this.serverEncryption = new RSACrypto(); this.serverEncryption.ImportKey (msg.PublicEncryptionKey); this.serverEncryptionKey = msg.PublicEncryptionKey; var encryption = new AesManaged { KeySize = 256 }; encryption.GenerateKey(); BufferValueWriter authKeyWriter = new BufferValueWriter (new byte[1600]); this.publicAuthenticationKey.Serialize (authKeyWriter, this.serverEncryption); this.serializer.AES = encryption; this.serializer.HMAC = new HMACSHA256 (encryption.Key); SendAsync (new FinalConnectMessage { AESKey = this.serverEncryption.Encrypt (encryption.Key), PublicAuthenticationKeyType = this.publicAuthenticationKey.GetType(), PublicAuthenticationKey = authKeyWriter.ToArray() }); break; case (ushort)TempestMessageType.Connected: var connected = (ConnectedMessage) e.Message; ConnectionId = connected.ConnectionId; OnConnected (new ClientConnectionEventArgs (this)); var tcs = Interlocked.Exchange (ref this.connectCompletion, null); if (tcs != null) tcs.TrySetResult (new ClientConnectionResult (ConnectionResult.Success, this.serverAuthenticationKey)); break; default: base.OnTempestMessageReceived(e); break; } }
protected override void OnTempestMessage (MessageEventArgs e) { switch (e.Message.MessageType) { case (ushort)TempestMessageType.AcknowledgeConnect: { var msg = (AcknowledgeConnectMessage)e.Message; this.serializer.Protocols = this.serializer.Protocols.Intersect (msg.EnabledProtocols); ConnectionId = msg.ConnectionId; this.remoteEncryption = new RSACrypto(); this.remoteEncryption.ImportKey (msg.PublicEncryptionKey); var encryption = new AesManaged { KeySize = 256 }; encryption.GenerateKey(); BufferValueWriter authKeyWriter = new BufferValueWriter (new byte[1600]); LocalKey.Serialize (authKeyWriter, this.remoteEncryption); SendAsync (new FinalConnectMessage { AESKey = this.remoteEncryption.Encrypt (encryption.Key), PublicAuthenticationKeyType = LocalKey.GetType(), PublicAuthenticationKey = authKeyWriter.ToArray() }); this.serializer.AES = encryption; this.serializer.HMAC = new HMACSHA256 (encryption.Key); break; } case (ushort)TempestMessageType.Connected: { var msg = (ConnectedMessage)e.Message; ConnectionId = msg.ConnectionId; this.formallyConnected = true; Timer t = Interlocked.Exchange (ref this.connectTimer, null); if (t != null) t.Dispose(); var tcs = Interlocked.Exchange (ref this.connectTcs, null); if (tcs != null) { if (tcs.TrySetResult (new ClientConnectionResult (ConnectionResult.Success, RemoteKey))) OnConnected(); } break; } default: base.OnTempestMessage (e); break; } }
public AesCipher() { _aes = new AesManaged {KeySize = KeySize}; _aes.GenerateIV(); _aes.GenerateKey(); }
/// <summary> /// Creates or updates cipher keys. /// </summary> internal void UpdateKeyIVs() { using (AesManaged symmetricAlgorithm = new AesManaged()) { symmetricAlgorithm.KeySize = 256; symmetricAlgorithm.GenerateKey(); symmetricAlgorithm.GenerateIV(); if ((object)m_keyIVs == null) { // Initialize new key set m_keyIVs = new byte[2][][]; m_keyIVs[EvenKey] = new byte[2][]; m_keyIVs[OddKey] = new byte[2][]; m_keyIVs[EvenKey][KeyIndex] = symmetricAlgorithm.Key; m_keyIVs[EvenKey][IVIndex] = symmetricAlgorithm.IV; symmetricAlgorithm.GenerateKey(); symmetricAlgorithm.GenerateIV(); m_keyIVs[OddKey][KeyIndex] = symmetricAlgorithm.Key; m_keyIVs[OddKey][IVIndex] = symmetricAlgorithm.IV; m_cipherIndex = EvenKey; } else { // Generate a new key set for current cipher index m_keyIVs[m_cipherIndex][KeyIndex] = symmetricAlgorithm.Key; m_keyIVs[m_cipherIndex][IVIndex] = symmetricAlgorithm.IV; // Set run-time to the other key set m_cipherIndex ^= 1; } } m_lastCipherKeyUpdateTime = DateTime.UtcNow.Ticks; }
public static SecretKey GenerateAESPrivateKey() { AesManaged aes = new AesManaged(); aes.KeySize = 128; aes.GenerateKey(); return new SecretKeySpec(aes.Key, "AES"); }
//internal static bool TryEncryptStream(Stream inputStream, Stream outputStream, out SymetricKey symenticKey) //{ // using (AesManaged aes = new AesManaged()) // { // symenticKey = new SymetricKey(); // try // { // aes.GenerateIV(); // aes.GenerateKey(); // symenticKey.Iv = aes.IV; // symenticKey.Key = aes.Key; // string tempFile = Path.GetTempFileName(); // FileStream tempWriteFileStream = new FileStream(tempFile, FileMode.Create); // CryptoStream cryptoStream = new CryptoStream(tempWriteFileStream, aes.CreateEncryptor(), // CryptoStreamMode.Write); // inputStream.CopyTo(cryptoStream); // cryptoStream.FlushFinalBlock(); // cryptoStream.Close(); // tempWriteFileStream.Close(); // using (var tempReadFileStream = new FileStream(tempFile, FileMode.Open)) // { // tempReadFileStream.CopyTo(outputStream); // outputStream.Position = 0; // } // return true; // } // catch (Exception) // { // return false; // } // } //} internal static bool TryEncryptStream(Stream inputStream, Stream outputStream, out SymetricKey symenticKey) { using (AesManaged aes = new AesManaged()) { symenticKey = new SymetricKey(); try { aes.GenerateIV(); aes.GenerateKey(); symenticKey.Iv = aes.IV; symenticKey.Key = aes.Key; CryptoStream cryptoStream = new CryptoStream(outputStream, aes.CreateEncryptor(), CryptoStreamMode.Write); inputStream.CopyTo(cryptoStream); cryptoStream.FlushFinalBlock(); outputStream.Position = 0; return true; } catch (Exception) { return false; } } }