Encryption technology in C #

xiaoxiao2021-03-06  19

Several symmetric encryption algorithms have been integrated in .NET, they can build their own encryption programs soon.

Class used to encrypt in .NET

tabindex = "0" keywords = "frlrfSystemSecurityCryptographyDESCryptoServiceProviderClassTopic" /> DESCryptoServiceProvider tabindex = "0" keywords = "frlrfSystemSecurityCryptographyRC2CryptoServiceProviderClassTopic" /> RC2CryptoServiceProvider tabindex = "0" keywords = "frlrfSystemSecurityCryptographyRijndaelManagedClassTopic" /> RijndaelManaged tabindex = "0" keywords = "frlrfSystemSecurityCryptographyTripleDESCryptoServiceProviderClassTopic" / > TripleDescryptoServiceProvider The following is the encrypted program I have built to note that each encryption algorithm is different for the length of the key and the initial vector, the encryption class is used system; use system.security.cryptography; namespace encryption {/// < summary> /// conversion decryption /// public class DecryptTransformer {internal DecryptTransformer (EncryptionAlgorithm deCryptId) {algorithmID = deCryptId;} private EncryptionAlgorithm algorithmID; private byte [] initVec; internal byte [] IV {set {this. INITVEC = value;}}} ///

/// Define basic encryption conversion calculation /// /// key /// internal ICryptoTransform GetCryptoServiceProvider (byte [] bytesKey) {switch (algorithmID) {case EncryptionAlgorithm.Des: {DES des = new DESCryptoServiceProvider (); des.Mode = CipherMode.CBC; des.Key = bytesKey; des .IV = initVec; return des.CreateDecryptor ();} case EncryptionAlgorithm.TripleDes: {TripleDES des3 = new TripleDESCryptoServiceProvider (); des3.Mode = CipherMode.CBC; // return a symmetric decryptor return des3.CreateDecryptor (bytesKey, initVec) ;

} Case EncryptionAlgorithm.Rc2: {RC2 rc2 = new RC2CryptoServiceProvider (); rc2.Mode = CipherMode.CBC; return rc2.CreateDecryptor (bytesKey, initVec);} case EncryptionAlgorithm.Rijndael: {Rijndael rijndael = new RijndaelManaged (); rijndael. Mode = CipherMode.CBC; return rijndael.CreateDecryptor (bytesKey, initVec);} default: {throw new CryptographicException ( "Algorithm ID '" algorithmID "' not supported");}}}}} using System; using System.Security .Cryptography; Namespace Encryption {///

/// One enumeration /// public enum encryptionalgorithm {des = 1, RC2, Rijndael, TripleDes}; /// /// setting encryption algorithm /// internal class EncryptTransformer {public EncryptTransformer (EncryptionAlgorithm algId) {algorithmID = algId;} private EncryptionAlgorithm algorithmID; private byte [] initVec; private byte [] encKey; internal byte [] IV {get {return THIS.INITVEC;} set {this.initvec = value;}} Internal Byt e [] key {get {return this.enckey;}} /// /// created a cryptometer (encryption conversion) /// /// secret Key /// INTERNALVICEPTOTRANSFORM GETCRYPTOSERVICEPROVIDER (Byte [] byteskey) {// The following variable algorithm based on the line of different encryption algorithms {CASE Encryptionalgorithm.des: {DES DES = new descryptoserviceProvider (); des.mode = cophermode.cbc; // below the key IF of the DES algorithm (null == byteskey) {eNCKEY = des.key;} else {des.key = byteskey; Enckey = des. KY;

} // The following settings The initialization vector if (null == initVec) {INITVEC = des.iv;} else {des.iv = initVec;} // Return a cryptometer Return DES.CREATEENCRYPTOR ();} Case EncryptionAlgorithm.tripledes: {TripLeDes Des3 = New TripleDescryptoServiceProvider (); des3.mode = cophermode.cbc; // Setting key IF (null == byteskey) {eLse = des3.key;} else {des3.key = byteskey; this.enckey = des3 K} // Setting the initialization vector if (null == initVec) {initVec = des3.IV;} else {des3.IV = initVec;} // Return the encrypler Return des3.createEncryptor ();} case encryptionalgorithm.RC2 : {// Initialization Encryption Service RC2 RC2 = New RC2cryptoserviceProvider (); rc2.mode = cophermode.cbc; // Setting Key IF (NULL == Byteskey) {eNCKEY = RC2.Key;} else {rc2.key = byteskey This.Enckey = rc2.key;} // Set the initialization vector if (null == initVec) {initVec = rc2.iv;} else {rc2.iv = initVec;} // Return to the encryprators return Return rc2.CreateEncryptor ();} case EncryptionAlgorithm.Rijndael: {Rijndael rijndael = new RijndaelManaged (); rijndael.Mode = CipherMode.CBC; // key set if (null == bytesKey) {encKey = rijndael.Key;} else {Rijndael.key = byteskey; this.Enckey = rijndael.key;} // sets the initialization vector if (null == initVec) {initVec = rijndael.iv;} else {rijndael.iv = initVec;} // Return Enterprise Return rijndael.createEncryptor ();} default: {throw new cryptographicException ("Algorithm ID '" Algorithmid "'

