本文整理汇总了C#中System.Security.Cryptography.AesCryptoServiceProvider类的典型用法代码示例。如果您正苦于以下问题:C# AesCryptoServiceProvider类的具体用法?C# AesCryptoServiceProvider怎么用?C# AesCryptoServiceProvider使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
AesCryptoServiceProvider类属于System.Security.Cryptography命名空间,在下文中一共展示了AesCryptoServiceProvider类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AESEncryption
public static void AESEncryption()
{
try
{
string original = "Here is some data to encrypt!";
// Create a new instance of the AesCryptoServiceProvider
// class. This generates a new key and initialization vector (IV).
using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
{
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);
//Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Round Trip: {0}", roundtrip);
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
示例2: OAuthServerHelper
static OAuthServerHelper()
{
RSAParameters privateRsaParameters;
RSAParameters publicRsaParameters;
using (var rsaKeyGen = new RSACryptoServiceProvider(RsaKeySize))
{
privateRsaParameters = rsaKeyGen.ExportParameters(true);
publicRsaParameters = rsaKeyGen.ExportParameters(false);
}
Tuple<byte[], byte[]> aesKeyAndIV;
using (var aesKeyGen = new AesCryptoServiceProvider())
{
aesKeyAndIV = Tuple.Create(aesKeyGen.Key, aesKeyGen.IV);
}
rsa = new ThreadLocal<RSACryptoServiceProvider>(() =>
{
var result = new RSACryptoServiceProvider();
result.ImportParameters(privateRsaParameters);
return result;
});
aes = new ThreadLocal<AesCryptoServiceProvider>(() =>
{
var result = new AesCryptoServiceProvider();
result.Key = aesKeyAndIV.Item1;
result.IV = aesKeyAndIV.Item2;
return result;
});
rsaExponent = OAuthHelper.BytesToString(publicRsaParameters.Exponent);
rsaModulus = OAuthHelper.BytesToString(publicRsaParameters.Modulus);
}
示例3: CreateAes
private static Aes CreateAes(ProgramOptions options, byte[] iv = null)
{
if (!options.EncryptionEnabled)
return null;
var salt = Convert.FromBase64String("hkuDTnecxj+oDytliJ69BQ==");
using (var kdf = new Rfc2898DeriveBytes(options.EncryptionPassword, salt))
{
var aes = new AesCryptoServiceProvider();
var keyLen = aes.KeySize/8;
if (iv != null)
{
aes.Key = kdf.GetBytes(keyLen);
aes.IV = iv;
return aes;
}
var ivLength = aes.BlockSize/8;
var bytes = kdf.GetBytes(keyLen + ivLength);
aes.Key = bytes.SubArray(0, keyLen);
aes.IV = bytes.SubArray(keyLen, ivLength);
return aes;
}
}
示例4: AESEncryptor
public static string AESEncryptor(string plainText, byte[] Key, byte[] IV)
{
byte[] data = ASCIIEncoding.ASCII.GetBytes(plainText);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
string encryptedString = Convert.ToBase64String(aes.CreateEncryptor(Key, IV).TransformFinalBlock(data, 0, data.Length));
return encryptedString;
}
示例5: EncryptAndUpload
public static void EncryptAndUpload(string file, string awsPath, string key)
{
if (bool.Parse(ConfigurationManager.AppSettings["ManagedEncryption"]))
{
Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(key, appKey);
using (var aes = new AesCryptoServiceProvider())
{
aes.Key = deriveBytes.GetBytes(aes.KeySize / 8);
aes.IV = deriveBytes.GetBytes(aes.BlockSize / 8);
using (var temp = new FileStream(file + "_encrypted", FileMode.Create))
{
using (var stream = new CryptoStream(new FileStream(file, FileMode.Open), aes.CreateEncryptor(), CryptoStreamMode.Read))
{
stream.CopyTo(temp);
}
}
UploadFile(file + "_encrypted", awsPath);
File.Delete(file + "_encrypted");
}
}
else
UploadFile(file, awsPath);
}
示例6: Protect
public static byte[] Protect(byte[] encryptionKey, byte[] validationKey, byte[] initializationVector, byte[] plainText)
{
using (var provider = new AesCryptoServiceProvider())
{
using (ICryptoTransform transform = provider.CreateEncryptor(encryptionKey, initializationVector))
{
using (var ms = new MemoryStream())
{
ms.Write(initializationVector, 0, initializationVector.Length);
using (var cryptoStream = new CryptoStream(ms, transform, CryptoStreamMode.Write))
{
// Encrypted payload
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
// Compute signature
using (var sha = new HMACSHA256(validationKey))
{
checked
{
byte[] signature = sha.ComputeHash(ms.GetBuffer(), 0, (int)ms.Length);
// Write the signature to the paylod
ms.Write(signature, 0, signature.Length);
// Final bytes
return ms.ToArray();
}
}
}
}
}
}
}
示例7: 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;
}
示例8: DecryptAesCbc
/// <summary>
/// Decrypt a message using AES in CBC (cipher-block chaining) mode.
/// </summary>
/// <param name="ciphertext">The message encrypted with AES in CBC mode</param>
/// <param name="key">The key used to encrypt the message</param>
/// <param name="iv">The initialization vector provided, if one was provided. If you are absolutely certain
/// the key will only be used once, an IV is not necessary and zero will be used.</param>
/// <param name="checkAndRemoveHmac">Set if an HMACHSA256 was placed at the end of the plaintext before encrypting.
/// The HMAC will be removed before the plaintext is returned. If the HMAC does not match, the method will throw a
/// System.Security.Cryptography.CryptographicException.</param>
/// <returns>The plaintext resulting from decrypting the ciphertext with the given key.</returns>
public static byte[] DecryptAesCbc(byte[] ciphertext, byte[] key, byte[] iv = null, bool checkAndRemoveHmac = false)
{
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
aes.Key = key;
if (iv == null)
iv = NullIv;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
// Decrypt the message
using (System.IO.MemoryStream plaintextStream = new System.IO.MemoryStream())
{
using (CryptoStream cs = new CryptoStream(plaintextStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(ciphertext, 0, ciphertext.Length);
}
byte[] plaintext = plaintextStream.ToArray();
if (checkAndRemoveHmac)
{
byte[] hmacProvided = plaintext.Skip(plaintext.Length - Sha256HmacLength).ToArray();
plaintext = plaintext.Take(plaintext.Length - Sha256HmacLength).ToArray();
byte[] hmacCalculated = new HMACSHA256(key).ComputeHash(plaintext);
if (!hmacProvided.SequenceEqual(hmacCalculated))
throw new CryptographicException("Message authentication code validation failed.");
}
return plaintext;
}
}
}
示例9: AesEncrypt
/// <summary>
/// AES加密
/// </summary>
/// <param name="data"></param>
/// <param name="key"></param>
/// <returns></returns>
public static byte[] AesEncrypt(string data, byte[] key)
{
if (key.Length != 16)
{
var ex = new Exception("the length of AES ecrypted key must be 16bit.");
throw ex;
}
byte[] result;
using (SymmetricAlgorithm algorithm = new AesCryptoServiceProvider())
{
algorithm.Mode = CipherMode.ECB;
algorithm.Padding = PaddingMode.PKCS7;
using (ICryptoTransform transform = algorithm.CreateEncryptor(key, key))
{
using (MemoryStream ms = new MemoryStream())
{
using (Stream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(cs))
{
writer.Write(data);
}
result = ms.ToArray();
}
}
}
}
return result;
}
示例10: DecryptedStream
public Stream DecryptedStream(Stream streamToDecrypt)
{
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
using (ICspProxy csp = CspFactory.GetProvider())
{
// Get the AES key from the stream
// The length will be the size of the RSA key which was used to encrypt
// the 256 bit AES key (assuming the RSA key is always larger than 256 bit).
byte[] encryptedKey = new byte[AsymmetricKeySize / 8];
byte[] decryptedKey;
streamToDecrypt.Read(encryptedKey, 0, encryptedKey.Length);
decryptedKey = csp.Decrypt(encryptedKey);
// Attempt to read IV from Stream
byte[] ivBytes = new byte[aesAlg.BlockSize / 8];
streamToDecrypt.Read(ivBytes, 0, ivBytes.Length);
// Set key and initialization vector
aesAlg.Key = decryptedKey;
aesAlg.IV = ivBytes;
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor();
CryptoStream cryptoStream = new CryptoStream(streamToDecrypt, decryptor, CryptoStreamMode.Read);
return cryptoStream;
}
}
示例11: EncryptAesCbc
/// <summary>
/// Encrypt a message using AES in CBC (cipher-block chaining) mode.
/// </summary>
/// <param name="plaintext">The message (plaintext) to encrypt</param>
/// <param name="key">An AES key</param>
/// <param name="iv">The IV to use or null to use a 0 IV</param>
/// <param name="addHmac">When set, a SHA256-based HMAC (HMAC256) of 32 bytes using the same key is added to the plaintext
/// before it is encrypted.</param>
/// <returns>The ciphertext derived by encrypting the orignal message using AES in CBC mode</returns>
public static byte[] EncryptAesCbc(byte[] plaintext, byte[] key, byte[] iv = null, bool addHmac = false)
{
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
aes.Key = key;
if (iv == null)
iv = NullIv;
aes.Mode = CipherMode.CBC;
aes.IV = iv;
// Encrypt the message with the key using CBC and InitializationVector=0
byte[] cipherText;
using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(plaintext, 0, plaintext.Length);
if (addHmac)
{
byte[] hmac = new HMACSHA256(key).ComputeHash(plaintext);
cs.Write(hmac, 0, hmac.Length);
}
cs.Flush();
}
cipherText = ciphertext.ToArray();
}
return cipherText;
}
}
示例12: InsecureEncryptionAlgorithm
public InsecureEncryptionAlgorithm()
{
using (var tripleDES = new MyTripleDESCryptoServiceProvider()) //Noncompliant
{
//...
}
using (var des = new DESCryptoServiceProvider()) //Noncompliant
{
//...
}
using (TripleDES TripleDESalg = TripleDES.Create()) //Noncompliant
{
}
using (var des = DES.Create("fgdsgsdfgsd")) //Noncompliant
{
}
using (var aes = new AesCryptoServiceProvider())
{
//...
}
SymmetricAlgorithm des1 = SymmetricAlgorithm.Create("DES"); //Noncompliant
des1 = SymmetricAlgorithm.Create("TripleDES"); //Noncompliant
des1 = SymmetricAlgorithm.Create("3DES"); //Noncompliant
}
示例13: AliceSendsData
private async static Task<byte[]> AliceSendsData(string message)
{
Console.WriteLine("Alice send message {0}", message);
byte[] rawData = Encoding.UTF8.GetBytes(message);
byte[] encryptedData = null;
using(var aliceAlgo = new ECDiffieHellmanCng(aliceKey))
{
using(CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.GenericPublicBlob))
{
byte[] symmKey = aliceAlgo.DeriveKeyMaterial(bobPubKey);
Console.WriteLine("Alice create this symm key with Bobs public key information : {0}", Convert.ToBase64String(symmKey));
using(var aes = new AesCryptoServiceProvider())
{
aes.Key = symmKey;
aes.GenerateIV();
using(ICryptoTransform encryptor = aes.CreateEncryptor())
{
using(MemoryStream ms = new MemoryStream())
{
var cs = new CryptoStream(ms, encryptor,CryptoStreamMode.Write);
await ms.WriteAsync(aes.IV, 0, aes.IV.Length);
cs.Write(rawData, 0, rawData.Length);
cs.Close();
encryptedData = ms.ToArray();
}
}
aes.Clear();
}
}
}
Console.WriteLine("Alice message is encrypted : {0}", Convert.ToBase64String(encryptedData));
return encryptedData;
}
示例14: CTS_NotAllowed
public void CTS_NotAllowed ()
{
// this check is normally (e.g. RijndaelManaged) done later
using (var aes = new AesCryptoServiceProvider ()) {
aes.Mode = CipherMode.CTS;
}
}
示例15: DecryptString
public static string DecryptString(byte[] encryptedString, byte[] encryptionKey)
{
using (var provider = new AesCryptoServiceProvider())
{
provider.Key = encryptionKey;
using (var ms = new MemoryStream(encryptedString))
{
// Read the first 16 bytes which is the IV.
byte[] iv = new byte[16];
ms.Read(iv, 0, 16);
provider.IV = iv;
using (var decryptor = provider.CreateDecryptor())
{
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (var sr = new StreamReader(cs))
{
return sr.ReadToEnd();
}
}
}
}
}
}