本文整理汇总了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();
}
示例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;
}
示例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;
}
示例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);
}
}
}
}
示例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;
}
示例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);
}
}
}
示例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);
}
}
示例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;
}
}
}
示例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();
}
}
}
示例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!"));
}
示例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;
}
示例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;
}
示例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 "";
}
}
示例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 "";
}
}
示例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;
}