• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Cryptography.AesManaged类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Security.Cryptography.AesManaged的典型用法代码示例。如果您正苦于以下问题:C# AesManaged类的具体用法?C# AesManaged怎么用?C# AesManaged使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



AesManaged类属于System.Security.Cryptography命名空间,在下文中一共展示了AesManaged类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: Decrypt

 internal static byte[] Decrypt(byte[] data)
 {
     byte[] output = null;
     using (var aes = new AesManaged())
     {
         using (var decryptor = aes.CreateDecryptor(Configuration.Default.EncryptionKey, Configuration.Default.EncryptionIV))
         {
             using (var dataStream = new MemoryStream())
             {
                 using (var encryptionStream = new CryptoStream(dataStream, decryptor, CryptoStreamMode.Write))
                 {
                     encryptionStream.Write(data, 0, data.Length);
                     encryptionStream.FlushFinalBlock();
                     dataStream.Position = 0;
                     byte[] transformedBytes = new byte[dataStream.Length];
                     dataStream.Read(transformedBytes, 0, transformedBytes.Length);
                     encryptionStream.Close();
                     dataStream.Close();
                     output = transformedBytes;
                 }
             }
         }
     }
     return output;
 }
开发者ID:ktw,项目名称:MvcTricks.RoundTripModelBinding,代码行数:25,代码来源:AesEncryption.cs


示例17: Encrypt

		///<summary>Encrypts signature text and returns a base 64 string so that it can go directly into the database.</summary>
		public static string Encrypt(string str,byte[] key){
			//No need to check RemotingRole; no call to db.
			if(str==""){
				return "";
			}
			byte[] ecryptBytes=Encoding.UTF8.GetBytes(str);
			MemoryStream ms=new MemoryStream();
			CryptoStream cs=null;
			Aes aes=new AesManaged();
			aes.Key=key;
			aes.IV=new byte[16];
			ICryptoTransform encryptor=aes.CreateEncryptor(aes.Key,aes.IV);
			cs=new CryptoStream(ms,encryptor,CryptoStreamMode.Write);
			cs.Write(ecryptBytes,0,ecryptBytes.Length);
			cs.FlushFinalBlock();
			byte[] encryptedBytes=new byte[ms.Length];
			ms.Position=0;
			ms.Read(encryptedBytes,0,(int)ms.Length);
			cs.Dispose();
			ms.Dispose();
			if(aes!=null) {
				aes.Clear();
			}
			return Convert.ToBase64String(encryptedBytes);			
		}
开发者ID:mnisl,项目名称:OD,代码行数:26,代码来源:CentralConnections.cs


示例18: Decrypt

        /// <summary> 
        /// Decrypt a string 
        /// </summary> 
        /// <param name="input">Input string in base 64 format</param> 
        /// <returns>Decrypted string</returns> 
        public static string Decrypt(string input, string password)
        {
            byte[] encryptedBytes = Convert.FromBase64String(input);
            byte[] saltBytes = Encoding.UTF8.GetBytes(password);
            string decryptedString = string.Empty;
            using (var aes = new AesManaged())
            {
                Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, saltBytes);
                aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                aes.KeySize = aes.LegalKeySizes[0].MaxSize;
                aes.Key = rfc.GetBytes(aes.KeySize / 8);
                aes.IV = rfc.GetBytes(aes.BlockSize / 8);

                using (ICryptoTransform decryptTransform = aes.CreateDecryptor())
                {
                    using (MemoryStream decryptedStream = new MemoryStream())
                    {
                        CryptoStream decryptor =
                            new CryptoStream(decryptedStream, decryptTransform, CryptoStreamMode.Write);
                        decryptor.Write(encryptedBytes, 0, encryptedBytes.Length);
                        decryptor.Flush();
                        decryptor.Close();

                        byte[] decryptBytes = decryptedStream.ToArray();
                        decryptedString =
                            UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);
                    }
                }
            }

            return decryptedString;
        }
开发者ID:kuki89,项目名称:IP_Lab,代码行数:37,代码来源:Function.cs


示例19: Decrypt

        public static string Decrypt(string ciphertext, string key)
        {
            if (string.IsNullOrEmpty(ciphertext))
                throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            var allTheBytes = Convert.FromBase64String(ciphertext);
            var saltBytes = allTheBytes.Take(_saltSize).ToArray();
            var ciphertextBytes = allTheBytes.Skip(_saltSize).Take(allTheBytes.Length - _saltSize).ToArray();

            using (var keyDerivationFunction = new Rfc2898DeriveBytes(key, saltBytes))
            {
                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 streamReader = new StreamReader(cryptoStream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }
开发者ID:vfrz,项目名称:ISNProjects,代码行数:26,代码来源:AES.cs


示例20: Encrypt

        /// <summary> 
        /// Encrypt the data 
        /// </summary> 
        /// <param name="input">String to encrypt</param> 
        /// <returns>Encrypted string</returns> 
        public static string Encrypt(string input, string password)
        {
            byte[] utfData = UTF8Encoding.UTF8.GetBytes(input);
            byte[] saltBytes = Encoding.UTF8.GetBytes(password);
            string encryptedString = string.Empty;
            using (AesManaged aes = new AesManaged())
            {
                Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, saltBytes);

                aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                aes.KeySize = aes.LegalKeySizes[0].MaxSize;
                aes.Key = rfc.GetBytes(aes.KeySize / 8);
                aes.IV = rfc.GetBytes(aes.BlockSize / 8);

                using (ICryptoTransform encryptTransform = aes.CreateEncryptor())
                {
                    using (MemoryStream encryptedStream = new MemoryStream())
                    {
                        using (CryptoStream encryptor =
                            new CryptoStream(encryptedStream, encryptTransform, CryptoStreamMode.Write))
                        {
                            encryptor.Write(utfData, 0, utfData.Length);
                            encryptor.Flush();
                            encryptor.Close();

                            byte[] encryptBytes = encryptedStream.ToArray();
                            encryptedString = Convert.ToBase64String(encryptBytes);
                        }
                    }
                }
            }
            return encryptedString;
        }
开发者ID:kuki89,项目名称:IP_Lab,代码行数:38,代码来源:Function.cs



注:本文中的System.Security.Cryptography.AesManaged类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Cryptography.AsnEncodedData类代码示例发布时间:2022-05-26
下一篇:
C# Cryptography.AesCryptoServiceProvider类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap