TripleDES Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Представляет базовый класс для алгоритмов Triple Data Encryption Standard, от которых должны быть производны все TripleDES реализации.
public ref class TripleDES abstract : System::Security::Cryptography::SymmetricAlgorithm
public abstract class TripleDES : System.Security.Cryptography.SymmetricAlgorithm
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class TripleDES : System.Security.Cryptography.SymmetricAlgorithm
type TripleDES = class
inherit SymmetricAlgorithm
[<System.Runtime.InteropServices.ComVisible(true)>]
type TripleDES = class
inherit SymmetricAlgorithm
Public MustInherit Class TripleDES
Inherits SymmetricAlgorithm
- Наследование
- Производный
- Атрибуты
Примеры
В следующем примере кода показано, как создать и использовать TripleDES объект для шифрования и расшифровки данных в файле.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
class TripleDESSample
{
static void Main()
{
try
{
byte[] key;
byte[] iv;
// Create a new TripleDES object to generate a random key
// and initialization vector (IV).
using (TripleDES tripleDes = TripleDES.Create())
{
key = tripleDes.Key;
iv = tripleDes.IV;
}
// Create a string to encrypt.
string original = "Here is some data to encrypt.";
// The name/path of the file to write.
string filename = "CText.enc";
// Encrypt the string to a file.
EncryptTextToFile(original, filename, key, iv);
// Decrypt the file back to a string.
string decrypted = DecryptTextFromFile(filename, key, iv);
// Display the decrypted string to the console.
Console.WriteLine(decrypted);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static void EncryptTextToFile(string text, string path, byte[] key, byte[] iv)
{
try
{
// Create or open the specified file.
using (FileStream fStream = File.Open(path, FileMode.Create))
// Create a new TripleDES object.
using (TripleDES tripleDes = TripleDES.Create())
// Create a TripleDES encryptor from the key and IV
using (ICryptoTransform encryptor = tripleDes.CreateEncryptor(key, iv))
// Create a CryptoStream using the FileStream and encryptor
using (var cStream = new CryptoStream(fStream, encryptor, CryptoStreamMode.Write))
{
// Convert the provided string to a byte array.
byte[] toEncrypt = Encoding.UTF8.GetBytes(text);
// Write the byte array to the crypto stream.
cStream.Write(toEncrypt, 0, toEncrypt.Length);
}
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
throw;
}
}
public static string DecryptTextFromFile(string path, byte[] key, byte[] iv)
{
try
{
// Open the specified file
using (FileStream fStream = File.OpenRead(path))
// Create a new TripleDES object.
using (TripleDES tripleDes = TripleDES.Create())
// Create a TripleDES decryptor from the key and IV
using (ICryptoTransform decryptor = tripleDes.CreateDecryptor(key, iv))
// Create a CryptoStream using the FileStream and decryptor
using (var cStream = new CryptoStream(fStream, decryptor, CryptoStreamMode.Read))
// Create a StreamReader to turn the bytes back into text
using (StreamReader reader = new StreamReader(cStream, Encoding.UTF8))
{
// Read back all of the text from the StreamReader, which receives
// the decrypted bytes from the CryptoStream, which receives the
// encrypted bytes from the FileStream.
return reader.ReadToEnd();
}
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
throw;
}
}
}
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Module TripleDESSample
Sub Main()
Try
Dim key As Byte()
Dim iv As Byte()
' Create a new TripleDES object to generate a key
' and initialization vector (IV).
Using tripleDes As TripleDES = TripleDES.Create
key = tripleDes.Key
iv = tripleDes.IV
End Using
' Create a string to encrypt.
Dim original As String = "Here is some data to encrypt."
' The name/path of the file to write.
Dim filename As String = "CText.enc"
' Encrypt the string to a file.
EncryptTextToFile(original, filename, key, iv)
' Decrypt the file back to a string.
Dim decrypted As String = DecryptTextFromFile(filename, key, iv)
' Display the decrypted string to the console.
Console.WriteLine(decrypted)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub
Sub EncryptTextToFile(text As String, path As String, key As Byte(), iv As Byte())
Try
' Create or open the specified file.
' Create a new TripleDES object,
' Create a TripleDES encryptor from the key and IV,
' Create a CryptoStream using the MemoryStream And encryptor
Using fStream As FileStream = File.Open(path, FileMode.Create),
tripleDes As TripleDES = TripleDES.Create,
encryptor As ICryptoTransform = tripleDes.CreateEncryptor(key, iv),
cStream = New CryptoStream(fStream, encryptor, CryptoStreamMode.Write)
' Convert the passed string to a byte array.
Dim toEncrypt As Byte() = Encoding.UTF8.GetBytes(text)
' Write the byte array to the crypto stream.
cStream.Write(toEncrypt, 0, toEncrypt.Length)
End Using
Catch e As CryptographicException
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
Throw
End Try
End Sub
Function DecryptTextFromFile(path As String, key As Byte(), iv As Byte()) As String
Try
' Open the specified file
' Create a new TripleDES object.
' Create a TripleDES decryptor from the key and IV
' Create a CryptoStream using the MemoryStream and decryptor
' Create a StreamReader to turn the bytes back into text
Using mStream As FileStream = File.OpenRead(path),
tripleDes As TripleDES = TripleDES.Create,
decryptor As ICryptoTransform = tripleDes.CreateDecryptor(key, iv),
cStream = New CryptoStream(mStream, decryptor, CryptoStreamMode.Read),
reader = New StreamReader(cStream, Encoding.UTF8)
' Read back all of the text from the StreamReader, which receives
' the decrypted bytes from the CryptoStream, which receives the
' encrypted bytes from the FileStream.
Return reader.ReadToEnd()
End Using
Catch e As CryptographicException
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
Return Nothing
End Try
End Function
End Module
В следующем примере кода показано, как создать и использовать TripleDES объект для шифрования и расшифровки данных в памяти.
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
class TripleDESSample2
{
static void Main()
{
try
{
byte[] key;
byte[] iv;
// Create a new TripleDES object to generate a random key
// and initialization vector (IV).
using (TripleDES tripleDes = TripleDES.Create())
{
key = tripleDes.Key;
iv = tripleDes.IV;
}
// Create a string to encrypt.
string original = "Here is some data to encrypt.";
// Encrypt the string to an in-memory buffer.
byte[] encrypted = EncryptTextToMemory(original, key, iv);
// Decrypt the buffer back to a string.
string decrypted = DecryptTextFromMemory(encrypted, key, iv);
// Display the decrypted string to the console.
Console.WriteLine(decrypted);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static byte[] EncryptTextToMemory(string text, byte[] key, byte[] iv)
{
try
{
// Create a MemoryStream.
using (MemoryStream mStream = new MemoryStream())
{
// Create a new TripleDES object.
using (TripleDES tripleDes = TripleDES.Create())
// Create a TripleDES encryptor from the key and IV
using (ICryptoTransform encryptor = tripleDes.CreateEncryptor(key, iv))
// Create a CryptoStream using the MemoryStream and encryptor
using (var cStream = new CryptoStream(mStream, encryptor, CryptoStreamMode.Write))
{
// Convert the provided string to a byte array.
byte[] toEncrypt = Encoding.UTF8.GetBytes(text);
// Write the byte array to the crypto stream and flush it.
cStream.Write(toEncrypt, 0, toEncrypt.Length);
// Ending the using statement for the CryptoStream completes the encryption.
}
// Get an array of bytes from the MemoryStream that holds the encrypted data.
byte[] ret = mStream.ToArray();
// Return the encrypted buffer.
return ret;
}
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
throw;
}
}
public static string DecryptTextFromMemory(byte[] encrypted, byte[] key, byte[] iv)
{
try
{
// Create a buffer to hold the decrypted data.
// TripleDES-encrypted data will always be slightly bigger than the decrypted data.
byte[] decrypted = new byte[encrypted.Length];
int offset = 0;
// Create a new MemoryStream using the provided array of encrypted data.
using (MemoryStream mStream = new MemoryStream(encrypted))
{
// Create a new TripleDES object.
using (TripleDES tripleDes = TripleDES.Create())
// Create a TripleDES decryptor from the key and IV
using (ICryptoTransform decryptor = tripleDes.CreateDecryptor(key, iv))
// Create a CryptoStream using the MemoryStream and decryptor
using (var cStream = new CryptoStream(mStream, decryptor, CryptoStreamMode.Read))
{
// Keep reading from the CryptoStream until it finishes (returns 0).
int read = 1;
while (read > 0)
{
read = cStream.Read(decrypted, offset, decrypted.Length - offset);
offset += read;
}
}
}
// Convert the buffer into a string and return it.
return Encoding.UTF8.GetString(decrypted, 0, offset);
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
throw;
}
}
}
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO
Module MemorySample
Sub Main()
Try
Dim key As Byte()
Dim iv As Byte()
' Create a new TripleDES object to generate a key
' and initialization vector (IV).
Using tripleDes As TripleDES = TripleDES.Create
key = tripleDes.Key
iv = tripleDes.IV
End Using
' Create a string to encrypt.
Dim original As String = "Here is some data to encrypt."
' Encrypt the string to an in-memory buffer.
Dim encrypted As Byte() = EncryptTextToMemory(original, key, iv)
' Decrypt the buffer back to a string.
Dim decrypted As String = DecryptTextFromMemory(encrypted, key, iv)
' Display the decrypted string to the console.
Console.WriteLine(decrypted)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub
Function EncryptTextToMemory(text As String, key As Byte(), iv As Byte()) As Byte()
Try
' Create a MemoryStream.
Using mStream As New MemoryStream
' Create a new TripleDES object,
' Create a TripleDES encryptor from the key and IV,
' Create a CryptoStream using the MemoryStream And encryptor
Using tripleDes As TripleDES = TripleDES.Create,
encryptor As ICryptoTransform = tripleDes.CreateEncryptor(key, iv),
cStream = New CryptoStream(mStream, encryptor, CryptoStreamMode.Write)
' Convert the passed string to a byte array.
Dim toEncrypt As Byte() = Encoding.UTF8.GetBytes(text)
' Write the byte array to the crypto stream and flush it.
cStream.Write(toEncrypt, 0, toEncrypt.Length)
' Ending the using block for the CryptoStream completes the encryption.
End Using
' Get an array of bytes from the MemoryStream that holds the encrypted data.
Dim ret As Byte() = mStream.ToArray()
' Return the encrypted buffer.
Return ret
End Using
Catch e As CryptographicException
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
Throw
End Try
End Function
Function DecryptTextFromMemory(encrypted As Byte(), key As Byte(), iv As Byte()) As String
Try
' Create a buffer to hold the decrypted data.
' TripleDES-encrypted data will always be slightly bigger than the decrypted data.
Dim decrypted(encrypted.Length - 1) As Byte
Dim offset As Integer = 0
' Create a new MemoryStream using the provided array of encrypted data.
' Create a new TripleDES object.
' Create a TripleDES decryptor from the key and IV
' Create a CryptoStream using the MemoryStream and decryptor
Using mStream As New MemoryStream(encrypted),
tripleDes As TripleDES = TripleDES.Create,
decryptor As ICryptoTransform = tripleDes.CreateDecryptor(key, iv),
cStream = New CryptoStream(mStream, decryptor, CryptoStreamMode.Read)
' Keep reading from the CryptoStream until it finishes (returns 0).
Dim read As Integer = 1
While (read > 0)
read = cStream.Read(decrypted, offset, decrypted.Length - offset)
offset += read
End While
End Using
' Convert the buffer into a string and return it.
Return New ASCIIEncoding().GetString(decrypted, 0, offset)
Catch e As CryptographicException
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
Return Nothing
End Try
End Function
End Module
Комментарии
TripleDES использует три последовательных итерации алгоритма DES . Он может использовать два или три 56-разрядных ключа.
Note
Доступен более новый алгоритм симметричного шифрования , расширенный стандарт шифрования (AES). Рекомендуется использовать Aes класс и производные TripleDES классы вместо класса. Используйте TripleDES только для совместимости с устаревшими приложениями и данными.
Этот алгоритм поддерживает длину ключей от 128 бит до 192 бит в добавках 64 бита.
Конструкторы
| Имя | Описание |
|---|---|
| TripleDES() |
Инициализирует новый экземпляр класса TripleDES. |
Поля
| Имя | Описание |
|---|---|
| BlockSizeValue |
Представляет размер блока в битах криптографической операции. (Унаследовано от SymmetricAlgorithm) |
| FeedbackSizeValue |
Представляет размер обратной связи (в битах) криптографической операции. (Унаследовано от SymmetricAlgorithm) |
| IVValue |
Представляет вектор инициализации (IV) для симметричного алгоритма. (Унаследовано от SymmetricAlgorithm) |
| KeySizeValue |
Представляет размер в битах секретного ключа, используемого симметричным алгоритмом. (Унаследовано от SymmetricAlgorithm) |
| KeyValue |
Представляет секретный ключ для симметричного алгоритма. (Унаследовано от SymmetricAlgorithm) |
| LegalBlockSizesValue |
Указывает размеры блоков в битах, поддерживаемые симметричным алгоритмом. (Унаследовано от SymmetricAlgorithm) |
| LegalKeySizesValue |
Указывает размеры ключей в битах, поддерживаемые симметричным алгоритмом. (Унаследовано от SymmetricAlgorithm) |
| ModeValue |
Представляет режим шифра, используемый в симметричном алгоритме. (Унаследовано от SymmetricAlgorithm) |
| PaddingValue |
Представляет режим заполнения, используемый в симметричном алгоритме. (Унаследовано от SymmetricAlgorithm) |
Свойства
| Имя | Описание |
|---|---|
| BlockSize |
Возвращает или задает размер блока в битах криптографической операции. (Унаследовано от SymmetricAlgorithm) |
| FeedbackSize |
Возвращает или задает размер обратной связи (в битах) криптографической операции для режимов шифрования обратной связи (CFB) и выходных отзывов (OFB). (Унаследовано от SymmetricAlgorithm) |
| IV |
Возвращает или задает вектор инициализации (IV) для симметричного алгоритма. (Унаследовано от SymmetricAlgorithm) |
| Key |
Возвращает или задает секретный ключ для алгоритма TripleDES . |
| KeySize |
Возвращает или задает размер в битах секретного ключа, используемого симметричным алгоритмом. (Унаследовано от SymmetricAlgorithm) |
| LegalBlockSizes |
Возвращает размеры блоков в битах, поддерживаемые симметричным алгоритмом. |
| LegalBlockSizes |
Возвращает размеры блоков в битах, поддерживаемые симметричным алгоритмом. (Унаследовано от SymmetricAlgorithm) |
| LegalKeySizes |
Возвращает размеры ключей в битах, поддерживаемые симметричным алгоритмом. |
| LegalKeySizes |
Возвращает размеры ключей в битах, поддерживаемые симметричным алгоритмом. (Унаследовано от SymmetricAlgorithm) |
| Mode |
Возвращает или задает режим для работы симметричного алгоритма. (Унаследовано от SymmetricAlgorithm) |
| Padding |
Возвращает или задает режим заполнения, используемый в симметричном алгоритме. (Унаследовано от SymmetricAlgorithm) |
Методы
| Имя | Описание |
|---|---|
| Clear() |
Освобождает все ресурсы, используемые классом SymmetricAlgorithm . (Унаследовано от SymmetricAlgorithm) |
| Create() |
Создает экземпляр криптографического объекта для выполнения алгоритма TripleDES . |
| Create(String) |
Создает экземпляр криптографического объекта для выполнения указанной реализации алгоритма TripleDES . |
| CreateDecryptor() |
Создает объект симметричного расшифровки с текущим Key свойством и вектором инициализации (IV). (Унаследовано от SymmetricAlgorithm) |
| CreateDecryptor(Byte[], Byte[]) |
При переопределении в производном классе создает симметричный объект расшифровки с указанным Key свойством и вектором инициализации (IV). (Унаследовано от SymmetricAlgorithm) |
| CreateEncryptor() |
Создает объект симметричного шифратора с текущим Key свойством и вектором инициализации (IV). (Унаследовано от SymmetricAlgorithm) |
| CreateEncryptor(Byte[], Byte[]) |
При переопределении в производном классе создает объект симметричного шифратора с указанным Key свойством и вектором инициализации (IV). (Унаследовано от SymmetricAlgorithm) |
| Dispose() |
Освобождает все ресурсы, используемые текущим экземпляром класса SymmetricAlgorithm. (Унаследовано от SymmetricAlgorithm) |
| Dispose(Boolean) |
Освобождает неуправляемые ресурсы, используемые SymmetricAlgorithm и при необходимости освобождает управляемые ресурсы. (Унаследовано от SymmetricAlgorithm) |
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GenerateIV() |
При переопределении в производном классе создает вектор случайной инициализации (IV) для использования алгоритма. (Унаследовано от SymmetricAlgorithm) |
| GenerateKey() |
При переопределении в производном классе создает случайный ключ (Key) для использования для алгоритма. (Унаследовано от SymmetricAlgorithm) |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| IsWeakKey(Byte[]) |
Определяет, является ли указанный ключ слабым. |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
| ValidKeySize(Int32) |
Определяет, является ли указанный размер ключа допустимым для текущего алгоритма. (Унаследовано от SymmetricAlgorithm) |
Явные реализации интерфейса
| Имя | Описание |
|---|---|
| IDisposable.Dispose() |
Этот API поддерживает инфраструктуру продукта и не предназначен для использования непосредственно из программного кода. Освобождает неуправляемые ресурсы, используемые SymmetricAlgorithm и при необходимости освобождает управляемые ресурсы. (Унаследовано от SymmetricAlgorithm) |