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); } }
public void IncorrectKeyForDecryption() { var keyGenerator = new AesManaged(); keyGenerator.GenerateKey(); var key1 = Convert.ToBase64String(keyGenerator.Key); keyGenerator.GenerateKey(); var key2 = Convert.ToBase64String(keyGenerator.Key); Assert.AreNotEqual(key1, key2); var plain = _randomWords.Sentence(RandomGen.Next(20, 99)); var crypto1 = new AesCryptString(key1); var cipher = crypto1.Encrypt(plain); var plain2 = crypto1.Decrypt(cipher); // this should work. Assert.AreEqual(plain, plain2); try { crypto1.Decrypt(key2, cipher); // this should fail Assert.Fail("Expected this decrypt to fail because the key was not provided."); } catch (CryptographicException error) { Assert.IsTrue(Regex.IsMatch(error.Message, "can not decrypt this text", RegexOptions.IgnoreCase), error.Message); } }
public cryTool(Cry_KeySize keySize) { int k = 0; switch (keySize) { case Cry_KeySize.Key_128: k = 128; break; case Cry_KeySize.Key_192: k = 192; break; case Cry_KeySize.Key_256: k = 256; break; } if (k != 0) { managed.KeySize = k; } else { managed.KeySize = 128; } //生成密钥和随机向量 managed.GenerateKey(); managed.GenerateIV(); //byte[] IVBlock = managed.IV; //byte[] KeyBlock = managed.Key; }
/// <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); }
private static void ParallelPartitionGenerateAESKeys() { var sw = Stopwatch.StartNew(); Parallel.ForEach(Partitioner.Create(1, NUM_AES_KEYS + 1), range => { var aesM = new AesManaged(); Debug.WriteLine("AES Range ({0}, {1}. Time: {2})", range.Item1, range.Item2, DateTime.Now.TimeOfDay); for (int i = range.Item1; i < range.Item2; i++) { aesM.GenerateKey(); byte[] result = aesM.Key; string hexString = ConvertToHexString(result); lock (_keysList) { // Critical code section // It is safe to add elements to the List _keysList.Add(hexString); } // Console.WriteLine("AES KEY: {0} ", hexString); } }); Debug.WriteLine("AES: " + sw.Elapsed.ToString()); }
public void EncryDecrpt() { var t = "Hello Word!"; var keyGen = new AesManaged(); var rand = new SecureRandom(); var ivLen = 256; //var iv = 16; var tag = 256; //keyGen.KeySize = tag; keyGen.GenerateIV(); keyGen.GenerateKey(); var iv = keyGen.IV; var key = keyGen.Key; var bytes = Encoding.UTF8.GetBytes(t); var encBytes = CryptoHelper.Encrypt(key, bytes, iv, tag); var deBytes = CryptoHelper.Decrypt(key, encBytes, iv, tag); for (var i = 0; i < bytes.Length; i++) { _output.WriteLine($"{bytes[i]} : {deBytes[i]}"); Assert.Equal(bytes[i], deBytes[i]); } _output.WriteLine(Convert.ToBase64String(deBytes)); }
private static void ParallelPartitionGenerateAESKeys() { var sw = Stopwatch.StartNew(); Parallel.ForEach( Partitioner.Create( 1, NUM_AES_KEYS, ((int)(NUM_AES_KEYS / Environment.ProcessorCount) + 1)), range => { var aesM = new AesManaged(); Debug.WriteLine( "AES Range ({0}, {1}. TimeOfDay before inner loop starts: {2})", range.Item1, range.Item2, DateTime.Now.TimeOfDay); for (int i = range.Item1; i < range.Item2; i++) { aesM.GenerateKey(); byte[] result = aesM.Key; string hexString = ConvertToHexString(result); // Console.WriteLine(“AES KEY: {0} “, hexString); } }); Debug.WriteLine("AES: " + sw.Elapsed.ToString()); }
public MessageCrypto(string logCtx, bool keyGenNeeded, ILoggingAdapter log) { _iv = new byte[16]; _hash = SHA256.Create(); _keyGenerator = new AesManaged(); _secureRandom = new SecureRandom(); _logCtx = logCtx; _log = log; _encryptedDataKeyMap = new ConcurrentDictionary <string, EncryptionKeyInfo>(); _dataKeyCache = new Cache <string, byte[]>(TimeSpan.FromHours(4)); //four hours try { // If keygen is not needed(e.g: consumer), data key will be decrypted from the message if (!keyGenNeeded) { _hash = SHA256.Create(); //new MD5CryptoServiceProvider(); _dataKey = null; return; } _secureRandom.NextBytes(_iv); _keyGenerator.IV = _iv; } catch (Exception e) { _log.Error($"{_logCtx} MessageCrypto initialization Failed {e.Message}"); } // Generate data key to encrypt messages _keyGenerator.GenerateKey(); _dataKey = _keyGenerator.Key; }
public static void GenAesKeyPair(ref byte[] key, ref byte[] iv) { using (Aes aes = new AesManaged()) { aes.KeySize = ConfigurationManager.CHIPER_KEY_SIZE; aes.Mode = ConfigurationManager.CHIPER_MODE; aes.Padding = ConfigurationManager.CHIPER_PADDING_MODE; aes.GenerateIV(); aes.GenerateKey(); byte[] volatileKey = aes.Key; byte[] volatileIv = aes.IV; key = new byte[volatileKey.Length]; iv = new byte[volatileIv.Length]; Array.Copy(volatileKey, key, volatileKey.Length); Array.Copy(volatileIv, iv, volatileIv.Length); Common.ClearArray(ref volatileKey); Common.ClearArray(ref volatileIv); aes.Clear(); } }
private static void ParallelPartitionGenerateAESKeys(int maxDegree) { var parallelOptions = new ParallelOptions(); parallelOptions.MaxDegreeOfParallelism = maxDegree; var sw = Stopwatch.StartNew(); Parallel.ForEach( Partitioner.Create(1, NUM_AES_KEYS + 1), parallelOptions, range => { var aesM = new AesManaged(); Debug.WriteLine("AES Range ({0}, {1}. Time: {2})", range.Item1, range.Item2, DateTime.Now.TimeOfDay); for (int i = range.Item1; i < range.Item2; i++) { aesM.GenerateKey(); byte[] result = aesM.Key; _byteArraysStack.Push(result); } }); Debug.WriteLine("AES: " + sw.Elapsed.ToString()); }
public static byte[] GenerateAesKey() { using var aes = new AesManaged(); aes.GenerateKey(); return(aes.Key); }
/// <summary> /// 对Byte[]进行加密, /// </summary> /// <param name="file">明文Byte[]流</param> /// <returns>EncryptedByte[] key iv</returns> public static Tuple <byte[], byte[], byte[]> RandomAesEncrypt(byte[] file) { byte[] encrypted; byte[] Key, IV; using (AesManaged aes = new AesManaged()) { aes.BlockSize = aes.LegalBlockSizes[0].MaxSize; aes.KeySize = aes.LegalKeySizes[0].MaxSize; aes.GenerateKey(); aes.GenerateIV(); ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { csEncrypt.Write(file, 0, file.Length); csEncrypt.FlushFinalBlock(); } encrypted = msEncrypt.ToArray();; } Key = aes.Key; IV = aes.IV; } return(new Tuple <byte[], byte[], byte[]>(encrypted, Key, IV)); }
private void ProcessKeyExchange(KeyExchangeRequest Request) { RSA RSAEncryption = RSA.Create(); RSAEncryption.KeySize = Request.RSAKeySize; RSAParameters PublicParameters = new RSAParameters() { Exponent = Request.RSAExponent, Modulus = Request.RSAModulus }; RSAEncryption.ImportParameters(PublicParameters); Cryptor = new AesManaged(); Cryptor.KeySize = Request.AESKeySize; Cryptor.GenerateIV(); Cryptor.GenerateKey(); Cryptor.Mode = CipherMode.CBC; Cryptor.Padding = PaddingMode.PKCS7; KeyExchangeResponse Response = new KeyExchangeResponse() { Accepted = true, EncryptedAESIV = RSAEncryption.Encrypt(Cryptor.IV, RSAEncryptionPadding.Pkcs1), EncryptedAESKey = RSAEncryption.Encrypt(Cryptor.Key, RSAEncryptionPadding.Pkcs1), ID = Request.ID }; Send(Response); }
public static string EncryptAsymmetric(byte[] exponent, byte[] modulus, string data) { var bytes = Encoding.UTF8.GetBytes(data); var results = new List <byte>(); #if NETFX_CORE throw new NotImplementedException("WinRT..."); #else 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())); #endif }
public AESStream(byte[] Key, byte[] VIKey, CipherMode CMode, PaddingMode PMode, bool AutoGenKey = false) { if (!Info.Moduls.Contains("Crypto/AES.cs")) { Info.Moduls.Add("Crypto/AES.cs"); } AesMa = new AesManaged(); if (Key != null && !AutoGenKey) { _Key = Key; AesMa.Key = _Key; } else { AesMa.GenerateKey(); _Key = AesMa.Key; } if (VIKey != null && !AutoGenKey) { _IVKey = VIKey; AesMa.IV = _IVKey; } else { AesMa.GenerateIV(); _IVKey = AesMa.IV; } AesMa.Mode = CMode; AesMa.Padding = PMode; }
/// <summary> /// Generates and retrieves a 128 bit AES hash. /// </summary> /// <returns>The hash.</returns> public static byte[] GetHashBytes() { if (_hashMutex == null) { _hashMutex = new Mutex(); } _hashMutex.WaitOne(); if (_cryptoTransform == null) { Aes aes = new AesManaged() { Mode = CipherMode.ECB }; aes.GenerateIV(); aes.GenerateKey(); _cryptoTransform = aes.CreateEncryptor(); if (_lastHash == null) { _lastHash = new byte[16]; } } _cryptoTransform.TransformBlock(_lastHash, 0, 16, _lastHash, 0); _hashMutex.ReleaseMutex(); return(_lastHash); }
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> /// TLS 本地线程同步锁 /// </summary> private static void ParallelPartionGenerateAESKeys() { //LocalDataStoreSlot线程本地存储 封装内存槽以存储本地数据 var sw = Stopwatch.StartNew(); Parallel.ForEach(Partitioner.Create(1, NUM_AES_KEYS + 1), range => { var aesm = new AesManaged(); Debug.WriteLine("AES Range({0},{1}.Time:{2})", range.Item1, range.Item2, DateTime.Now.TimeOfDay); for (int i = range.Item1; i < range.Item2; i++) { aesm.GenerateKey(); byte[] result = aesm.Key; string hexString = ConvertToHexString(result); //确保每次只有一个线程运行_keyList对象里的方法 //Lock 关键词创造了一个临界代码区,但是增加了一定的开销,会降低可扩展性 //临界代码区可以对_keyList进行排他访问 其他任务将会试图获得该锁,锁在释放之前 //会它们将会阻塞并等待进入这个临界区 lock (_keysList) { _keysList.Add(hexString); } } }); Debug.WriteLine("AES: " + sw.Elapsed.ToString()); }
//Generates AES key. public byte[] GenerateAesKey() { AesManaged aes = new AesManaged(); aes.GenerateKey(); return(aes.Key); }
public CryptoInformation() : this(true) { if (keyArray == null) { aes = new AesManaged(); aes.GenerateKey(); keyArray = aes.Key; } DebugOutputArray(keyArray, "Key Array: "); if (IVArray == null) { if (aes == null) { aes = new AesManaged(); } aes.GenerateIV(); IVArray = aes.IV; } DebugOutputArray(IVArray, "IV Array"); SaveCryptInfo(); }
public string Encrypt(string input, out string key, out string iv) { Aes aes = new AesManaged { KeySize = KeySize, BlockSize = BlockSize }; aes.GenerateKey(); aes.GenerateIV(); key = Convert.ToBase64String(aes.Key); iv = Convert.ToBase64String(aes.IV); using MemoryStream outputStream = new(); using ICryptoTransform transform = aes.CreateEncryptor(); using CryptoStream cryptoStream = new(outputStream, transform, CryptoStreamMode.Write); cryptoStream.WriteUtf8String(input); byte[] bytes = outputStream.ToArray(); string cipherText = Convert.ToBase64String(bytes, 0, bytes.Length); return(cipherText); }
private static void ParallelPartitionGenerateAESKeysWCP(System.Threading.CancellationToken ct, char prefix) { var sw = Stopwatch.StartNew(); var parallelOptions = new ParallelOptions(); // Set the CancellationToken for the ParallelOptions instance parallelOptions.CancellationToken = ct; Parallel.ForEach(Partitioner.Create(1, NUM_AES_KEYS + 1), parallelOptions, range => { var aesM = new AesManaged(); Debug.WriteLine("AES Range ({0}, {1}. TimeOfDay before inner loop starts: {2})", range.Item1, range.Item2, DateTime.Now.TimeOfDay); for (int i = range.Item1; i < range.Item2; i++) { aesM.GenerateKey(); byte[] result = aesM.Key; string hexString = ConvertToHexString(result); // Console.WriteLine("AES KEY: {0} ", hexString); if (hexString[0] == prefix) { Keys.Enqueue(hexString); } parallelOptions.CancellationToken.ThrowIfCancellationRequested(); } }); Debug.WriteLine("AES: " + sw.Elapsed.ToString()); }
/// <summary> /// Serializes data. /// </summary> /// <typeparam name="_T">data type to be serialized</typeparam> /// <param name="dataToSerialize">data to be serialized</param> /// <returns>serialized data</returns> public object Serialize <_T>(_T dataToSerialize) { using (EneterTrace.Entering()) { byte[][] aData = new byte[3][]; // Generate random key for AES. AesManaged anAes = new AesManaged(); anAes.KeySize = myAesBitSize; anAes.GenerateIV(); anAes.GenerateKey(); // Serialize data with AES using the random key. AesSerializer anAesSerializer = new AesSerializer(anAes.Key, anAes.IV, myUnderlyingSerializer); aData[2] = (byte[])anAesSerializer.Serialize <_T>(dataToSerialize); // Encrypt the random key with RSA using the public key. // Note: Only guy having the private key can decrypt it. RSACryptoServiceProvider aCryptoServiceProvider = new RSACryptoServiceProvider(); aCryptoServiceProvider.ImportParameters(myPublicKey); aData[0] = aCryptoServiceProvider.Encrypt(anAes.Key, false); aData[1] = aCryptoServiceProvider.Encrypt(anAes.IV, false); // Serialize encrypted data, key and iv with the underlying serializer. object aSerializedData = myUnderlyingSerializer.Serialize <byte[][]>(aData); return(aSerializedData); } }
/// <summary> /// Генерирует Key, IV необходимые для шифрования AES /// </summary> /// <returns>true, успешно сгенерированы /// false, генерация не удалась (возможно, ключи уже есть)</returns> private void GenerateKeyIV() { if (!File.Exists(PATH_TO_KEY) && !File.Exists(PATH_TO_IV)) { AesManaged aes = new AesManaged(); aes.GenerateKey(); aes.GenerateIV(); using (var bwKey = new BinaryWriter(new FileStream(PATH_TO_KEY, FileMode.Create))) { bwKey.Write(aes.Key); } using (var bwIV = new BinaryWriter(new FileStream(PATH_TO_IV, FileMode.Create))) { bwIV.Write(aes.IV); } } else { using (var brKey = new BinaryReader(new FileStream(PATH_TO_KEY, FileMode.Open))) { KEY = brKey.ReadBytes(LengthFIleInBytes(PATH_TO_KEY)); } using (var brIV = new BinaryReader(new FileStream(PATH_TO_IV, FileMode.Open))) { IV = brIV.ReadBytes(LengthFIleInBytes(PATH_TO_IV)); } } }
public void Initialize(ProtectedLoggerConfiguration configuration) { if (configuration == null) { return; } this.configuration = configuration; try { // Create log directory if (!Directory.Exists(configuration.LogDirectory)) { Directory.CreateDirectory(configuration.LogDirectory); } // Generate AES key and IV using (var aesCryptoProvider = new AesManaged()) { aesCryptoProvider.GenerateKey(); aesCryptoProvider.GenerateIV(); aesKey = aesCryptoProvider.Key; aesIV = aesCryptoProvider.IV; } isInitialized = true; } catch { LogProvider.Log.Error("Logger service has not been initialized."); } }
private static List <String> GenerateAESKeysWithCharPrefix( System.Threading.CancellationToken ct, char prefix) { var sw = Stopwatch.StartNew(); var aesM = new AesManaged(); var keysList = new List <String>(); for (int i = 1; i <= NUM_AES_KEYS; i++) { aesM.GenerateKey(); byte[] result = aesM.Key; string hexString = ConvertToHexString(result); if (hexString[0] == prefix) { keysList.Add(hexString); } // Console.WriteLine("AES KEY: {0} ", hexString); if (ct.IsCancellationRequested) { ct.ThrowIfCancellationRequested(); } } Debug.WriteLine("AES: " + sw.Elapsed.ToString()); return(keysList); }
private static void GenerateKey() { string filePath = @"C:\Users\silas\Desktop\appUSB\appUSB-Debugger\networkDetails.txt"; List <string> linesFromNetDetails = File.ReadAllLines(filePath).ToList(); AesManaged aes = new AesManaged(); aes.KeySize = 128; aes.GenerateKey(); aes.Key.CopyTo(key, 0); //copy aes.key to byte[] key starting at 0 index string keyStr = BitConverter.ToString(aes.Key).Replace('-', ':'); string keyFile = $"Aes128Key[{keyStr}]"; linesFromNetDetails.Insert(0, keyFile); File.WriteAllLines(filePath, linesFromNetDetails); //DEBUGGING System.Diagnostics.Debug.Write("AES128_Key Combo: "); //write '\n' foreach (byte b in key) { System.Diagnostics.Debug.Write(b); //write key to debugger } System.Diagnostics.Debug.WriteLine(""); //write '\n' }
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); } }
private string EncryptText(string PlainText, ref string Key, ref string Iv) { AesManaged aesManaged = new AesManaged(); try { byte[] bytestoEncrypt = Encoding.ASCII.GetBytes(PlainText); aesManaged.KeySize = KeyBitSize; aesManaged.Mode = CipherMode.ECB; aesManaged.Padding = PaddingMode.PKCS7; aesManaged.GenerateIV(); aesManaged.GenerateKey(); Iv = Convert.ToBase64String(aesManaged.IV); Key = Convert.ToBase64String(aesManaged.Key); ICryptoTransform cryptoTransform = aesManaged.CreateEncryptor(aesManaged.Key, aesManaged.IV); byte[] resultArray = cryptoTransform.TransformFinalBlock(bytestoEncrypt, 0, bytestoEncrypt.Length); return(Convert.ToBase64String(resultArray)); } catch (Exception ex) { throw ex; } }
public static string GenerateKey() { var aes = new AesManaged(); aes.GenerateKey(); return(Convert.ToBase64String(aes.Key)); }
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); }