Криптографические средства Microsoft .NET
Дипломная работа - Компьютеры, программирование
Другие дипломы по предмету Компьютеры, программирование
ile, then encrypt and write to the output file.( rdlen < totlen )
{= fin->Read( bin, 0, 100 );>Write( bin, 0, len );= rdlen + len;::WriteLine( "{0} bytes processed", rdlen );
}>Close();>Close();>Close();
}
Асимметричное шифрование
В примере кода показано, как реализовать пользовательский алгоритм асимметричного шифрования, наследуемый от класса AsymmetricAlgorithm. Для демонстрации порядка использования пользовательского класса приведен дополнительный класс.
Язык Visual C++
#using
#using namespace System;namespace System::Xml;namespace System::Text;namespace System::Security::Cryptography;namespace System::Reflection;
[assembly: AssemblyKeyFile("CustomCrypto.snk")];
[assembly: AssemblyVersion("1.0.0.0")];
[assembly: CLSCompliant(true)];Contoso
{
// Define a CustomCrypto class that inherits from the AsymmetricAlgorithm
// class.ref class CustomCrypto :System::Security::Cryptography::AsymmetricAlgorithm
{
// Declare local member variables.:^ cryptoServiceParameters;^ customValidKeySizes;
// Initialize a CustomCrypto with the default key size of 8.:()
{= arrayKeySize = 8;
}
// Initialize a CustomCrypto with the specified key size.:(int keySize)
{= arrayKeySize = keySize;
}
// Accessor function for keySizes member variable.:array^ LegalKeySizes
{array^ get() override
{(arrayClone();
}
}
// Modify the KeySizeValue property inherited from the Asymmetric
// class. Prior to setting the value, ensure it falls within the
// range identified in the local keySizes member variable.:int KeySize
{int get() override
{KeySizeValue;
}void set(int value) override
{(int i = 0; i Length; i++)
{(customValidKeySizes[i]->SkipSize == 0)
{(customValidKeySizes[i]->MinSize == value)
{= value;;
}
}
{(int j = customValidKeySizes[i]->MinSize;SkipSize)
{(j == value)
{= value;;
}
}
}
}
// If the key does not fall within the range identified
// in the keySizes member variable, throw an exception.gcnew CryptographicException("Invalid key size.");
}
}
// Initialize the parameters with default values.:InitializeParameters()
{= gcnew CspParameters();>ProviderName = "Contoso";>KeyContainerName = "SecurityBin1";>KeyNumber = 1;>ProviderType = 2;
}
// Parse specified xmlString for values to populate the CspParams
// Expected XML schema:
//
//
//
//
//
// :void FromXmlString(String^ xmlString) override
{(xmlString != nullptr)
{^ document = gcnew XmlDocument();>LoadXml(xmlString);^ firstNode = document->FirstChild;^ nodeList;
// Assemble parameters from values in each XML element.= gcnew CspParameters();
// KeyContainerName is optional.= >GetElementsByTagName("KeyContainerName");(nodeList->Count > 0)
{>KeyContainerName =>Item(0)->InnerText;
}
// KeyNumber is optional.= document->GetElementsByTagName("KeyNumber");(nodeList->Count > 0)
{>KeyNumber =::Parse(nodeList->Item(0)->InnerText);
}
// ProviderName is optional.= document->GetElementsByTagName("ProviderName");(nodeList->Count > 0)
{>ProviderName =>Item(0)->InnerText;
}
// ProviderType is optional.= document->GetElementsByTagName("ProviderType");(nodeList->Count > 0)
{>ProviderType =::Parse(nodeList->Item(0)->InnerText);
}
}
{gcnew ArgumentNullException("xmlString");
}
}
// Create an XML string representation of the parameters in the
// current customCrypto object.:String^ ToXmlString(bool includePrivateParameters) override
{^ keyContainerName = "";^ keyNumber = "";^ providerName = "";^ providerType = "";(cryptoServiceParameters != nullptr)
{= >KeyContainerName;= cryptoServiceParameters->KeyNumber.ToString();= cryptoServiceParameters->ProviderName;= >ProviderType.ToString();
}^ sb = gcnew StringBuilder();>Append("ToString());
}
// Return the name for the key exchange algorithm.:String^ KeyExchangeAlgorithm
{String^ get() override
{"RSA-PKCS1-KeyEx";
}
}
// Retrieves the name of the signature alogrithm.:String^ SignatureAlgorithm
{String^ get() override
{"
}
}
// Required member for implementing the AsymmetricAlgorithm class.:~CustomCrypto()
{
}
// Call the Create method using the CustomCrypto assembly name.
// The create function attempts to create a CustomCrypto
// object using the assembly name. This functionality requires
// modification of the machine.config file. Add the following
// section to the configuration element and modify the values
// of the cryptoClass to reflect what isinstalled
// in your machines GAC.
//
//
//
//
// <cryptoClass CustomCrypto="Contoso.CustomCrypto,
// CustomCrypto,
// Culture=neutral,
// PublicKeyToken=fdb9f9c4851028bf,
// Version=1.0.1448.27640" />
//
// <nameEntry name="Contoso.CustomCrypto"
// class="CustomCrypto" />
//
//
//
//:CustomCrypto^ Create()
{Create("CustomCrypto");
}
// Create a CustomCrypto object by calling CrytoConfig's
// CreateFromName method and casting the type to CustomCrypto.
// The create function attempts to create a CustomCrypto object
// using the assembly name. This functionality requires
// modification of the machine.config file. Add the following
// section to the configuration element and modify the values
// of the cryptoClass to reflect what is installed
// in your machines GAC.
//
//
//
//
// <cryptoClass CustomCrypto="Contoso.CustomCrypto,
// CustomCrypto,
// Culture=neutral,
// PublicKeyToken=fdb9f9c4851028bf,
// Version=1.0.1448.27640" />
//
// <nameEntry name="Contoso.CustomCrypto"
// class="CustomCrypto" />
//
//
//
//:CustomCrypto^ Create(String^ algorithmName)
{(CustomCrypto^) ::CreateFromName(algorithmName);
}
};
}
Хэширование
В следующем примере кода показано, как вычислить хэш SHA1CryptoServiceProvider для массива. В этом примере предполагается существование предварительно определенного массива байтов dataArray[]. SHA1CryptoServiceProvider является производным классом HashAlgorithm.
Язык Visual C++
HashAlgorithm^ sha = gcnew SHA1CryptoServiceProvider;
arrayComputeHash( dataArray );
Заключение
класс криптографический framework шифрование
В данной работе были рассмотрены криптографические средства Microsoft .NET. Проведен обзор основных криптографических классо?/p>