NOT Supported. ");}}}}}}}}}}}}}}}} Using system; use system.io; use system.security.cryptography; namespace encryption {///

/// Used to decrypt data /// public class Decryptor {public Decryptor (EncryptionAlgorithm algId) {this.transformer = new DecryptTransformer (algId);} private DecryptTransformer transformer; private byte [] initVec; public byte [] IV {set {this.initVec = value;}} /// /// Decryption data /// /// Decouveling data /// key /// public byte [] Decrypt (byte [] bytesData, byte [] bytesKey) {MemoryStream memStreamDecryptedData = new MemoryStream (); transformer.IV = initVec; ICryptoTransform transform = transformer.GetCryptoServiceProvider (bytesKey ); CryptoStream decStream = new CryptoStream (memStreamDecryptedData, transform, CryptoStreamMode.Write); try {decStream.Write (bytesData, 0, bytesData.Length);} catch (Exception ex) {t hrow new Exception ( "Error while writing encrypted data to the stream: / n" ex.Message);} decStream.FlushFinalBlock (); decStream.Close (); return memStreamDecryptedData.ToArray ();}}} using System; using System.IO; using System.Security.Cryptography; namespace encryption {/// /// is used to encrypt the data /// public class Encryptor {public Encryptor (EncryptionAlgorithm algId) {this.transformer = new Encrypttransformer (algid); private encrypttransformer transformer; private bote [] initVec; private bote [] eNCKEY; /// /// The initial vector is used to avoid the repetition part of the file to prevent the decryption ///

Public Byte [] iv {get {Return INITVEC;}}} public byte [] key {get {return enckey;}} ///

/// {加 加 /// < / summary> /// To encrypt data /// key /// After encrypted data public byte [] Encrypt (byte [] bytesData, byte [] bytesKey) {MemoryStream memStreamEncryptedData = new MemoryStream (); transformer.IV = initVec; ICryptoTransform transform = transformer.GetCryptoServiceProvider (bytesKey); CryptoStream encStream = new CryptoStream (memStreamEncryptedData, transform, CryptoStreamMode.Write); try {encStream.Write (bytesData, 0, bytesData.Length);} catch (Exception ex) {throw new Exception ( "Error while writing encrypted data to the stream: / n" ex.Message);} encKey = transformer.Key; initVec = transformer.IV; encStream.FlushFinalBlock (); encStream.Close (); return memStreamEncryptedData.ToArray ();}}} using System; using System.IO; using System .Security.cryptogras PHY; Namespace Encryption {/// /// file decryption class /// public class filedeptor {/// /// Initialization a file decryption class /// / // EncryptionAlgorithm enumerator for determining the encryption algorithm public FileDecryptor (EncryptionAlgorithm algId) {this.transformer = new DecryptTransformer (algId);} private DecryptTransformer transformer; private byte [] initVec ; // Initialization vector /// /// initialization vector, initialize /// public byte []}} {initVec = value;}} / // /// Decryption file /// <

/ summary> /// Deciplive file path /// Output file path /// password /// public bool DecryptFile (String inName, String outName, byte [] bytesKey) {FileStream fin = new FileStream (inName, FileMode.Open, FileAccess.Read); // the input filestream FileStream fout = new FileStream (outName, FileMode.OpenOrCreate, FileAccess.Write); // the output filestream fout.SetLength (0); // set the length of the output filestream for initalization byte [] bin = New byte [100]; // this is interface for the encryption. Long rdlen = 0; // this is the total number of bytes Written. Long Totlen = FIN.LENGTH; // this is The Total Length of the Input File of THE INPUT FILE . int len; // This is the number of bytes to be written at a time transformer.IV = initVec;. // initialization vector of the decrypted class set ICryptoTransform transform = transformer.GetCryptoServiceProvider (bytesKey); CryptoStream encStream = new CryptoSt Ream (Fout, Transform, Cryptostreammode.Write); Console.WriteLine ("Decrypting ..."); while (rdlen /// 加 文件 文件 文件 /// Public CLASS FileEncryptor {///

/// Construct a file encryption class /// an enumeration, used to define encryption methods public fileEncryptor (encryptionalgorithm algid) {this.transformer = New encrypttransformer (algid);} private encrypttransformer transformer; private botte [] initVec; private bote [] enckey; ///

