本文整理汇总了C#中CipherMode类的典型用法代码示例。如果您正苦于以下问题:C# CipherMode类的具体用法?C# CipherMode怎么用?C# CipherMode使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CipherMode类属于命名空间,在下文中一共展示了CipherMode类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Decrypt
// Decrypt a byte array into a byte array using a key and an IV
public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV, CipherMode cipherMode, PaddingMode paddingMode)
{
// Create a MemoryStream that is going to accept the
// decrypted bytes
MemoryStream ms = new MemoryStream();
// Create a symmetric algorithm.
// We are going to use Rijndael because it is strong and
// available on all platforms.
// You can use other algorithms, to do so substitute the next
// line with something like
// TripleDES alg = TripleDES.Create();
Rijndael alg = Rijndael.Create();
// Now set the key and the IV.
// We need the IV (Initialization Vector) because the algorithm
// is operating in its default
// mode called CBC (Cipher Block Chaining). The IV is XORed with
// the first block (8 byte)
// of the data after it is decrypted, and then each decrypted
// block is XORed with the previous
// cipher block. This is done to make encryption more secure.
// There is also a mode called ECB which does not need an IV,
// but it is much less secure.
alg.Mode = cipherMode;
alg.Padding = paddingMode;
alg.Key = Key;
alg.IV = IV;
// Create a CryptoStream through which we are going to be
// pumping our data.
// CryptoStreamMode.Write means that we are going to be
// writing data to the stream
// and the output will be written in the MemoryStream
// we have provided.
CryptoStream cs = new CryptoStream(ms,
alg.CreateDecryptor(), CryptoStreamMode.Write);
// Write the data and make it do the decryption
cs.Write(cipherData, 0, cipherData.Length);
// Close the crypto stream (or do FlushFinalBlock).
// This will tell it that we have done our decryption
// and there is no more data coming in,
// and it is now a good time to remove the padding
// and finalize the decryption process.
cs.Close();
// Now get the decrypted data from the MemoryStream.
// Some people make a mistake of using GetBuffer() here,
// which is not the right way.
byte[] decryptedData = ms.ToArray();
return decryptedData;
}
示例2: Decrypt
public static byte[] Decrypt(byte[] value, byte[] key, byte[] iv, CipherMode mode = CipherMode.CBC, PaddingMode padding = PaddingMode.None)
{
if (value == null || value.Length <= 0)
throw new ArgumentNullException("value");
if (key == null || key.Length <= 0)
throw new ArgumentNullException("key");
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException("iv");
byte[] result;
using (RijndaelManaged rijndael = new RijndaelManaged())
{
rijndael.Key = key;
rijndael.IV = iv;
rijndael.Mode = mode;
rijndael.Padding = padding;
ICryptoTransform transform = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV);
using (MemoryStream memory = new MemoryStream())
using (CryptoStream crypto = new CryptoStream(memory, transform, CryptoStreamMode.Read))
{
crypto.Write(value, 0, value.Length);
result = memory.ToArray();
}
}
return result;
}
示例3: CreateTransformCore
private static ICryptoTransform CreateTransformCore(
CipherMode cipherMode,
PaddingMode paddingMode,
byte[] key,
byte[] iv,
int blockSize,
bool encrypting)
{
// The algorithm pointer is a static pointer, so not having any cleanup code is correct.
IntPtr algorithm;
switch (cipherMode)
{
case CipherMode.CBC:
algorithm = Interop.Crypto.EvpDesCbc();
break;
case CipherMode.ECB:
algorithm = Interop.Crypto.EvpDesEcb();
break;
default:
throw new NotSupportedException();
}
BasicSymmetricCipher cipher = new OpenSslCipher(algorithm, cipherMode, blockSize, key, 0, iv, encrypting);
return UniversalCryptoTransform.Create(paddingMode, cipher, encrypting);
}
示例4: NewEncryptor
private ICryptoTransform NewEncryptor (byte[] rgbKey,
CipherMode mode,
byte[] rgbIV,
int feedbackSize,
RijndaelManagedTransformMode encryptMode) {
// Build the key if one does not already exist
if (rgbKey == null) {
rgbKey = Utils.GenerateRandom(KeySizeValue / 8);
}
// If not ECB mode, make sure we have an IV. In CoreCLR we do not support ECB, so we must have
// an IV in all cases.
#if !FEATURE_CRYPTO
if (mode != CipherMode.ECB) {
#endif // !FEATURE_CRYPTO
if (rgbIV == null) {
rgbIV = Utils.GenerateRandom(BlockSizeValue / 8);
}
#if !FEATURE_CRYPTO
}
#endif // !FEATURE_CRYPTO
// Create the encryptor/decryptor object
return new RijndaelManagedTransform (rgbKey,
mode,
rgbIV,
BlockSizeValue,
feedbackSize,
PaddingValue,
encryptMode);
}
示例5: TripleDesOpenSslCipher
public TripleDesOpenSslCipher(CipherMode cipherMode, int blockSizeInBytes, byte[] key, byte[] iv, bool encrypting)
: base(cipherMode.GetCipherIv(iv), blockSizeInBytes)
{
_encrypting = encrypting;
OpenKey(cipherMode, key);
}
示例6: GetCipher
private Native.SafeCipherHandle GetCipher(CipherMode mode, int keyLength)
{
if (mode == CipherMode.CBC) {
switch (keyLength) {
case 16:
return Native.EVP_aes_128_cbc ();
case 24:
return Native.EVP_aes_192_cbc ();
case 32:
return Native.EVP_aes_256_cbc ();
}
} else if (mode == CipherMode.ECB) {
switch (keyLength) {
case 16:
return Native.EVP_aes_128_ecb ();
case 24:
return Native.EVP_aes_192_ecb ();
case 32:
return Native.EVP_aes_256_ecb ();
}
}
throw new CryptographicException (string.Format ("{0} not supported", mode));
}
示例7: EncriptarDeImagen
public static byte[] EncriptarDeImagen(byte[] bytEncriptar, string strPK, CipherMode cMode)
{
Rijndael rijndael = Rijndael.Create();
byte[] buffer = null;
byte[] array = null;
try
{
rijndael.Key = new PasswordDeriveBytes(strPK, null).GetBytes(0x20);
rijndael.Mode = cMode;
byte[] destinationArray = new byte[bytEncriptar.Length - 0x22];
Array.Copy(bytEncriptar, 0x22, destinationArray, 0, bytEncriptar.Length - 0x22);
buffer = rijndael.CreateEncryptor().TransformFinalBlock(destinationArray, 0, destinationArray.Length);
array = new byte[0x22 + buffer.Length];
bytEncriptar.CopyTo(array, 0);
buffer.CopyTo(array, 0x22);
}
catch
{
}
finally
{
rijndael.Clear();
}
return array;
}
示例8: DecryptMessage
public static string DecryptMessage(string message, byte[] key, CipherMode mode)
{
var cipherBytes = CipherHelper.ConvertFromHexString(message).ToArray<byte>();
// first 16 bytes of cipher text is IV
var IV = cipherBytes.Take<byte>(blockSize).ToArray<byte>();
cipherBytes = cipherBytes.Skip<byte>(blockSize).ToArray<byte>();
var textBytes = new byte[cipherBytes.Length];
using (var aesAlg = Aes.Create())
{
aesAlg.Mode = mode;
aesAlg.KeySize = keySize;
aesAlg.Padding = PaddingMode.PKCS7;
using(ICryptoTransform decryptor = aesAlg.CreateDecryptor(key, IV))
{
using(MemoryStream memStream = new MemoryStream(cipherBytes))
{
using(CryptoStream cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
{
using (var reader = new BinaryReader(cryptoStream))
{
textBytes = reader.ReadBytes(cipherBytes.Length);
}
}
}
}
}
return CipherHelper.GetASCIIString(textBytes);
}
示例9: _NewEncryptor
[System.Security.SecurityCritical] // auto-generated
private ICryptoTransform _NewEncryptor (byte[] rgbKey, CipherMode mode, byte[] rgbIV, int feedbackSize, CryptoAPITransformMode encryptMode) {
int cArgs = 0;
int[] rgArgIds = new int[10];
Object[] rgArgValues = new Object[10];
// Check for bad values
// 1) we don't support OFB mode in DESCryptoServiceProvider
if (mode == CipherMode.OFB)
throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_OFBNotSupported"));
// 2) we only support CFB with a feedback size of 8 bits
if ((mode == CipherMode.CFB) && (feedbackSize != 8))
throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_CFBSizeNotSupported"));
// Build the key if one does not already exist
if (rgbKey == null) {
rgbKey = new byte[8];
Utils.StaticRandomNumberGenerator.GetBytes(rgbKey);
}
// Set the mode for the encryptor (defaults to CBC)
if (mode != CipherMode.CBC) {
rgArgIds[cArgs] = Constants.KP_MODE;
rgArgValues[cArgs] = mode;
cArgs += 1;
}
// If not ECB mode -- pass in an IV
if (mode != CipherMode.ECB) {
if (rgbIV == null) {
rgbIV = new byte[8];
Utils.StaticRandomNumberGenerator.GetBytes(rgbIV);
}
//
// We truncate IV's that are longer than the block size to 8 bytes : this is
// done to maintain backward compatibility with the behavior shipped in V1.x.
// The call to set the IV in CryptoAPI will ignore any bytes after the first 8
// bytes. We'll still reject IV's that are shorter than the block size though.
//
if (rgbIV.Length < 8)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidIVSize"));
rgArgIds[cArgs] = Constants.KP_IV;
rgArgValues[cArgs] = rgbIV;
cArgs += 1;
}
// If doing OFB or CFB, then we need to set the feed back loop size
if ((mode == CipherMode.OFB) || (mode == CipherMode.CFB)) {
rgArgIds[cArgs] = Constants.KP_MODE_BITS;
rgArgValues[cArgs] = feedbackSize;
cArgs += 1;
}
// Create the encryptpr/decryptor object
return new CryptoAPITransform(Constants.CALG_DES, cArgs, rgArgIds,
rgArgValues, rgbKey, PaddingValue,
mode, BlockSizeValue, feedbackSize, false,
encryptMode);
}
示例10: Decrypt
public static string Decrypt(string cipherText, string Password, CipherMode cipherMode, PaddingMode paddingMode)
{
byte[] cipherData = Convert.FromBase64String(cipherText);
PasswordDeriveBytes bytes = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 110, 0x20, 0x4d, 0x65, 100, 0x76, 0x65, 100, 0x65, 0x76 });
byte[] buffer2 = Decrypt(cipherData, bytes.GetBytes(0x20), bytes.GetBytes(0x10), cipherMode, paddingMode);
return Encoding.Unicode.GetString(buffer2);
}
示例11: buttonGenerator_Click
private void buttonGenerator_Click(object sender, EventArgs e)
{
try
{
// Selected 'Preset'
if (tabControl.SelectedIndex == 0)
{
CurrentBlockSize = comboBoxPresets.SelectedIndex == 0 ? 128 : 256;
CurrentKeySize = comboBoxPresets.SelectedIndex == 0 ? 128 : 256;
SelectedCipher = CipherMode.CBC;
SelectedPadding = PaddingMode.PKCS7;
}
int index = tabControl.SelectedIndex;
if ((index == 0 && comboBoxPresets.SelectedIndex == 1) ||
(index == 1 && radioButtonAes.Checked))
Build(new RijndaelManaged());
else
Build(new AesManaged());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
示例12: EncriptarDeImagen
public static byte[] EncriptarDeImagen(byte[] bytEncriptar, string strPK, CipherMode cMode)
{
Rijndael miRijndael = Rijndael.Create();
byte[] encrypted = null;
byte[] returnValue = null;
try
{
miRijndael.Key = (new PasswordDeriveBytes(strPK, null)).GetBytes(32);
miRijndael.Mode = cMode;
byte[] toEncrypt = new byte[bytEncriptar.Length-34];
Array.Copy(bytEncriptar, 34, toEncrypt, 0, bytEncriptar.Length-34);
encrypted = (miRijndael.CreateEncryptor()).TransformFinalBlock(toEncrypt, 0, toEncrypt.Length);
returnValue = new byte[34 + encrypted.Length];
bytEncriptar.CopyTo(returnValue, 0);
encrypted.CopyTo(returnValue, 34);
}
catch { }
finally { miRijndael.Clear(); }
return returnValue;
}
示例13: TestAlgorithms
public static bool TestAlgorithms(SymmetricAlgorithm encAlgorithm, SymmetricAlgorithm decAlgorithm, CipherMode[] modes, int maxLength, int iterations)
{
Random rand = new Random();
for (int i = 0; i < iterations; i++)
{
// Create random data, key, IV, mode
//
byte[] key = new byte[KeySizeBytes[rand.Next(KeySizeBytes.Length)]];
rand.NextBytes(key);
byte[] data = new byte[rand.Next(1, maxLength + 1)];
rand.NextBytes(data);
byte[] IV = new byte[BlockSizeBytes];
rand.NextBytes(IV);
CipherMode mode = modes[rand.Next(modes.Length)];
PaddingMode padding = PaddingModes[new Random().Next(PaddingModes.Length)];
// Encrypt the data
//
byte[] encryptedData;
encAlgorithm.Key = key;
encAlgorithm.IV = IV;
encAlgorithm.Mode = mode;
encAlgorithm.Padding = padding;
ICryptoTransform transform = encAlgorithm.CreateEncryptor();
encryptedData = transform.TransformFinalBlock(data, 0, data.Length);
// Decrypt the data
//
byte[] decryptedData;
decAlgorithm.Key = key;
decAlgorithm.IV = IV;
decAlgorithm.Mode = mode;
decAlgorithm.Padding = padding;
transform = decAlgorithm.CreateDecryptor();
decryptedData = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
if (!CompareBytes(data, decryptedData))
{
Console.WriteLine("ERROR - roundtrip encrypt/decrypt failed!\n");
Console.WriteLine("Encryption algorithm: {0}", encAlgorithm.ToString());
Console.WriteLine("Decryption algorithm: {0}", decAlgorithm.ToString());
Console.WriteLine("Original data: {0}", ByteArrayToString(data));
Console.WriteLine("Roundtrip data: {0}", ByteArrayToString(decryptedData));
Console.WriteLine("Key: {0}", ByteArrayToString(key));
Console.WriteLine("IV: {0}", ByteArrayToString(IV));
Console.WriteLine("Cipher mode: {0}", mode.ToString());
Console.WriteLine("Padding mode: {0}", padding.ToString());
return false;
}
}
return true;
}
示例14: AES_THL
/// <summary>
/// Initialize new AES
/// </summary>
/// <param name="keySize">Optional key size. Default 128.</param>
/// <param name="mode">Optional cipher mode. Default: CBC</param>
public AES_THL(int keySize = 128, CipherMode mode = CipherMode.CBC)
{
this.keySize = keySize;
this.mode = mode;
aes = new AesCryptoServiceProvider();
aes.Mode = mode;
aes.KeySize = keySize;
}
示例15: CapiSymmetricAlgorithm
public CapiSymmetricAlgorithm(int blockSize, int feedbackSize, SafeCspHandle provider, SafeCapiKeyHandle key, byte[] iv, CipherMode cipherMode, PaddingMode paddingMode, EncryptionMode encryptionMode)
{
this.m_blockSize = blockSize;
this.m_encryptionMode = encryptionMode;
this.m_paddingMode = paddingMode;
this.m_provider = provider.Duplicate();
this.m_key = SetupKey(key, ProcessIV(iv, blockSize, cipherMode), cipherMode, feedbackSize);
}