當前位置: 首頁>>代碼示例>>C#>>正文


C# Cryptography.AesManaged類代碼示例

本文整理匯總了C#中System.Security.Cryptography.AesManaged的典型用法代碼示例。如果您正苦於以下問題:C# AesManaged類的具體用法?C# AesManaged怎麽用?C# AesManaged使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


AesManaged類屬於System.Security.Cryptography命名空間,在下文中一共展示了AesManaged類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: Server

 /// <summary>
 /// konstruktor obiektu Server 
 /// </summary>
 public Server()
 {
     requestReceived += Server_requestReceived;
     aesKeyGenerator = new AesManaged();
     hashAlgorithm = new SHA256Managed();
     rsaKeyGenerator = new RSACryptoServiceProvider();      
 }
開發者ID:Kubabanka,項目名稱:PKRY_15Z_Komunikator,代碼行數:10,代碼來源:Server.cs

示例2: DecryptBase64

        public static bool DecryptBase64(string cliperText, string key, out string originText)
        {
            byte[] inputData = Convert.FromBase64String(cliperText);

            var aes = new AesManaged()
            {
                Padding = _padding,
                Mode = _cipherMode,
                IV = ORIGIN_IV,
                Key = Encoding.UTF8.GetBytes(key.PadRight(KEY_LENGTH, PADDING_CHAR).Substring(0, KEY_LENGTH))
            };

            var decryptor = aes.CreateDecryptor();
            bool decryptSuccess = true;
            try
            {
                byte[] decryptedData = decryptor.TransformFinalBlock(inputData, 0, inputData.Length);
                originText = Encoding.UTF8.GetString(decryptedData);
            }
            catch
            {
                decryptSuccess = false;
                originText = string.Empty;
            }
            finally
            {
                decryptor.Dispose();
                if (aes != null)
                {
                    aes.Clear();
                }
            }
            return decryptSuccess;
        }
開發者ID:JerryXia,項目名稱:ML,代碼行數:34,代碼來源:AesCryptoService.cs

示例3: Main

	public static int Main()
    {
       List<byte[]>[] inputs = new List<byte[]>[]
        {
            GenerateInput(new int[] { 3, 1 }),
            GenerateInput(new int[] { 2, 2 }),
            GenerateInput(new int[] { 2, 1, 1 }),
            GenerateInput(new int[] { 1, 3}),
            GenerateInput(new int[] { 1, 2, 1}),
            GenerateInput(new int[] { 1, 1, 2 }),
            GenerateInput(new int[] { 1, 1, 1, 1 })
        };

	   foreach (PaddingMode paddingMode in PaddingModes)
		{
			List<byte[]> results = new List<byte[]>();

			// AESCSP is not supported on Win2k so just round-trip with AesManaged in this case
			//
			Aes aes1 = (AesCSPSupported()) ? (Aes) new AesCryptoServiceProvider() : (Aes) new AesManaged();
			aes1.Padding = paddingMode;

			Aes aes2 = new AesManaged();
			aes2.Padding = paddingMode;

			aes1.Key = aes2.Key;
			aes1.IV = aes2.IV;
			aes1.Mode = aes2.Mode;

			for (int i = 0; i < inputs.Length; i++)
			{
				byte[] result = null;
				if (!TestRoundTrip(aes1, aes2, inputs[i], out result))
				{
					Console.WriteLine("Test Fail - roundtrip fails");
					return FailCode;
				}

				results.Add(result);
			}

			for(int i = 0; i < results.Count - 1; i++)
			{
				if (!CompareBytes(results[i], results[i + 1]))
				{
					Console.WriteLine("Test Fail - mismatch");
					Console.WriteLine("Result {0}: {1}", i, ByteArrayToString(results[i]));
					Console.WriteLine("Result {0}: {1}", i+1, ByteArrayToString(results[i+1]));
					Console.WriteLine("Key: {0}", ByteArrayToString(aes1.Key));
					Console.WriteLine("IV: {0}", ByteArrayToString(aes1.IV));
					Console.WriteLine("Cipher mode: {0}", aes1.Mode.ToString());
					Console.WriteLine("Padding mode: {0}", aes1.Padding.ToString());
				   return FailCode;
				}
			}
		}

        Console.WriteLine("Test Passed");
		return PassCode;
    }
開發者ID:koson,項目名稱:.NETMF_for_LPC17xx,代碼行數:60,代碼來源:AESBlocks.cs

