encryption

xiaoxiao2021-03-06  53

Apply a hashtable in C # (Hashtable)

I. Brief introduction in .NET Framework, HashTable is a container provided by the System.Collections named space for processing and expressing key-value pairs like Key / Value, where KEY is usually available quickly, At the same time, Key is case sensitive; VALUE is used to store values ​​corresponding to Key. The key / value key value in HashTable is an Object type, so HashTable can support any type of Key / Value key value pair.

Second, the bricked table of the hash table adds a Key / Value key value in the hash table: HashTableObject.add (key, value); removes a Key / Value key value in the hash table: HashtableObject.remove Key); removes all elements from the hash table: HashTableObject.clear (); Judging whether the hash table contains a specific key Key: HashTableObject.contains (key); the following console will contain all the above operations: use system; using When using hashtable, you must introduce this namespace Class HashTable {public static void main () {uShtable HT = new hashtable (); // Create a HashTable instance HT.Add ("e", "e" ); // Add Key / Value key value to ht.add ("a", "a"); HT.Add ("c", "c"); ht.add ("b", "b"); String s = (string) HT ["a"]; if (HT.Contains ("e")) // Judging whether the hash table contains a specific key, its return value is true or false console.writeline ("The e key : exist "); ht.remove (" c "); // Remove a key / value key value to console.writeLine (HT [" A "]); // output a ht.clear (); / / Remove all Elements Console.Writeline (HT ["A"]); // will not have any output}} here

Third, traversing the hash table, traversing the hash table, you need to use the DictionaryEntry Object, the code is as follows: for (DictionaryTry de in HT) // HT is a HashTable instance {console.writeline (de.key); // de.key corresponds to Key / Value key value to key console.writeline (de.value); // de.key corresponds to the key / value key value pair value}

4. Sort the hash table to the hash table is defined here. The key to the key / value key value is rearranged, but in fact, this definition cannot be implemented, because we can't be directly HashTable makes a rearrangement of Key. If HashTable is required to provide an output of a certain rule, you can use a variation method: arraylist akeys = new arraylist (ht.keys); // Don't forget to import system.collections akeys.sort ); // Sort for in alphabetical order {Console.Write (SKEY ":"); console.writeLine (HT [SKEY]); // Sort Output} Hash (irreversible) encryption Universal class library function

Using system.io; using system.security.cryptography;

Namespace Common {///

/// copyright (c), 2004, kwklover (伟科) /// File name: Hasher.cs /// Author: Weikers Version: 1.0 Date: April 22, 2004 /// Description: Hash (irreversible) Encryption universal class library function ///

Public class haasher

{

Private byte [] _hashkey; // hash key storage variable

Private string_hashtext; // String to be encrypted

Public Hasher ()

{

//

// TODO: Add constructor logic here

//

}

///

/// has a hash key / / /

Public Byte [] HashKey

{

set

{

_Hashkey = value;

}

get

{

Return_hashkey;

}

}

///

/// Need to generate a stream of encrypted hash ///

Public String Hashtext

{

set

{

_Hashtext = value;

}

get

{

Return_hashtext;

}

}

///

/// Use the HMACSHA1 class to generate a hash sequence of a length of 20 bytes. The corresponding key is required to accept any size key. ///

///

Public String Hmacsha1Hasher ()

{

Byte [] hmackey = hashkey;

Byte [] hmacdata = system.text.encoding.utf8.getbytes (Hashtext);

Hmacsha1 hmac = new hmacsha1 (hmackey);

Cryptostream CS = New CryptostReam (stream.null, hmac, cryptostreammode.write); cs.write (hmacdata, 0, hmacdata.length); cs.close ();

Byte [] result = hmac.hash;

Return Convert.TOBASE64String (Result); // Return to 28 bytes of strings}

///

/// Use the MactriPLEDES class to generate a hash sequence with a length of 8 bytes. The corresponding key is required, the key length can be 8, 16 or 24 bytes of keys. ///

///

Public String Mactribledeshasher ()

{

BYTE [] Mackey = Hashkey;

Byte [] MacData = System.Text.encoding.utf8.getbytes (Hashtext);

Mactribledes Mac = New Mactripledes (Mackey); Byte [] Result = mac.computehash (MacData);

Return Convert.TOBASE64STRING (RESULT); // Return to 12 byte strings}

///

/// Use the MD5cryptoServiceProvider class to generate a hash value. No key is required. ///

///

Public String MD5HASHER ()

{

Byte [] md5data = system.text.Encoding.utf8.getbytes (Hashtext);

MD5 MD5 = New MD5CryptoserviceProvider ();

Byte [] result = md5.computehash (md5data);

Return Convert.TOBASE64String (Result); // Return to 25 bytes string}

///

/// Use the Sha1managed class to generate a length of 160-bit hash value. No key is required. ///

///

Public String Sha1ManagedHasher ()

{

Byte [] sha1data = system.text.Encoding.utf8.getbytes (Hashtext);

Sha1Managed Sha1 = New Sha1Managed ();

Byte [] result = sha1.computehash (sha1data);

Return Convert.TOBASE64String (Result); // Returns a string of 28 bytes}

///

/// Use the SHA256MANAGED class to generate a length of 256-bit hash. No key is required. ///

///

Public String Sha256ManagedHasher ()

{

Byte [] SHA256DATA = system.text.encoding.utf8.getbytes (Hashtext);

SHA256MANAGED SHA256 = New Sha256Managed ();

Byte [] result = sha256.computehash (sha256data);

Return Convert.TOBASE64String (Result); // Return the length of 44 bytes}

///

/// The length of 384-bit hash value is generated using the SHA384Managed class. No key is required. ///

///

Public String Sha384ManagedHasher ()

{

Byte [] sha384data = system.text.encoding.utf8.getbytes;

SHA384MANAGED SHA384 = New SHA384Managed ();

Byte [] result = sha384.computehash (SHA384DATA);

Return Convert.TOBASE64STRING (Result); // Returns a string of 64 bytes}

///

/// Use the SHA512MANAGED class to generate a length of 512-bit hash value. No key is required. ///

///

Public String Sha512ManagedHasher ()

{

Byte [] sha512data = system.text.Encoding.utf8.getbytes (Hashtext);

SHA512MANAGED SHA512 = New Sha512Managed ();

BYTE [] Result = sha512.computehash (sha512data);

Return Convert.TOBASE64String (Result); // Return the string of length 88 bytes}}}}}}

Symmetrical encryption decryption universal class library function Using system; use system.io; use means system.security.cryptography;

Namespace Common {///

/// Encryption Decryption Universal Class Function /// Copyright (C), 2004, Kwklover (伟科) /// File Name: Crypto.cs /// Author: Weike Version: 1.0 Date: April 21, 2004 / // Description: Reprincible general symmetric encryption decryption function set /////

PUBLIC CLASS CRYPTO {private swriting _crypttext; // Standby Variable Variables to be encrypted and decrypted Private Byte [] _CryptKey; // Encrypted Decryption private key variable private bote [] _cryptiv; // encrypted decryption initialization vector IV variable

///

/// The character sequence to be encrypted or decrypted /////

Public string crypttext {set {_crypttext = value;} get {return_crypttext;}}

///

/// Encryption private key ///

Public Byte [] CryptKey {set {_cryptkey = value;} get {return _cryptkey;}}

///

/// Encrypted initialization vector IV ///

Public Byte [] Cryptiv {set {_cryptiv = value;} get {return _cryptiv;}}

Public crypto () {// // Todo: Add constructor logic here //}

///

/// encryption function is used to encrypt the string. The corresponding key and IV are required. ///

///

Public string encrypt () {string strongText = crypttext; byte [] enkey = cryptkey; Byte [] ENIV =

Byte [] INPUTBYTEARRAY = System.Text.Encoding.utf8.getbytes (Strentext);

// You can also create additional decryption class instances, but pay attention to different (length) encryption classes require different key Key and initialization vector IV rijndaelmanaged rmcrypto = new rijndaelManaged ();

MemoryStream ms = new MemoryStream (); CryptoStream cs = new CryptoStream (ms, RMCrypto.CreateEncryptor (EnKey, EnIV), CryptoStreamMode.Write); cs.Write (inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock ();

Return Convert.TOBASE64STRING (ms.toarray ());}

///

/// Decryptive function is used to encrypt the encrypted character sequence. The corresponding key and IV are required. ///

///

PUBLIC STRING DECRYPT () {String strdExt = crypttext; Byte [] Dekey = cryptkey; byte [] deiv = cryptiv;

Byte [] INPUTBYTEARRING (STRDETEXT); // You can also create additional decryption class instances, but pay attention to different encryption classes require different (length) Key Key and initialization vector IV RijndaelManaged RMCrypto = New RijndaelManaged );

MemoryStream ms = new MemoryStream (); CryptoStream cs = new CryptoStream (ms, RMCrypto.CreateDecryptor (DeKey, DeIV), CryptoStreamMode.Write); cs.Write (inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock ();

Return System.Text.Encoding.utf8.getstring (ms.toarray ());}}} Some of the following data encrypted below, I can't summarize these data into valuable expression, I hope you don't worry. Enlightenment:

Admiral English letters, digital length range encrypted before Chinese characters long range encryption length size 0-150-52416-316-104432-4711-15648-6316-208864-7921-1510880-9516-3012896-1113-35152

RSA Encrypts Data Errors Being out of 117 bytes

The previous array of public security bureaus is used to use public key encryption technology and symmetric key encryption technology. The information is encrypted by 3DES, and the key is transmitted through the RSA public key system. The client is decrypted using the CPU card ekey. However, in the system writing process, the RSA encryption algorithm in .NET adds some random numbers to be added before the data is ready to be encrypted, so the RSA encryption algorithm in the .NET encrypted 117 bytes (more The 117-byte needs to be split into a plurality of segments, encrypted and then connected, and after encryption, obtain a length of 128 bytes of encrypted data. However, this will bring a lot of trouble for the public key system that needs to be confirmed by the identity of both parties. In my system, I need to implement online encryption of the user session key by following the steps:

Encryption process: 1. Add a random number to the session key, add 128 bits, 2, use the CA private key to decrypt, the result is 128-bit data, 3, encrypt the data using the user public key to obtain 128-bit data, transmitted over the network .

Decryption process: 1. Use the user private key to decrypt the 128-bit data transferred on the online transfer; 2. Use the CA public key encryption; 3, remove the random number used to confuse, extract the session key

However, the RSA encryption in .NET can only operate 117 bytes of data, resulting in 128-bit data to process two parts, so encrypted data constantly expands. In order to solve this problem, the RSA encryption, the decryption process is consistent with the process on the EKEY, I have to write my own RSA encryption algorithm.

After finding a lot of information, I decided to use the ready-made Biginteger class. You can get more information about http://www.codeproject.com/csharp/biginteger.asp. With Biginteger, I added two ways RSAENCRYPT and RSADECrypt to implement RSA encryption decryption. This will never be limited by 117 bytes.

The two sections are given, and the program first is to use .NET comes with the RSA encryption algorithm to achieve encrypted decryption, once the TextLength property exceeds 117, the system will not be encrypted; the second is the transformed system, and 128-bit data can be performed. Encryption, no restrictions on 117. The program is omitted by the Biginteger class. If you need it, you can download it from http://www.codeger.asp, don't forget to comment the main method, otherwise there is a compilation error when compiling, saying two An entry point (of course, you can also specify an entry point in the project properties). Program 1:

Using

System;

Using

System.security.cryptography;

Using

System.Text;

Class

Oldrsa

...

{Static void Main () ... {int TextLength = 117; byte [] encryptedData; byte [] decryptedData; string Key1 = " 4n6EJsx4qNFpp6h wcPdJz8sSMMRJEVJaBQEGsOOBHKNePo / v3M94Nf89 zL5lLH7 / LuRgcUfnizVIETH / z9 H / yDuM0F3fjImN3UtK1TK0ioFf0cVC9lnErbEoEjmkeQIVUJUC4c BmqtTN6UrhFCY3R3zGp3feeGqORLjeKVc = AQAB

7w2qsVRBn168Ehc4V / fiPML 7WUkORRIJ9I8i21Fs5GlvYrja2CzBzPLKrAHumLOCLgd / qKj0iApF17471nfKw == 8oztAlInRK1VDuVLHnPPcNQsehbP9IF5p kwRu07sFGwAHnyeWuRG0EpebvbGOE / 1KzpKqb / WU8vSN4OeauohQ == DIh 5oUwW5av7ZLiFVqdtenTS8b9uzBhCBVxry2vddaxBdr SWbse / gvMrG / 9fmwK6zbhbopNJ8TCHKmQoZHuQ == 6g96q / GxeUG3Qk dBP8HIL9vSEX5Wd8UEigicV9 / aS / 7IwqLJgbama1xI8tXrBO6MDbIL2PGKF4UqEG5QEqZrQ == nyx28u1fREiIgXgx2S5 PXbB8wq0xVxnE2G2Mt0vq9xQDHbaXEFpfznjNaga8AhVluNahqG5uRGRY3OgQONO4g == PVKj1R1nTc3lHU XGitvq9QE0TR9V6RCY7SFOV9XBCM / YPF20Q8SOD3Y0AD87U9ccssdwfjyagukai0wugjfgfalf8 / 4pfwqzrgblsn96klmklmy7c6oihlriw myxmvaggsp3 / r4se6wgk5 ISchjKIKyv / PyWoobDRe6orDzIE = "; try ... {RSACryptoServiceProvider RSA = new RSACryptoServiceProvider (); RSA.FromXmlString (Key1); byte [] dataToEncrypt = GenerateBytes (TextLength); Console.WriteLine (" Original buff: " Convert.ToBase64String (dataToEncrypt) " "); encryptedData = RSA.Encrypt (dataToEncrypt, false); Console.WriteLine (" Encrypted buff: " Convert.ToBase64String (encryptedData) "

"); DecryptedData = RSA.Decrypt (encryptedData, false); Console.WriteLine (" Decrypted buff: " Convert.ToBase64String (decryptedData) " ");} catch ... {Console.WriteLine (" Encryption failed. " );}} // ************************************************************ ************************************************************************************* *********************************************************** *********** Public static Byte [] generatebytes (int Bytelength) ... {byte [] buff = new byte [bytelength]; rngcryptoserviceProvider RNG = new RNGCRYPTOSERVICEPROVIDER (); // This array has been used Password enhanced random bytes fill RNG.GetBytes (buff); Return BUFF;}} 2:

Using

System;

Using

System.security.cryptography;

Using

System.Text;

Class

NewRSA

...

{Public static void Main () ... {int TextLength = 128; byte [] encryptedData; byte [] decryptedData; string Key1 = " 4n6EJsx4qNFpp6h wcPdJz8sSMMRJEVJaBQEGsOOBHKNePo / v3M94Nf89 zL5lLH7 / LuRgcUfnizVIETH / z9 H / yDuM0F3fjImN3UtK1TK0ioFf0cVC9lnErbEoEjmkeQIVUJUC4c BmqtTN6UrhFCY3R3zGp3feeGqORLjeKVc = AQAB

7w2qsVRBn168Ehc4V / fiPML 7WUkORRIJ9I8i21Fs5GlvYrja2CzBzPLKrAHumLOCLgd / qKj0iApF17471nfKw == 8oztAlInRK1VDuVLHnPPcNQsehbP9IF5p kwRu07sFGwAHnyeWuRG0EpebvbGOE / 1KzpKqb / WU8vSN4OeauohQ == DIh 5oUwW5av7ZLiFVqdtenTS8b9uzBhCBVxry2vddaxBdr SWbse / gvMrG / 9fmwK6zbhbopNJ8TCHKmQoZHuQ == 6g96q / GxeUG3Qk dBP8HIL9vSEX5Wd8UEigicV9 / aS / 7IwqLJgbama1xI8tXrBO6MDbIL2PGKF4UqEG5QEqZrQ == nyx28u1fREiIgXgx2S5 PXbB8wq0xVxnE2G2Mt0vq9xQDHbaXEFpfznjNaga8AhVluNahqG5uRGRY3OgQONO4g == PVKj1R1nTc3lHU XGitvq9QE0TR9V6RCY7SFOV9XBCM / YPF20Q8SOD3Y0AD87U9ccssdwfjyagukai0wugjfgfalf8 / 4pfwqzrgblsn96klmklmy7c6oihlriw myxmvagssp3 / r4 sE6wGk5ISchjKIKyv / PyWoobDRe6orDzIE = "; try ... {RSACryptoServiceProvider RSA = new RSACryptoServiceProvider (); RSA.FromXmlString (Key1); RSAParameters RSAKeyInfo = RSA.ExportParameters (true); byte [] dataToEncrypt = GenerateBytes ("Original Buff:" Convert.TOBASE64STRING (DataToEncrypt) ""); EncryptedData = RSAENCrypt (DatatoEncrypt, RsakeyInfo.exponent, RsakeyInfo.modulus);

Console.WriteLine ( "Encrypted buff:" Convert.ToBase64String (encryptedData) ""); decryptedData = RSADecrypt (encryptedData, RSAKeyInfo.D, RSAKeyInfo.Modulus); Console.WriteLine ( "Decrypted buff:" Convert.ToBase64String ( DecryptedData) "");} catch ... {console.writeline ("Encryption failed.");}} // ****************************** ********************************************************* / / Rsa encrypt // ************************************************************* ******************************************** Static public Byte [] rTE [] DataToencrypt, Byte [] Exponent, Byte [] MODULUS) .. . {BigInteger original = new BigInteger (dataToEncrypt); BigInteger e = new BigInteger (Exponent); BigInteger n = new BigInteger (Modulus); BigInteger encrypted = original.modPow (e, n); return HexStringToByte (encrypted.ToHexString ()) } // ************************************************************* *********************** // RSA Decrypt // *************************** ********** ************************************************************** Static Public Byte [] RSADecrypt ( byte [] encryptedData, byte [] D, byte [] Modulus) ... {BigInteger encrypted = new BigInteger (encryptedData); BigInteger d = new BigInteger (D); BigInteger n = new BigInteger (Modulus); BigInteger decrypted = encrypted .MODPOW (D, N); Return HEXSTRINGTOBYTE (Decrypted.toHexString ());

转载请注明原文地址:https://www.9cbs.com/read-116836.html

New Post(0)