public RAOPClient( string Host ) { host = Host; volume = VOLUME_DEF; ajstatus = JACK_STATUS_DISCONNECTED; ajtype = JACK_TYPE_ANALOG; nfi = new CultureInfo( "en-US" ).NumberFormat; alg = Rijndael.Create(); alg.Mode = CipherMode.CBC; alg.Padding = PaddingMode.None; alg.KeySize = 128; alg.GenerateKey(); alg.GenerateIV(); int i = host.LastIndexOf( '.' ); string hostnet = host.Substring( 0, i ); IPHostEntry iphe = Dns.GetHostEntry(Dns.GetHostName());//Dns.GetHostByName( Dns.GetHostName() ); foreach( IPAddress ipaddr in iphe.AddressList ) { string s = ipaddr.ToString(); if( s.StartsWith( hostnet ) ) { local = s; break; } } if( local == null ) local = Host; }
private static byte[] RijndaelEncryption(byte[] input, byte[] key, bool encrypt, bool parallel = true) { var algorithm = new Rijndael(); int InputBlockLen_byte = algorithm.InputBlockLen_bit/8; byte[] expandedkey = algorithm.ExpandKey(key); if (input.Length > 0 && key.Length > 0) { int countblocks; byte[] output; if (encrypt) { int bytestoadd = (InputBlockLen_byte - (input.Length + 1)%InputBlockLen_byte)%InputBlockLen_byte; int newinputlen = input.Length + bytestoadd + 1; Array.Resize(ref input, newinputlen); input[input.Length - 1] = (byte) bytestoadd; countblocks = newinputlen/InputBlockLen_byte; output = new byte[newinputlen]; } else { countblocks = input.Length/InputBlockLen_byte; output = new byte[input.Length]; } if (parallel) { Parallel.For(0, countblocks, delegate(int b) { var block = new byte[InputBlockLen_byte]; Buffer.BlockCopy(input, b*InputBlockLen_byte, block, 0, InputBlockLen_byte); block = encrypt ? algorithm.EncryptBlock(block, expandedkey) : algorithm.DecryptBlock(block, expandedkey); Buffer.BlockCopy(block, 0, output, b*InputBlockLen_byte, InputBlockLen_byte); }); } else { var block = new byte[InputBlockLen_byte]; for (int b = 0; b < countblocks; b++) { Buffer.BlockCopy(input, b*InputBlockLen_byte, block, 0, InputBlockLen_byte); block = encrypt ? algorithm.EncryptBlock(block, expandedkey) : algorithm.DecryptBlock(block, expandedkey); Buffer.BlockCopy(block, 0, output, b*InputBlockLen_byte, InputBlockLen_byte); } } if (!encrypt) { int countbytestoerase = output[output.Length - 1] + 1; int newoutputlenght = output.Length - countbytestoerase; Array.Resize(ref output, newoutputlenght); } return output; } return null; }
private static void VerifyEncrypt(NistKnownAnswerTestVector vector) { var rijndael = new Rijndael(vector.Key); int feedbackSize = vector.BitLength < 128 ? 8 : vector.BitLength; var transform = RijndaelEncryptionTransformFactory.Create(rijndael, vector.CipherMode, vector.IV, feedbackSize, PaddingMode.None); byte[] output = transform.TransformFinalBlock(vector.Plaintext, 0, vector.Plaintext.Length); AssertBytesEqual(vector.Ciphertext, output, vector.BitLength); }
private void buttonStartClick(object sender, EventArgs e) { if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) { Thread thread = new Thread(new ThreadStart(delegate { buttonStartClick(sender, e); })); thread.IsBackground = true; thread.Start(); return; } Rijndael aes = new Rijndael(Tools.StringToBytes(textBoxKey.Text)); Stream messageFile = new PKCSPaddedStream(aes, new FileStream(labelMessage.Text, FileMode.OpenOrCreate)), cipherFile = new FileStream(labelCipher.Text, FileMode.OpenOrCreate); IBlockCipherMode blockMode = null; if (radioButtonCFB.Checked) blockMode = new CipherFeedback(aes, Tools.StringToBytes(textBoxIv.Text)); else if (radioButtonCTR.Checked) blockMode = new SegmentedIntegerCounter(aes, Tools.StringToBytes(textBoxIv.Text)); else if (radioButtonECB.Checked) blockMode = new ElectronicCodeBook(aes); else if (radioButtonCBC.Checked) blockMode = new CipherBlockChaining(aes, Tools.StringToBytes(textBoxIv.Text)); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); long bytes; if (radioButtonEncrypt.Checked) { bytes = messageFile.Length; blockMode.Encrypt(messageFile, cipherFile); } else { bytes = cipherFile.Length; blockMode.Decrypt(cipherFile, messageFile); } stopwatch.Stop(); Console.WriteLine(stopwatch.Elapsed + " (" + (stopwatch.Elapsed.Ticks / bytes) + " ticks/byte)"); MessageBox.Show("Cryption done!", stopwatch.Elapsed + " (" + (stopwatch.Elapsed.Ticks / bytes) + " ticks/byte)"); messageFile.Close(); cipherFile.Close(); }
/// <summary> /// Metoto de lcase encargado de descifrar un string de forma cimetrica /// </summary> /// <param name="encryptedMessage"></param> /// <param name="Key"></param> /// <param name="IV"></param> /// <returns></returns> public string DecryptString(string TextPlain, string Key, string IV) { if (String.IsNullOrEmpty(TextPlain)) { return(null); } byte[] Keya = null; byte[] Iva = null; Keya = Encoding.UTF8.GetBytes(Key); Array.Resize(ref Keya, KEYSIZE); Iva = Encoding.UTF8.GetBytes(IV); Array.Resize(ref Iva, IVSIZE); MemoryStream memoryStream = null; CryptoStream cryptoStream = null; try { byte[] cipherTextBytes = Convert.FromBase64String(TextPlain); byte[] plainTextBytes = new byte[cipherTextBytes.Length]; Rijndael RijndaelAlg = Rijndael.Create(); memoryStream = new MemoryStream(cipherTextBytes); cryptoStream = new CryptoStream(memoryStream, RijndaelAlg.CreateDecryptor(Keya, Iva), CryptoStreamMode.Read); int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); return(Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)); } finally { if (cryptoStream != null) { cryptoStream.Close(); } } }
/// <summary> /// Encrypt a given string using the given key. The cipherText is Base64 /// encoded and returned. The algorithjm currently used is "Rijndael" /// </summary> /// <param name="clearString">The string to encrypt.</param> /// <param name="keyBytes">The key for the encryption algorithm</param> /// <returns>The Base64 encoded cipher text</returns> public static String EncryptString(String clearString, byte[] keyBytes) { MemoryStream ms = new MemoryStream(); //DES alg = DES.Create(); //RC2 alg = RC2.Create(); Rijndael alg = Rijndael.Create(); alg.Key = keyBytes; alg.IV = GetSalt(); byte[] clearBytes = Encoding.Unicode.GetBytes(clearString); CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); byte[] cipherText = ms.ToArray(); return(Convert.ToBase64String(cipherText)); }
public static string UnAesStr(this string source, string keyVal, string ivVal) { string str; Encoding encoding = Encoding.UTF8; byte[] rgbKey = keyVal.FormatByte(encoding); byte[] rgbIV = ivVal.FormatByte(encoding); byte[] buffer = Convert.FromBase64String(source); Rijndael rijndael = Rijndael.Create(); using (MemoryStream stream = new MemoryStream()) { using (CryptoStream stream2 = new CryptoStream(stream, rijndael.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write)) { stream2.Write(buffer, 0, buffer.Length); stream2.FlushFinalBlock(); str = encoding.GetString(stream.ToArray()); } } rijndael.Clear(); return(str); }
private static void PerformRandomizedTest(CipherMode mode, PaddingMode padding, int keySize) { var aesCapi = new AesCryptoServiceProvider(); aesCapi.Mode = mode; aesCapi.Padding = padding; aesCapi.Key = ByteUtilities.GetCryptographicallyRandomBytes(keySize/Constants.BitsPerByte); aesCapi.IV = ByteUtilities.GetCryptographicallyRandomBytes(128/Constants.BitsPerByte); var capiEncryptionTransform = aesCapi.CreateEncryptor(); var ours = new Rijndael(aesCapi.Key); var ourEncryptionTransform = ours.CreateEncryptor(aesCapi.Mode, aesCapi.IV, aesCapi.FeedbackSize, aesCapi.Padding); byte[] encryptedResult = PerformRandomizedTest(capiEncryptionTransform, ourEncryptionTransform, null); var capiDecryptionTransform = aesCapi.CreateDecryptor(); var ourDecryptionTransform = ours.CreateDecryptor(aesCapi.Mode, aesCapi.IV, aesCapi.FeedbackSize, aesCapi.Padding); byte[] decryptedResult = PerformRandomizedTest(capiDecryptionTransform, ourDecryptionTransform, encryptedResult); }
/// <summary> /// Decrypt a file into another file using a password. /// </summary> /// <param name="fileIn">Input file.</param> /// <param name="fileOut">Output file.</param> /// <param name="password">The password used in the decryptation.</param> public static void Decrypt(string fileIn, string fileOut, string password) { // First we are going to open the file streams FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read); FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write); // Then we are going to derive a Key and an IV from the Password and create an algorithm PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); Rijndael alg = Rijndael.Create(); alg.Key = pdb.GetBytes(32); alg.IV = pdb.GetBytes(16); // Now create a crypto stream through which we are going to be pumping data. // Our fileOut is going to be receiving the Decrypted bytes. CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), CryptoStreamMode.Write); // Now will will initialize a buffer and will be processing the input file in chunks. // This is done to avoid reading the whole file (which can be huge) into memory. int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int bytesRead; do { // read a chunk of data from the input file bytesRead = fsIn.Read(buffer, 0, bufferLen); // Decrypt it cs.Write(buffer, 0, bytesRead); } while (bytesRead != 0); // close everything cs.Close(); // this will also close the unrelying fsOut stream fsIn.Close(); }
/// <summary> /// AES Rijndael ile Şifreleme /// </summary> /// <param name="veri">AES ile şifrelenecek veri</param> /// <param name="key">Anahtar</param> /// <param name="iv">Initialization vector (Başlatma Vektörü)</param> /// <returns>AES ile şifrelenmiş veriyi döndürür</returns> internal static byte[] SifreleAes(byte[] veri, byte[] key, byte[] iv) { byte[] cikti; using (MemoryStream ms = new MemoryStream()) using (Rijndael aes = Rijndael.Create()) { aes.BlockSize = AesBlockSize; aes.KeySize = AesKeySize; aes.Mode = AesMode; aes.Padding = AesPadding; aes.Key = key; // GetBytes(aes.KeySize / 8) aes.IV = iv; // GetBytes(aes.BlockSize / 8) using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(veri, 0, veri.Length); cs.FlushFinalBlock(); } cikti = ms.ToArray(); } return(cikti); }
byte[] AESDec(byte[] encrypted, byte[] Key, byte[] IV) { byte[] plain; using (Rijndael rijAlg = Rijndael.Create()) { rijAlg.Key = Key; rijAlg.IV = IV; ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); using (MemoryStream msDecrypt = new MemoryStream(encrypted)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { string sf = srDecrypt.ReadToEnd(); plain = Encoding.UTF8.GetBytes(sf); } } } } return(plain); }
//Con este método usamos el mensaje cifrado y la clave introducida para descirar el mensaje public static String DescifrarTexto(byte[] entrada, byte[] clave) { // Instanciamos el Rijndael Rijndael cifradoRijn = Rijndael.Create(); // Inicializamos un array temporal con la longitud del vector de inicialización byte[] arrayTemporal = new byte[cifradoRijn.IV.Length]; // Inicializamos un array que tendrá la longitud del mensaje encriptado byte[] encriptado = new byte[entrada.Length - cifradoRijn.IV.Length]; String textodescifrado = String.Empty; try { // Asignamos la clave cifradoRijn.Key = clave; // Copiamos en el array temporal el vector de inicialización Array.Copy(entrada, arrayTemporal, arrayTemporal.Length); // Copiamos el mensaje sin el vector de inicialización en un array Array.Copy(entrada, arrayTemporal.Length, encriptado, 0, encriptado.Length); // Asignamos el vector de inicialización cifradoRijn.IV = arrayTemporal; // Desencriptamos el mensaje byte[] prueba = cifradoRijn.CreateDecryptor().TransformFinalBlock(encriptado, 0, encriptado.Length); // Convertimos el mensaje descifrado a String textodescifrado = Encoding.UTF8.GetString(prueba); } catch (Exception ex) { throw new Exception(ex.Message); } finally { // Limpiamos el Rijndael cifradoRijn.Dispose(); cifradoRijn.Clear(); } // Devolvemos el mensaje descifrado return(textodescifrado); }
private static Rijndael CriarInstanciaRijndael(string chave, string vetorInicializacao) { if (!(chave != null && (chave.Length == 16 || chave.Length == 24 || chave.Length == 32))) { throw new Exception("A chave de criptografia deve possuir 16, 24 ou 32 caracteres."); } if (vetorInicializacao == null || vetorInicializacao.Length != 16) { throw new Exception("O vetor de inicialização deve possuir 16 caracteres."); } Rijndael algoritmo = Rijndael.Create(); algoritmo.Key = Encoding.ASCII.GetBytes(chave); algoritmo.IV = Encoding.ASCII.GetBytes(vetorInicializacao); return(algoritmo); }
/// <summary> /// Saves state of instance of T into file via encryption. /// </summary> public override bool Save(string key, object obj) { Debug.Log(_filePath); using (var aes = Rijndael.Create()) { aes.Key = GenerateEncryptionKey(key); aes.GenerateIV(); using (FileStream fileStream = new FileStream(_filePath, FileMode.Create)) { using (CryptoStream cryptoStream = new CryptoStream(fileStream, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write)) { fileStream.Write(aes.IV, 0, aes.IV.Length); // Prepend initialization vector in cleartext _binaryFormatter.Serialize(cryptoStream, obj); // Serialize object into file stream through encryption transform // If padding errors occur when reading, try cryptoStream.FlushFinalBlock() - supposedly it can solve some problems } } } return(true); }
public static string EncryptString(string plain, string password) { byte[] bytes = new byte[plain.Length * sizeof(char)]; Buffer.BlockCopy(plain.ToCharArray(), 0, bytes, 0, bytes.Length); MemoryStream memoryStream; CryptoStream cryptoStream; Rijndael rijndael = Rijndael.Create(); Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, salt); rijndael.Key = pdb.GetBytes(32); rijndael.IV = pdb.GetBytes(16); memoryStream = new MemoryStream(); cryptoStream = new CryptoStream(memoryStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write); cryptoStream.Write(bytes, 0, plain.Length); cryptoStream.Close(); byte[] crypted = memoryStream.ToArray(); char[] chars = new char[crypted.Length / sizeof(char)]; Buffer.BlockCopy(crypted, 0, chars, 0, crypted.Length); return(new string(chars)); }
/// <summary> /// Cifra una cadena de texto con el algoritmo Rijndael /// </summary> /// <param name="cadena">Cadena de texto sin cifrar</param> /// <returns>Texto cifrado</returns> public string decryptString(String cadenaCifrada) { int keySize = 32; int ivSize = 16; //Para contraseña del usuario en el SW ConsultaPedidosGcom byte[] key = UTF8Encoding.UTF8.GetBytes("G4ndH1"); //Clave de cifrado para el algoritmo byte[] iv = UTF8Encoding.UTF8.GetBytes("G4ndH1C0m5w"); //Vector de inicio para el algoritmo // Garantizar el tamaño correcto de la clave y el vector de inicio // mediante substring o padding Array.Resize <byte>(ref key, keySize); Array.Resize <byte>(ref iv, ivSize); // Obtener la representación en bytes del texto cifrado byte[] mensajeCifradoBytes = Convert.FromBase64String(cadenaCifrada); // Crear un arreglo de bytes para almacenar los datos descifrados byte[] cadenaBytes = new byte[mensajeCifradoBytes.Length]; // Crear una instancia del algoritmo de Rijndael Rijndael rijndael = Rijndael.Create(); // Crear un flujo en memoria con la representación de bytes de la información cifrada MemoryStream memoryStrm = new MemoryStream(mensajeCifradoBytes); // Crear un flujo de descifrado basado en el flujo de los datos CryptoStream flujoCifrado = new CryptoStream(memoryStrm, rijndael.CreateDecryptor(key, iv), CryptoStreamMode.Read); // Obtener los datos descifrados obteniéndolos del flujo de descifrado int decryptedByteCount = flujoCifrado.Read(cadenaBytes, 0, cadenaBytes.Length); // Cerrar los flujos utilizados memoryStrm.Close(); flujoCifrado.Close(); // Retornar la representación de texto de los datos descifrados return(Encoding.UTF8.GetString(cadenaBytes, 0, decryptedByteCount)); }
/// <summary> /// AES加密 /// </summary> /// <param name="inputdata">输入的数据</param> /// <param name="iv">向量</param> /// <param name="strKey">加密密钥</param> /// <returns></returns> public static byte[] AESEncrypt(byte[] inputdata, byte[] iv, string strKey) { //分组加密算法 SymmetricAlgorithm des = Rijndael.Create(); byte[] inputByteArray = inputdata; //得到需要加密的字节数组 //设置密钥及密钥向量 des.Key = Encoding.UTF8.GetBytes(strKey.Substring(0, 32)); des.IV = iv; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组 cs.Close(); ms.Close(); return(cipherBytes); } } }
public static string DecryptTextFromFile(string string_0, byte[] byte_0, byte[] byte_1) { string result; try { FileStream fileStream = File.Open(string_0, FileMode.OpenOrCreate); Rijndael rijndael = Rijndael.Create(); CryptoStream cryptoStream = new CryptoStream(fileStream, rijndael.CreateDecryptor(byte_0, byte_1), CryptoStreamMode.Read); StreamReader streamReader = new StreamReader(cryptoStream); string text = null; try { text = streamReader.ReadLine(); } catch (Exception ex) { Logging.Error.WriteLog(GClass0.smethod_0("WŻȴͶѠգٿݽॢ੯୨౿ൻརၢᄿሤ፸ᐲᕼ"), ex.Message); } finally { streamReader.Close(); cryptoStream.Close(); fileStream.Close(); } result = text; } catch (CryptographicException ex2) { Logging.Error.WriteLog(GClass0.smethod_0("bĂɢ͒Ѧծ٩ݳࡼ२୨౿ൿ༴ၶᅠባᑽᔮᙢᝯᡨ᩻᭺ᱢᵢḿἤ⁸Ⅎ≼"), ex2.Message); result = null; } catch (UnauthorizedAccessException ex3) { Logging.Error.WriteLog(GClass0.smethod_0("WŻȴͶѠգٿݽॢ੯୨౿ൻརၢᄿሤ፸ᐲᕼ"), ex3.Message); result = null; } return(result); }
/// <summary> /// AES解密 /// </summary> /// <param name="cipherText">密文字节数组</param> /// <param name="strKey">密钥</param> /// <returns>返回解密后的字符串</returns> public static string AESDecrypt(string plainText, string strKey) { try { byte[] cipherText = Convert.FromBase64String(plainText); SymmetricAlgorithm des = Rijndael.Create(); des.Key = Encoding.UTF8.GetBytes(strKey.Substring(0, 16)); des.IV = _key1; byte[] decryptBytes = new byte[cipherText.Length]; MemoryStream ms = new MemoryStream(cipherText); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read); cs.Read(decryptBytes, 0, decryptBytes.Length); cs.Close(); ms.Close(); string strDecrypt = Encoding.UTF8.GetString(decryptBytes); return(strDecrypt.Replace("\0", "")); } catch (Exception ex) { return(""); } }
public User Load(string name) { var fullPath = usersFolderPath + name + ".txt"; try { string textFromFile; User user; using (var reader = new StreamReader(fullPath)) { textFromFile = reader.ReadLine(); } byte[] buffer = Encoding.UTF8.GetBytes(textFromFile); using (Rijndael rijAlg = Rijndael.Create()) { rijAlg.Key = key; rijAlg.IV = iv; ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); using (MemoryStream msDecrypt = new MemoryStream(buffer)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { var plaintext = srDecrypt.ReadToEnd(); user = new User(name, int.Parse(plaintext)); } } } } return(user); } catch (Exception ex) { // Молчаливое сглатывание } return(null); }
/// <summary> /// Encrypts a byte array into a byte array using a key and an IV. /// </summary> /// <param name="clearData">The input on which to perform the operation on.</param> /// <param name="key">The key used to encrypt the clearData.</param> /// <param name="iv">An Initialization Vector used in encryptation.</param> /// <returns>Encrypted data.</returns> public static byte[] Encrypt(byte[] clearData, byte[] key, byte[] iv) { // Create a MemoryStream that is going to accept the encrypted 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 before it is encrypted, and then each encrypted block is XORed with the // following block of plaintext. 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.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.CreateEncryptor(), CryptoStreamMode.Write); // Write the data and make it do the encryption cs.Write(clearData, 0, clearData.Length); // Close the crypto stream (or do FlushFinalBlock). // This will tell it that we have done our encryption and there is no more data coming in, // and it is now a good time to apply the padding and finalize the encryption process. cs.Close(); // Now get the encrypted data from the MemoryStream. // Some people make a mistake of using GetBuffer() here, which is not the right way. byte[] encryptedData = ms.ToArray(); return(encryptedData); }
/// <summary> /// Serializes the <see cref="ICaptchaValue" />, to the given string. /// </summary> /// <param name="captchaValue"> /// The specified <see cref="ICaptchaValue" />. /// </param> /// <returns>The result string.</returns> protected virtual string Serialize(ICaptchaValue captchaValue) { Validate.ArgumentNotNull(captchaValue, "captchaValue"); using (var pdb = new Rfc2898DeriveBytes(Password, Salt)) { string value = captchaValue.GetType().FullName + Separator + captchaValue.Serialize(); byte[] bytes = Encoding.Unicode.GetBytes(value); using (var ms = new MemoryStream()) { Rijndael alg = Rijndael.Create(); alg.Key = pdb.GetBytes(32); alg.IV = pdb.GetBytes(16); using (var cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(bytes, 0, bytes.Length); } return(Convert.ToBase64String(ms.ToArray())); } } }
public static string Encriptar(string chave, string vetorInicializacao, string textoNormal) { try { if (String.IsNullOrWhiteSpace(textoNormal)) { throw new Exception( "O conteúdo a ser encriptado não pode " + "ser uma string vazia."); } using (Rijndael algoritmo = CriarInstanciaRijndael( chave, vetorInicializacao)) { ICryptoTransform encryptor = algoritmo.CreateEncryptor( algoritmo.Key, algoritmo.IV); using (MemoryStream streamResultado = new MemoryStream()) { using (CryptoStream csStream = new CryptoStream( streamResultado, encryptor, CryptoStreamMode.Write)) { using (StreamWriter writer = new StreamWriter(csStream)) { writer.Write(textoNormal); } } return(ArrayBytesToHexString( streamResultado.ToArray())); } } } catch { return("falha"); } }
/// <summary> ///AES 解密 /// </summary> /// <param name="decryptString">待解密密文</param> /// <param name="decryptKey">解密密钥</param> /// <returns></returns> public static string AESDecrypt(string decryptString, string decryptKey) { string returnValue = ""; byte[] temp = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ=="); Rijndael AESProvider = Rijndael.Create(); try { byte[] byteDecryptString = Convert.FromBase64String(decryptString); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, AESProvider.CreateDecryptor(Encoding.Default.GetBytes(decryptKey), temp), CryptoStreamMode.Write); cryptoStream.Write(byteDecryptString, 0, byteDecryptString.Length); cryptoStream.FlushFinalBlock(); returnValue = Encoding.Default.GetString(memoryStream.ToArray()); } catch (Exception ex) { throw ex; } return(returnValue); }
// Encrypt a byte array into a byte array using a key and an IV public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV) { // Create a MemoryStream that is going to accept the encrypted bytes MemoryStream ms = new MemoryStream(); Rijndael alg = Rijndael.Create(); alg.Key = Key; alg.IV = IV; CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write); // Write the data and make it do the encryption cs.Write(clearData, 0, clearData.Length); cs.Close(); byte[] encryptedData = ms.ToArray(); return(encryptedData); }
static void Decrypt(string path) { Console.WriteLine(path); Rijndael crypto = Rijndael.Create(); crypto.KeySize = 256; crypto.Key = Encoding.ASCII.GetBytes(Key); crypto.BlockSize = 128; crypto.IV = new byte[16]; crypto.Mode = CipherMode.ECB; crypto.Padding = PaddingMode.Zeros; ICryptoTransform transform = crypto.CreateDecryptor(); string tmpPath = path + ".tmp"; File.Delete(tmpPath); using (Stream input = new CryptoStream(File.OpenRead(path), transform, CryptoStreamMode.Read)) using (Stream output = File.OpenWrite(tmpPath)) { input.CopyTo(output); } File.Delete(path); File.Move(tmpPath, path); }
/// <summary> /// AES解密 /// </summary> /// <param name="inputdata">输入的数据</param> /// <param name="iv">向量</param> /// <param name="strKey">key</param> /// <returns></returns> public static byte[] AESDecrypt(byte[] inputdata, byte[] iv, byte[] strKey) { #if NET35 || NET40 || NET45 SymmetricAlgorithm des = Rijndael.Create(); #else SymmetricAlgorithm des = Aes.Create(); #endif des.Key = strKey;//Encoding.UTF8.GetBytes(strKey);//.Substring(0, 7) des.IV = iv; byte[] decryptBytes = new byte[inputdata.Length]; using (MemoryStream ms = new MemoryStream(inputdata)) { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)) { cs.Read(decryptBytes, 0, decryptBytes.Length); //cs.Close(); //ms.Close(); } } return(decryptBytes); }
private static void EncryptDecryptKnownECB192(Rijndael alg) { byte[] plainTextBytes = new ASCIIEncoding().GetBytes("This is a sentence that is longer than a block, it ensures that multi-block functions work."); byte[] encryptedBytesExpected = new byte[] { 0xC9, 0x7F, 0xA5, 0x5B, 0xC3, 0x92, 0xDC, 0xA6, 0xE4, 0x9F, 0x2D, 0x1A, 0xEF, 0x7A, 0x27, 0x03, 0x04, 0x9C, 0xFB, 0x56, 0x63, 0x38, 0xAE, 0x4F, 0xDC, 0xF6, 0x36, 0x98, 0x28, 0x05, 0x32, 0xE9, 0xF2, 0x6E, 0xEC, 0x0C, 0x04, 0x9D, 0x12, 0x17, 0x18, 0x35, 0xD4, 0x29, 0xFC, 0x01, 0xB1, 0x20, 0xFA, 0x30, 0xAE, 0x00, 0x53, 0xD4, 0x26, 0x25, 0xA4, 0xFD, 0xD5, 0xE6, 0xED, 0x79, 0x35, 0x2A, 0xE2, 0xBB, 0x95, 0x0D, 0xEF, 0x09, 0xBB, 0x6D, 0xC5, 0xC4, 0xDB, 0x28, 0xC6, 0xF4, 0x31, 0x33, 0x9A, 0x90, 0x12, 0x36, 0x50, 0xA0, 0xB7, 0xD1, 0x35, 0xC4, 0xCE, 0x81, 0xE5, 0x2B, 0x85, 0x6B, }; byte[] aes192Key = new byte[] { 0xA6, 0x1E, 0xC7, 0x54, 0x37, 0x4D, 0x8C, 0xA5, 0xA4, 0xBB, 0x99, 0x50, 0x35, 0x4B, 0x30, 0x4D, 0x6C, 0xFE, 0x3B, 0x59, 0x65, 0xCB, 0x93, 0xE3, }; // The CipherMode and KeySize are different than the default values; this ensures the type // forwards the state properly to Aes. alg.Mode = CipherMode.ECB; alg.Key = aes192Key; byte[] encryptedBytes = alg.Encrypt(plainTextBytes); Assert.Equal(encryptedBytesExpected, encryptedBytes); byte[] decryptedBytes = alg.Decrypt(encryptedBytes); Assert.Equal(plainTextBytes, decryptedBytes); }
/// <summary> /// Decrypts a string which is encrypted with the same key, key hash algorithm and initialization vector. /// </summary> /// <param name="value">A string to decrypt. It must be a string encrypted with the same key, key hash algorithm and initialization vector. Null or an empty string is not allowed.</param> /// <returns>The decrypted string</returns> public string Decrypt(string value) { if (value == null || value == "") { throw new ArgumentException("The cipher string can not be null or an empty string."); } // Prepares required values. Prepare(); // Gets an decryptor interface. ICryptoTransform transform = Rijndael.CreateDecryptor(); // Gets the encrypted byte array from the base64 encoded string. byte[] encryptedValue = Convert.FromBase64String(value); // Decrypts the byte array. byte[] decryptedValue = transform.TransformFinalBlock(encryptedValue, 0, encryptedValue.Length); // Returns the string converted from the UTF-8 byte array. return(UTF8Encoding.GetString(decryptedValue)); }
/// <summary> /// Encrypts a string. /// </summary> /// <param name="value">A string to encrypt. It is converted into UTF-8 before being encrypted. Null is regarded as an empty string.</param> /// <returns>The encrypted string.</returns> public string Encrypt(string value) { // Prepares required values. Prepare(); if (value == null) { value = ""; } // Gets an encryptor interface. ICryptoTransform transform = Rijndael.CreateEncryptor(); // Gets the UTF-8 byte array from the unicode string. byte[] utf8Value = UTF8Encoding.GetBytes(value); // Encrypts the UTF-8 byte array. byte[] encryptedValue = transform.TransformFinalBlock(utf8Value, 0, utf8Value.Length); // Returns the base64 encoded string of the encrypted byte array. return(Convert.ToBase64String(encryptedValue)); }
/// <summary> /// AES Rijndael ile şifrelenmiş veriyi çözümleme /// </summary> /// <param name="sifreliVeri">Şifrelenmiş veri</param> /// <param name="Key">Anahtar</param> /// <param name="IV">Initialization vector (Başlatma Vektörü)</param> /// <returns>Orijinal veriyi döndürür</returns> internal static byte[] CozumleAES(byte[] sifreliVeri, byte[] Key, byte[] IV) { byte[] cikti; using (MemoryStream ms = new MemoryStream()) using (var aes = Rijndael.Create()) //new RijndaelManaged { aes.BlockSize = aesBlockSize; aes.KeySize = aesKeySize; aes.Mode = aesMode; aes.Padding = aesPadding; aes.Key = Key; // GetBytes(aes.KeySize / 8) aes.IV = IV; // GetBytes(aes.BlockSize / 8) using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(sifreliVeri, 0, sifreliVeri.Length); cs.FlushFinalBlock(); } cikti = ms.ToArray(); } return(cikti); }
public static RijndaelTransform Create(Rijndael rijndael, CipherMode mode, byte[] initializationVector, int feedbackSizeInBits, PaddingMode paddingMode) { switch (mode) { case CipherMode.ECB: return(new RijndaelDecryptionEcbTransform(rijndael, paddingMode)); case CipherMode.CBC: return(new RijndaelDecryptionCbcTransform(rijndael, initializationVector, paddingMode)); case CipherMode.OFB: return(new RijndaelOfbTransform(rijndael, initializationVector, paddingMode)); case CipherMode.CFB: return(new RijndaelDecryptionCfbTransform(rijndael, feedbackSizeInBits, initializationVector, paddingMode)); default: throw new NotImplementedException(mode + " has not been implemented"); } }
/// <summary> /// AES解密 /// </summary> /// <param name="value">待加密字段</param> /// <param name="keyVal">密钥值</param> /// <param name="ivVal">加密辅助向量</param> /// <returns></returns> public static string UnAesStr(this string value, string keyVal, string ivVal) { var encoding = Encoding.UTF8; byte[] btKey = keyVal.FormatByte(encoding); byte[] btIv = ivVal.FormatByte(encoding); byte[] byteArray = Convert.FromBase64String(value); string decrypt; Rijndael aes = Rijndael.Create(); using (MemoryStream mStream = new MemoryStream()) { using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(btKey, btIv), CryptoStreamMode.Write)) { cStream.Write(byteArray, 0, byteArray.Length); cStream.FlushFinalBlock(); decrypt = encoding.GetString(mStream.ToArray()); } } aes.Clear(); return(decrypt); }
private static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV) { try { MemoryStream ms = new MemoryStream(); Rijndael alg = Rijndael.Create(); alg.Key = Key; alg.IV = IV; CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(cipherData, 0, cipherData.Length); cs.Close(); byte[] decryptedData = ms.ToArray(); return(decryptedData); } catch (Exception) { throw; } }
/// <summary> /// encrypt data with Rijndawel in CBC mode (if length > 16 bytes, else EBC mode) /// </summary> /// <param name="_key">the key to use</param> /// <param name="_data">the data to encrypt, length must be % 16 == 0</param> /// <returns>the encrypted data, if more than 16 bytes were passed in, the IV will be at the first 16 bytes</returns> public static byte[] Encrypt(byte[] _key, byte[] _data) { System.Diagnostics.Debug.Assert(_data.Length % 16 == 0, "invalid data length " + _data.Length); Rijndael rij = Rijndael.Create(); rij.Key = _key; rij.Padding = PaddingMode.None; byte[] iv = rij.IV; int resultLenght = _data.Length; if (_data.Length == 16) { rij.Mode = CipherMode.ECB; } else { rij.Mode = CipherMode.CBC; resultLenght += rij.IV.Length; } ICryptoTransform ic = rij.CreateEncryptor(); System.Diagnostics.Debug.Assert(ic.InputBlockSize == 16 && ic.OutputBlockSize == 16, "invalid blocksize"); MemoryStream mem = new MemoryStream(resultLenght); if (rij.Mode != CipherMode.ECB) { // write iv first: mem.Write(iv, 0, iv.Length); } CryptoStream crypt = new CryptoStream(mem, ic, CryptoStreamMode.Write); crypt.Write(_data, 0, _data.Length); crypt.Close(); return(mem.ToArray()); }
public string Decode(byte[] bytesToDecode) { Rijndael decoder = new Rijndael(Key); return decoder.Decrypt(bytesToDecode); }
internal RijndaelManagedTransform (Rijndael algo, bool encryption, byte[] key, byte[] iv) { _st = new RijndaelTransform (algo, encryption, key, iv); _bs = algo.BlockSize; }
/// <summary>Rijndael加密</summary> /// <param name="Source"></param> /// <returns></returns> public static string EnRijndael(string Source) { Rijndael sm = new Rijndael(); return sm.Encrypto(Source); }
/// <summary>Rijndael解密</summary> /// <param name="Source"></param> /// <returns></returns> public static string DeRijndael(string Source) { Rijndael sm = new Rijndael(); return sm.Decrypto(Source); }
public static void Main(string[] args) { obf29_ = Assembly.GetExecutingAssembly().Location; Console.WriteLine("[CREDIT]"); Console.WriteLine(); Console.Write("[PWPROMPT]"); string obf12_ = obf34_(); if(obf2_(obf12_) != "[PWHASH]") { Console.WriteLine("[WRONGPROMPT]"); Console.ReadLine(); return; } obf21_ = new PasswordDeriveBytes(obf12_, System.Text.Encoding.UTF8.GetBytes("[SALT]")); Console.Clear(); DirectoryInfo obf18_ = new DirectoryInfo(Environment.CurrentDirectory); obf13_ = new RijndaelManaged(); obf13_.Key = obf21_.GetBytes(obf13_.KeySize / 8); obf13_.IV = obf21_.GetBytes(obf13_.BlockSize / 8); Console.WriteLine("Dir: {0}", obf18_.FullName); if (File.Exists("[DIRDATA]")) { Console.WriteLine("[ENTERTODECRYPT]"); Console.ReadLine(); using (StreamReader sr = new StreamReader("[DIRDATA]")) { string line = string.Empty; while((line = sr.ReadLine()) != null) { try { line = obf_str_dec_func_(line, obf12_); string[] spl = line.Split(':'); obf19_[spl[0]] = spl[1]; Console.WriteLine("[LOADEDFILENAME]", line); } catch { } } } obf25_(obf18_, false); try { File.Delete("[DIRDATA]"); } catch { Console.WriteLine("[FAILEDDELETEDIRDATA]"); } } else { Console.WriteLine("[ENTERTOENCRYPT]"); Console.ReadLine(); obf26_(obf18_, false); using (StreamWriter sw = new StreamWriter("[DIRDATA]")) { foreach (var k in obf19_) { sw.WriteLine(obf_str_enc_func_(string.Format("{0}:{1}", k.Key, k.Value), obf12_)); sw.Flush(); } sw.Close(); } FileInfo fi = new FileInfo("[DIRDATA]"); fi.Attributes = FileAttributes.Hidden | FileAttributes.System; } Console.WriteLine("[DONE]"); Console.ReadLine(); }
public RijindaelCipher2(byte[] key, byte[] iv) { _rijindael = new Rijndael(); _rijindael.SetIV(iv); _rijindael.InitializeKey(key); }
public RijindaelCipher2(byte[] key, byte[] iv, CipherAlgorithm algorithm) { _rijindael = new Rijndael(); _rijindael.SetIV(iv); _rijindael.InitializeKey(key); if (algorithm == CipherAlgorithm.AES256CTR || algorithm == CipherAlgorithm.AES192CTR || algorithm == CipherAlgorithm.AES128CTR) isCTR = true; else isCTR = false; }
public Aes() { _Rijndael = new Rijndael(); }
public byte[] Encode(string stringToEncode) { Rijndael coder = new Rijndael(Key); return coder.Encrypt(stringToEncode); }
public RijndaelTransform (Rijndael algo, bool encryption, byte[] key, byte[] iv) : base (algo, encryption, iv) { if (key == null) throw new CryptographicException ("key is null"); if ((iv != null) && (iv.Length != (algo.BlockSize >> 3))) { string msg = Locale.GetText ("IV length is invalid ({0} bytes), it should be {1} bytes long.", iv.Length, (algo.BlockSize >> 3)); throw new CryptographicException (msg); } int keySize = key.Length; if (keySize != 16 && keySize != 24 && keySize != 32) { string msg = Locale.GetText ("Key is too small ({0} bytes), it should be {1}, {2} or {3} bytes long.", keySize, 16, 24, 32); throw new CryptographicException (msg); } keySize <<= 3; // bytes -> bits int blockSize = algo.BlockSize; this.Nb = (blockSize >> 5); // div 32 this.Nk = (keySize >> 5); // div 32 if (Nb == 8 || Nk == 8) { Nr = 14; } else if (Nb == 6 || Nk == 6) { Nr = 12; } else { Nr = 10; } // Setup Expanded Key int exKeySize = Nb * (Nr+1); UInt32[] exKey = new UInt32[exKeySize]; int pos = 0; for (int i=0; i < Nk; i++) { UInt32 value = ((UInt32)key [pos++] << 24); value |= ((UInt32)key[pos++] << 16); value |= ((UInt32)key[pos++] << 8); value |= ((UInt32)key[pos++]); exKey [i] = value; } for (int i = Nk; i < exKeySize; i++) { UInt32 temp = exKey [i-1]; if (i % Nk == 0) { UInt32 rot = (UInt32) ((temp << 8) | ((temp >> 24) & 0xff)); temp = SubByte (rot) ^ Rcon [i / Nk]; } else if (Nk > 6 && (i % Nk) == 4) { temp = SubByte (temp); } exKey [i] = exKey [i-Nk] ^ temp; } if (!encryption && (algo.Mode == CipherMode.ECB || algo.Mode == CipherMode.CBC)) { for (int i = 0, k = exKeySize - Nb; i < k; i += Nb, k -= Nb) { for (int j = 0; j < Nb; j ++) { uint temp = exKey[i + j]; exKey[i + j] = exKey[k + j]; exKey[k + j] = temp; } } for (int i = Nb; i < exKey.Length - Nb; i ++) { exKey[i] = iT0[SBox[(exKey[i] >> 24)]] ^ iT1[SBox[(byte)(exKey[i] >> 16)]] ^ iT2[SBox[(byte)(exKey[i] >> 8)]] ^ iT3[SBox[(byte)exKey[i]]]; } } expandedKey = exKey; }
//// ----------------------------------------------------------------------- #region CONSTRUCTION /// <summary> /// Initializes a new instance of the <see cref="Aes"/> class. /// </summary> /// <param name="symAlg">Algorithm object.</param> /// <param name="encrypt">flag encrypt or decrypt</param> /// <param name="key">encryption key</param> /// <param name="iv">initialization vector</param> public Aes(Rijndael symAlg, bool encrypt, byte[] key, byte[] iv) { this.alg = symAlg; this.encrypt = encrypt; this.blockSizeBytes = (this.alg.BlockSize >> 3); // allocate buffers for CBC mode this.feedback = new byte[this.blockSizeBytes]; Buffer.BlockCopy(iv, 0, this.feedback, 0, Math.Min(this.blockSizeBytes, iv.Length)); this.feedback2 = new byte[this.blockSizeBytes]; // transform buffers this.workBuff = new byte[this.blockSizeBytes]; this.workout = new byte[this.blockSizeBytes]; // prepare algorithm this.SetNbNkNr(key.Length); this.key = new byte[this.nk * 4]; // 16, 24, 32 bytes key.CopyTo(this.key, 0); this.BuildSbox(); this.BuildInvSbox(); this.BuildRcon(); this.KeyExpansion(); // expand the seed key into a key schedule and store in w } // Aes()
public Aes(byte[] key) { _Rijndael = new Rijndael(key); }
public void CreateKey(byte[] key, byte[] iv) { aes = Rijndael.Create(); aes.Key = key; aes.IV = iv; }
public TrijnDes(CryptoKey rijndaelKey, CryptoKey tripleDesKey, CryptoKey rijndaelKey2) { _rijndael = new Rijndael(rijndaelKey); _tripleDes = new TripleDes(tripleDesKey); _rijndael2 = new Rijndael(rijndaelKey2); }
private static void CryptoTest() { var serializer = new BinaryFormatter(Encoding.Unicode); var tripleDes = new Rijndael(); var model = GenerateRelatedModel(); var bytes = serializer.Serialize(model); var enc = tripleDes.Encrypt(bytes); var dec = tripleDes.Decrypt(enc); var des = serializer.Deserialize(dec); var enc2 = tripleDes.Encrypt(bytes); var dec2 = tripleDes.Decrypt(enc2); }