示例4: Encrypt

        public static string Encrypt(string plainText, string key)
        {
            if(string.IsNullOrEmpty(plainText)) {
                throw new ArgumentNullException("plainText");
            }

            if(string.IsNullOrEmpty(key)) {
                throw new ArgumentNullException("key");
            }

            using(var keyDerivationFunction = new Rfc2898DeriveBytes(key, SALT_SIZE)) {
                byte[] saltBytes = keyDerivationFunction.Salt;
                byte[] keyBytes = keyDerivationFunction.GetBytes(32);
                byte[] ivBytes = keyDerivationFunction.GetBytes(16);

                using(var aesManaged = new AesManaged()) {
                    aesManaged.KeySize = 256;

                    using(var encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes)) {
                        MemoryStream memoryStream = null;
                        CryptoStream cryptoStream = null;

                        return WriteMemoryStream(plainText, ref saltBytes, encryptor, ref memoryStream, ref cryptoStream);
                    }
                }
            }
        }
開發者ID:2nfro,項目名稱:dotNet,代碼行數:27,代碼來源:AES.cs

示例5: Load

 public static MyWallet Load(string path, string password)
 {
     MyWallet wallet = new MyWallet();
     byte[] aes_key = Encoding.UTF8.GetBytes(password).Sha256().Sha256();
     byte[] aes_iv = new byte[16];
     using (AesManaged aes = new AesManaged())
     using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
     {
         fs.Read(aes_iv, 0, aes_iv.Length);
         using (ICryptoTransform decryptor = aes.CreateDecryptor(aes_key, aes_iv))
         using (CryptoStream cs = new CryptoStream(fs, decryptor, CryptoStreamMode.Read))
         using (BinaryReader reader = new BinaryReader(cs))
         {
             int count = (int)reader.ReadVarInt();
             for (int i = 0; i < count; i++)
             {
                 byte[] privateKey = reader.ReadBytes(32);
                 bool compressed = reader.ReadBoolean();
                 ECPoint publicKey = ECCurve.Secp256k1.G * privateKey;
                 UInt160 publicKeyHash = publicKey.EncodePoint(compressed).ToScriptHash();
                 wallet.accounts.Add(new WalletEntry(privateKey, publicKey, publicKeyHash, compressed));
             }
         }
     }
     Array.Clear(aes_key, 0, aes_key.Length);
     return wallet;
 }
開發者ID:erikzhang,項目名稱:IceWallet,代碼行數:27,代碼來源:MyWallet.cs

示例6: Encrypt

        public static string Encrypt(string plainText, string key)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentNullException("plainText");
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            using (var keyDerivationFunction = new Rfc2898DeriveBytes(key, _saltSize))
            {
                var saltBytes = keyDerivationFunction.Salt;
                var keyBytes = keyDerivationFunction.GetBytes(32);
                var ivBytes = keyDerivationFunction.GetBytes(16);

                using (var aesManaged = new AesManaged())
                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(plainText);

                    var cipherTextBytes = memoryStream.ToArray();
                    Array.Resize(ref saltBytes, saltBytes.Length + cipherTextBytes.Length);
                    Array.Copy(cipherTextBytes, 0, saltBytes, _saltSize, cipherTextBytes.Length);

                    return Convert.ToBase64String(saltBytes);
                }
            }
        }
開發者ID:vfrz,項目名稱:ISNProjects,代碼行數:29,代碼來源:AES.cs

示例7: decrypt

        public static string decrypt(string valueToDecrypt)
        {
            using (Aes aes = new AesManaged())
            {
                aes.Padding = PaddingMode.PKCS7;
                aes.KeySize = 128;          // in bits
                aes.Key = new byte[128 / 8];  // 16 bytes for 128 bit encryption
                aes.IV = new byte[128 / 8];   // AES needs a 16-byte IV

                // Should set Key and IV here.  Good approach: derive them from 
                // a password via Cryptography.Rfc2898DeriveBytes 
                byte[] cipherText = Convert.FromBase64String(valueToDecrypt);
                byte[] plainText = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherText, 0, cipherText.Length);
                    }

                    plainText = ms.ToArray();
                }

                return UTF8Encoding.UTF8.GetString(plainText);
            }
        }
開發者ID:stvnhg,項目名稱:be.codeblade.utilities,代碼行數:26,代碼來源:CBEncryptionService.cs

示例8: Encrypt

        /// <summary>
        /// Encrypts the plainText input using the given Key.
        /// A 128 bit random salt will be generated and prepended to the ciphertext before it is returned.
        /// </summary>
        /// <param name="plainText">The plain text to encrypt.</param>
        /// <param name="password">The plain text encryption key.</param>
        /// <returns>The salt and the ciphertext</returns>
        public static byte[] Encrypt(byte[] plainText, string password)
        {
            if (plainText == null || plainText.Length == 0) throw new ArgumentNullException("plainText");
            if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password");

            // Derive a new Salt, Key, and IV from the password
            using (var keyDerivationFunction = new Rfc2898DeriveBytes(password, SaltSize))
            {
                var saltBytes = keyDerivationFunction.Salt;
                var keyBytes = keyDerivationFunction.GetBytes(32);
                var ivBytes = keyDerivationFunction.GetBytes(16);

                using (var aesManaged = new AesManaged())
                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 BinaryWriter(cryptoStream))
                    {
                        streamWriter.Write(plainText);
                    }

                    var cipherTextBytes = memoryStream.ToArray();
                    Array.Resize(ref saltBytes, saltBytes.Length + cipherTextBytes.Length);
                    Array.Copy(cipherTextBytes, 0, saltBytes, SaltSize, cipherTextBytes.Length);

                    return saltBytes;
                }
            }
        }