/// The initial vector is used to avoid the repetition part of the file to prevent being decrypted /// public Byte []} set {{return = value;}} public byte [] key {get {return enckey;}} /// /// is used to encrypt a file / // /// To encrypted file path /// Encrypted data save path /// < param name = "bytesKey"> key /// public bool EncryptFile (String inName, String outName, byte [] bytesKey) {FileStream fin = new FileStream (inName, FileMode.Open , FileAccess.read; // The Input FileStream FileStream Fout = New FileStream (Outname, Filemode.Openorcreate, FileAccess.write); // The Output FileStream Fout.setLength (0); // SET THE L ength of the output filestream for initalization byte [] bin = new byte [100]; // This is intermediate storage for the encryption long rdlen = 0;. // This is the total number of bytes written long totlen = fin.Length. ; // This is the total length of the input file int len;. // This is the number of bytes to be written at a time transformer.IV = initVec;. ICryptoTransform transform = transformer.GetCryptoServiceProvider (bytesKey); encKey = transformer KY;

// if you do not give a key then will create a key automaticlly CryptoStream encStream = new CryptoStream (fout, transform, CryptoStreamMode.Write); Console.WriteLine ( "Encrypting ..."); while (rdlen /// Class1. /// class class1 {///

/// The primary entry point of the application.

/// [stathread] static void main (String [] args) {message ("This is a program that encrypts and decrypts, using symmetric encryption technology, uses DES, 3DES, RS2, RIJNDAEL encryption algorithm!" ); Message ("follow the prompts to complete the operation! (Note that the length of the key and the initial vector"); Message ("@ 2005 ---- Pan Weifeng"); int action = 0; string infile = Null; string outfile = null; string password = null; string IV = null; int encryptedMethod = 0; byte [] key = null; byte [] IV = null; if (args.length == 4) {action = convert. TOINT32 (Args [0] .trim ()); infile = args [1]; outfile = args [2]; password = args [3]; EncryptedMethod = Convert.Toint32 (Args [4] .trim ());} While (action == 0 || infile == null || outfile == null || PASSWORD == NULL || iv == null || encryptedMethod == 0) {if (action == 0) {Console.WriteLine "Please select an action"); console.writeline ("1. Encrypted a file"); console.writeline ("2. Decrypt a file"); action = convert.Toint32 (console.readline (). Trim ()) } If (infile == null) {if (action == 1) {console.writeline ("Please enter the file path you want to encrypted");} if (action == 2) {Console.WriteLine ("Please enter You have to decrypt the file path "); } Infile = console.readline (). Trim (); fileinfo f = new fileInfo (infile); if (! F.exists) {console.writeline ("file does not exist"); infile = null; continue;}}} (outfile == null) {if (action == 1) {console.writeLine ("Please enter the encrypted file storage path");} if (action == 2) {console.writeLine ("Please enter the decrypted file Storage path ");} outfile = console.readline (). Trim ();} if (encryptedMethod ==

0) {Console.Writeline ("Please select an encryption algorithm:"); console.writeline ("1.des"); console.writeLine ("2.RC2"); console.writeLine ("3.rijndael"); Console.writeline ("4.tripledes"); EncryptedMethod = Convert.Toint32 (). Trim ());} if (password == null) {Console.WriteLine ("Please enter your password:"); showRightKeysize (EncryptedMethod); Password = console.readline (). Trim ();} if (iv == null) {Console.Writeline ("Please enter the initial vector:"); console.writeline ("Note: The initial vector must correct "); ShowRightIVSize (encryptedmethod); iv = Console.ReadLine () Trim ();}} // choose a Encrypted Mehod EncryptionAlgorithm algorithm; switch (encryptedmethod) {case 1:. {algorithm = EncryptionAlgorithm.Des; break;} case 2: {algorithm = EncryptionAlgorithm.Rc2; break;} case 3: {algorithm = EncryptionAlgorithm.Rijndael; break;} case 4: {algorithm = EncryptionAlgorithm.TripleDes; break;} default: {algorithm = Encrypt Ionalgorithm.des; break;}} iv = encoding.ascii.getbytes (iv); key = encoding.ascii.getBytes (password); if (action == 1) {FileEncryptor Fe = New FileEncryptor (algorithm); // define A New FileEncryptor Acording to the EncryptorMethod Fe.IV = IV; IF (Fe.EncryptFile (Infile, Outfile, Key)) {Console.WriteLine ("Encryption Success"); console.readline ();}} f (action == 2) {FileDecryptor FD = New FileDecryptor (Algorithm); fd.iv = iv; if (fd.decryptfile (infile, outfile, key)) {console.writeline ("Decryption success"); console.readline ();

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

New Post(0)