開發者ID:richard-green,項目名稱:LCGoogleApps,代碼行數:37,代碼來源:SymmetricEncryption.cs

示例9: Decrypt

        /// <summary>
        /// Decrypts the ciphertext using the Key.
        /// </summary>
        /// <param name="ciphertext">The ciphertext to decrypt.</param>
        /// <param name="password">The plain text encryption key.</param>
        /// <returns>The decrypted text.</returns>
        public static byte[] Decrypt(byte[] cipherText, string password)
        {
            if (cipherText == null || cipherText.Length == 0) throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password");

            // Extract the salt from our ciphertext
            var saltBytes = cipherText.Take(SaltSize).ToArray();
            var ciphertextBytes = cipherText.Skip(SaltSize).ToArray();

            using (var keyDerivationFunction = new Rfc2898DeriveBytes(password, saltBytes))
            {
                // Derive the previous Key and IV from the password and salt
                var keyBytes = keyDerivationFunction.GetBytes(32);
                var ivBytes = keyDerivationFunction.GetBytes(16);

                using (var aesManaged = new AesManaged())
                using (var decryptor = aesManaged.CreateDecryptor(keyBytes, ivBytes))
                using (var memoryStream = new MemoryStream(ciphertextBytes))
                using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                using (var outputStream = new StreamReader(cryptoStream))
                using (var outMemoryStream = new MemoryStream())
                {
                    outputStream.BaseStream.CopyTo(outMemoryStream);
                    return outMemoryStream.ToArray();
                }
            }
        }
開發者ID:richard-green,項目名稱:LCGoogleApps,代碼行數:33,代碼來源:SymmetricEncryption.cs

示例10: Can_Send_Encrypted_Message

        public void Can_Send_Encrypted_Message()
        {
            var client = CreateClient();

            var request = new HelloSecure { Name = "World" };

            var aes = new AesManaged { KeySize = AesUtils.KeySize };

            var aesKeyBytes = aes.Key.Combine(aes.IV);
            var rsaEncAesKeyBytes = RsaUtils.Encrypt(aesKeyBytes, SecureConfig.PublicKeyXml);

            var timestamp = DateTime.UtcNow.ToUnixTime();

            var requestBody = timestamp + " POST " + typeof(HelloSecure).Name + " " + request.ToJson();

            var encryptedMessage = new EncryptedMessage
            {
                EncryptedSymmetricKey = Convert.ToBase64String(rsaEncAesKeyBytes),
                EncryptedBody = AesUtils.Encrypt(requestBody, aes.Key, aes.IV)
            };
            var encResponse = client.Post(encryptedMessage);

            var responseJson = AesUtils.Decrypt(encResponse.EncryptedBody, aes.Key, aes.IV);
            var response = responseJson.FromJson<HelloSecureResponse>();

            Assert.That(response.Result, Is.EqualTo("Hello, World!"));
        }
開發者ID:dittodhole,項目名稱:dotnet-ServiceStack,代碼行數:27,代碼來源:EncryptedMessagesTests.cs

示例11: Decrypt

        public static Stream Decrypt(Stream source,
            Headers headers, byte[] masterKey)
        {
            byte[] easKey;
            using (var buffer = new MemoryStream())
            {
                var masterSeed = headers.MasterSeed;
                buffer.Write(masterSeed, 0, masterSeed.Length);
                buffer.Write(masterKey, 0, masterKey.Length);

                easKey = BufferEx.GetHash(buffer.ToArray());
            }

            var eas = new AesManaged
            {
                KeySize = 256,
                Key = BufferEx.Clone(easKey),
                IV = BufferEx.Clone(headers.EncryptionIV)
            };

            Stream stream = new CryptoStream(source,
                eas.CreateDecryptor(),
                CryptoStreamMode.Read);

            if (!VerifyStartBytes(headers, stream))
                return null;

            stream = new HashedBlockStream(stream, true);
            return headers.Compression == Compressions.GZip
                ? new GZipInputStream(stream) : stream;
        }
開發者ID:oldlaurel,項目名稱:WinPass,代碼行數:31,代碼來源:FileFormat.cs

示例12: DecryptCipherAES

        /// <summary>
        /// this algorithm uses the AES algorithm to decrypt the given cipherText
        /// </summary>
        /// <param name="cipherText"></param>
        /// <param name="sharedSecret"></param>
        /// <returns></returns>
        public static string DecryptCipherAES(string cipherText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(cipherText))
            {
                return cipherText;
            }

            AesManaged aesAlg = null;
            string plaintext = null;
            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, salt);

            // Create the streams used for decryption.
            byte[] bytes = Convert.FromBase64String(cipherText);
            using (MemoryStream memoryDecrypt = new MemoryStream(bytes))
            {
                aesAlg = new AesManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                // Get the initialization vector from the encrypted stream
                aesAlg.IV = ReadByteArray(memoryDecrypt);
                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                using (CryptoStream cryptoDecrypt =
                    new CryptoStream(memoryDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader streamDecrypt = new StreamReader(cryptoDecrypt))
                    {
                        plaintext = streamDecrypt.ReadToEnd();
                    }
                }
            }
            return plaintext;
        }
開發者ID:FrankSiegemund,項目名稱:azure-powershell,代碼行數:39,代碼來源:CryptoHelper.cs

示例13: DecryptString

        /// <summary>
        /// Decrypt encrypted string
        /// </summary>
        /// <param name="Str">Encrypted string</param>
        /// <param name="Password">Password used for encryption</param>
        /// <param name="Salt">Salt string used for encryption (at least 8 bytes)</param>
        /// <returns>Decrypted string if success; otherwise - empty string</returns>
        public static string DecryptString(string Str, string Password = "tdcm1234", string Salt = "tdcm1234")
        {
            try
            {
                using (Aes aes = new AesManaged())
                {
                    Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Password, Encoding.UTF8.GetBytes(Salt));
                    aes.Key = deriveBytes.GetBytes(128 / 8);
                    aes.IV = aes.Key;

                    using (MemoryStream decryptionStream = new MemoryStream())
                    {
                        using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            byte[] encryptedData = Convert.FromBase64String(Str);
                            decrypt.Write(encryptedData, 0, encryptedData.Length);
                            decrypt.Flush();
                        }
                        byte[] decryptedData = decryptionStream.ToArray();
                        return UTF8Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error : AES ~ DecryptString ; " + ex.Message);
                return "";
            }
        }
開發者ID:KongMono,項目名稱:HTV_WP,代碼行數:36,代碼來源:AES.cs

示例14: EncryptString

 /// <summary>
 /// Encrypt a string using AES
 /// </summary>
 /// <param name="Str">String to encrypt</param>
 /// <param name="Password">Encryption password</param>
 /// <param name="Salt">A salt string (at least 8 bytes)</param>
 /// <returns>Encrypted string in case of success; otherwise - empty string</returns>
 public static string EncryptString(string Str, string Password = "tdcm1234", string Salt = "tdcm1234")
 {
     try
     {
         using (Aes aes = new AesManaged())
         {
             Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Password, Encoding.UTF8.GetBytes(Salt));
             aes.Key = deriveBytes.GetBytes(128 / 8);
             aes.IV = aes.Key;
             using (MemoryStream encryptionStream = new MemoryStream())
             {
                 using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                 {
                     byte[] utfD1 = UTF8Encoding.UTF8.GetBytes(Str);
                     encrypt.Write(utfD1, 0, utfD1.Length);
                     encrypt.FlushFinalBlock();
                 }
                 return Convert.ToBase64String(encryptionStream.ToArray());
             }
         }
     }
     catch (Exception ex)
     {
         Debug.WriteLine("Error : AES ~ EncryptString ; " + ex.Message);
         return "";
     }
 }
開發者ID:KongMono,項目名稱:HTV_WP,代碼行數:34,代碼來源:AES.cs

示例15: Test

    static Boolean Test()
    {
        Boolean bResult;

        Console.WriteLine("Testing AesManaged encrypt/decrypt...");
        AesManaged     aes = new AesManaged();
        EncDec      ed = new EncDec();
        EncDecMul   edm = new EncDecMul();

        bResult = ed.TestAlgorithm(aes);
        bResult = edm.TestAlgorithm(aes) && bResult;

        if (AesCSPSupported())
		{
			Console.WriteLine("Testing AesCryptoServiceProvider encrypt/decrypt...");
			AesCryptoServiceProvider     aescsp = new AesCryptoServiceProvider();
			ed = new EncDec();
			edm = new EncDecMul();

			bResult = ed.TestAlgorithm(aescsp);
			bResult = edm.TestAlgorithm(aescsp) && bResult;
		}

        return bResult;
    }
開發者ID:aura1213,項目名稱:netmf-interpreter,代碼行數:25,代碼來源:EncDec_AES.cs


注:本文中的System.Security.Cryptography.AesManaged類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。