public static string Encrypt(this string text, string salt) { try { using (Aes aes = new AesManaged()) { Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(salt)); aes.Key = deriveBytes.GetBytes(128 / 8); aes.IV = aes.Key; using (MemoryStream encryptionStream = new MemoryStream()) { using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { byte[] cleanText = Encoding.UTF8.GetBytes(text); encrypt.Write(cleanText, 0, cleanText.Length); encrypt.FlushFinalBlock(); } byte[] encryptedData = encryptionStream.ToArray(); string encryptedText = Convert.ToBase64String(encryptedData); return encryptedText; } } } catch { return String.Empty; } }
//</Snippet2> // <Snippet3> // Encrypt a file using a public key. private static void EncryptFile(string inFile, RSACryptoServiceProvider rsaPublicKey) { using (AesManaged aesManaged = new AesManaged()) { // Create instance of AesManaged for // symetric encryption of the data. aesManaged.KeySize = 256; aesManaged.BlockSize = 128; aesManaged.Mode = CipherMode.CBC; using (ICryptoTransform transform = aesManaged.CreateEncryptor()) { RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsaPublicKey); byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType()); // Create byte arrays to contain // the length values of the key and IV. byte[] LenK = new byte[4]; byte[] LenIV = new byte[4]; int lKey = keyEncrypted.Length; LenK = BitConverter.GetBytes(lKey); int lIV = aesManaged.IV.Length; LenIV = BitConverter.GetBytes(lIV); // Write the following to the FileStream // for the encrypted file (outFs): // - length of the key // - length of the IV // - ecrypted key // - the IV // - the encrypted cipher content int startFileName = inFile.LastIndexOf("\\") + 1; // Change the file's extension to ".enc" string outFile = encrFolder + inFile.Substring(startFileName, inFile.LastIndexOf(".") - startFileName) + ".enc"; Directory.CreateDirectory(encrFolder); using (FileStream outFs = new FileStream(outFile, FileMode.Create)) { outFs.Write(LenK, 0, 4); outFs.Write(LenIV, 0, 4); outFs.Write(keyEncrypted, 0, lKey); outFs.Write(aesManaged.IV, 0, lIV); // Now write the cipher text using // a CryptoStream for encrypting. using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write)) { // By encrypting a chunk at // a time, you can save memory // and accommodate large files. int count = 0; int offset = 0; // blockSizeBytes can be any arbitrary size. int blockSizeBytes = aesManaged.BlockSize / 8; byte[] data = new byte[blockSizeBytes]; int bytesRead = 0; using (FileStream inFs = new FileStream(inFile, FileMode.Open)) { do { count = inFs.Read(data, offset, blockSizeBytes); offset += count; outStreamEncrypted.Write(data, 0, count); bytesRead += count; }while (count > 0); inFs.Close(); } outStreamEncrypted.FlushFinalBlock(); outStreamEncrypted.Close(); } outFs.Close(); } } } }
/// <summary> /// Encrypts the specified string expression /// </summary> /// <param name="plainText">Text expression to encrypt</param> /// <returns>Base64-encoded ciphertext expression</returns> /// <example> /// <code> /// string thumbprint = @"ccdc673c40ebb2a433300c0c8a2ba6f443da5688"; /// <see cref="X509Context"/> certStore = <see cref="X509Context"/>.<see cref="X509Context.UserReadOnly"/>; /// /// string plaintext = @"Hello world!"; /// string ciphertext; /// using (<see cref="X509CryptoAgent"/> agent = new <see cref="X509CryptoAgent"/>(thumbprint, certStore)) /// { /// ciphertext = agent.EncryptText(plaintext); /// } /// </code> /// </example> public string EncryptText(string plainText) { byte[] cipherTextBytes; byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); using (AesManaged aesManaged = new AesManaged()) { aesManaged.KeySize = CryptoConstants.AESKeySize; aesManaged.BlockSize = CryptoConstants.AESBlockSize; aesManaged.Mode = CipherMode.CBC; using (ICryptoTransform transform = aesManaged.CreateEncryptor()) { byte[] keyEncrypted = publicKey.Encrypt(aesManaged.Key, RSAEncryptionPadding.OaepSHA384); //Contain the length values of the key and IV respectively byte[] KeyLengthIndicator = new byte[CryptoConstants.AESBytes]; byte[] IVLengthIndicator = new byte[CryptoConstants.AESBytes]; //Byte arrays to contain the length values of the key and IV int keyLength = keyEncrypted.Length; KeyLengthIndicator = BitConverter.GetBytes(keyLength); int IVLength = aesManaged.IV.Length; IVLengthIndicator = BitConverter.GetBytes(IVLength); using (MemoryStream memStream = new MemoryStream()) { memStream.Write(KeyLengthIndicator, 0, CryptoConstants.AESBytes); memStream.Write(IVLengthIndicator, 0, CryptoConstants.AESBytes); memStream.Write(keyEncrypted, 0, keyLength); memStream.Write(aesManaged.IV, 0, IVLength); //Write the ciphertext using a CryptoStream using (CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write)) { int count = 0; int offset = 0; int blockSizeInBytes = aesManaged.BlockSize / CryptoConstants.AESWords; byte[] data = new byte[blockSizeInBytes]; int bytesRead = 0; using (MemoryStream inStream = new MemoryStream(plainTextBytes, false)) { do { count = inStream.Read(data, 0, blockSizeInBytes); offset += count; cryptoStream.Write(data, 0, count); bytesRead += blockSizeInBytes; }while (count > 0); inStream.Close(); } cryptoStream.FlushFinalBlock(); cryptoStream.Close(); cipherTextBytes = memStream.ToArray(); } } } return(Convert.ToBase64String(cipherTextBytes)); } }
private void Encrpt_Click(object sender, EventArgs e) { if (EncAlg.Text == "DES") { byte[] key = new byte[8]; for (int i = 0; i < 8; i++) { key[i] = (byte)EncKey.Text[i]; } string inName = EncFile.Text; string outName = string.Concat(EncFile.Text, ".des"); //Create the file streams to handle the input and output files. FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write); fout.SetLength(0); //Create variables to help with read and write. 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. DES des = new DESCryptoServiceProvider(); CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(key, key), CryptoStreamMode.Write); //Read from the input file, then encrypt and write to the output file. while (rdlen < totlen) { len = fin.Read(bin, 0, 100); encStream.Write(bin, 0, len); rdlen = rdlen + len; } encStream.Close(); fout.Close(); fin.Close(); MessageBox.Show("DES加密完成"); } else if (EncAlg.Text == "AES") { byte[] key = new byte[16]; for (int i = 0; i < 16; i++) { key[i] = (byte)EncKey.Text[i]; } string inName = EncFile.Text; string outName = string.Concat(EncFile.Text, ".aes"); //Create the file streams to handle the input and output files. FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write); fout.SetLength(0); //Create variables to help with read and write. 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. AesManaged aes = new AesManaged(); CryptoStream encStream = new CryptoStream(fout, aes.CreateEncryptor(key, key), CryptoStreamMode.Write); //Read from the input file, then encrypt and write to the output file. while (rdlen < totlen) { len = fin.Read(bin, 0, 100); encStream.Write(bin, 0, len); rdlen = rdlen + len; } encStream.Close(); fout.Close(); fin.Close(); MessageBox.Show("AES加密完成"); } else { MessageBox.Show("请选择加密算法"); } }
private static byte[] Encrypt(byte[] byteArrayToEncrypt, string password) { try { using (Aes aes = new AesManaged()) { aes.BlockSize = BLOCK_SIZE; aes.KeySize = KEY_SIZE; aes.Key = GetKey(Encoding.UTF8.GetBytes(password), aes); aes.IV = staticIV; using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { byte[] utfD1 = byteArrayToEncrypt; cryptoStream.Write(utfD1, 0, utfD1.Length); cryptoStream.FlushFinalBlock(); } return(memoryStream.ToArray()); } } } catch { throw new AppException(T360ErrorCodes.EncryptionFailed); } }
/// <summary> /// Saves a stream into a file with encryption /// </summary> /// <param name="filename"></param> /// <param name="contents">Stream</param> public override void Save(string filename, Stream contents) { EnsureDirectoryExists(filename); DateTime dtMetric = DateTime.UtcNow; byte[] bytes = null; AesManaged aesAlg = null; // Create the streams used for encryption. FileStream fileStream = null; CryptoStream csEncrypt = null; BinaryWriter binaryWriter = null; BinaryReader binaryReader = null; GZipStream gzip = null; try { aesAlg = GetAesManaged(); // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); binaryReader = new BinaryReader(contents); fileStream = new FileStream(filename, FileMode.Create); csEncrypt = new CryptoStream(fileStream, encryptor, CryptoStreamMode.Write); gzip = new GZipStream(csEncrypt, CompressionMode.Compress); binaryWriter = new BinaryWriter(gzip); // process through stream in small chunks to keep peak memory usage down. bytes = binaryReader.ReadBytes(6144); while (bytes.Length > 0) { binaryWriter.Write(bytes); bytes = binaryReader.ReadBytes(6144); } } finally { if (binaryWriter != null) { binaryWriter.Close(); } if (gzip != null) { gzip.Close(); } if (csEncrypt != null) { csEncrypt.Close(); } if (fileStream != null) { fileStream.Close(); } if (binaryReader != null) { binaryReader.Close(); } // Clear the RijndaelManaged object. if (aesAlg != null) { aesAlg.Clear(); } } MXDevice.Log.Debug(string.Format("BasicFileEncrypted.Save(stream): File: {0} Time: {1} milliseconds", filename, DateTime.UtcNow.Subtract(dtMetric).TotalMilliseconds)); }
/// <summary> /// Encrypt a file. /// </summary> /// <param name="inputFile">The name of the file to encrypt.</param> /// <param name="password">The password to use.</param> /// <param name="overwrite">If the resultfile should be overwritten if it already exists.</param> /// <param name="deleteOriginal">If the original file should be deleted after encryption.</param> public void EncryptFile(string inputFile, string password, bool overwrite = true, bool deleteOriginal = false) { var outputFile = inputFile + _extension; if (File.Exists(inputFile) == false) { throw new FileNotFoundException("Inputfile not found"); } if (File.Exists(outputFile)) { if (overwrite) { try { File.Delete(outputFile); Logger.Info(" Deleted " + outputFile); } catch (Exception ex) { Logger.Error(ex); throw; } } else { throw new ApplicationException("Outputfile exists"); } } Logger.Info("Encrypting " + inputFile); using (var aesManaged = new AesManaged()) { // Set ciphermode for the AES algoritm (CBC, cipher block chaining, by default) aesManaged.Mode = CipherMode.CBC; // Generate initialization vector, IV is 16 bytes (128 bits) long aesManaged.GenerateIV(); // Generate a random salt byte[] salt = GenerateRandomSalt(); // Generate a 256 bits key using the password and the salt aesManaged.Key = GenerateKey(password, salt); byte[] buffer = new byte[1024 * 1024]; int read, totalRead = 0; using (var inputStream = new FileStream(inputFile, FileMode.Open)) using (var outputStream = new FileStream(outputFile, FileMode.Create)) { // Append salt to filestream outputStream.Write(salt, 0, salt.Length); // Append initialization vector to filestream outputStream.Write(aesManaged.IV, 0, aesManaged.IV.Length); try { using (var cryptoStream = new CryptoStream(outputStream, aesManaged.CreateEncryptor(), CryptoStreamMode.Write)) { while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0) { totalRead += read; Logger.Trace(" {0} bytes", totalRead); cryptoStream.Write(buffer, 0, read); } Logger.Info(" Encrypt Done - {0} bytes", totalRead); } } catch (CryptographicException ex_CryptographicException) { Logger.Error(ex_CryptographicException, "CryptographicException error"); throw; } catch (Exception ex) { Logger.Error(ex); throw; } } if (deleteOriginal) { try { File.Delete(inputFile); Logger.Info(" Deleted " + inputFile); } catch (Exception ex) { Logger.Error(ex); throw; } } } }
/// <summary> /// Encrypts a JSON representation of a UserData object using AES128-CBC with a 16-bit SHA1 salted hash key. /// Returns a Base64 String containing the encrypted JSON pre-pended with the initialization vector (IV) used in the encryption. /// </summary> /// <param name="user_data">The UserData object to be encrypted.</param> /// <returns></returns> protected static string EncryptData(UserData user_data) { // Using byte arrays instead of strings byte[] encrypted; byte[] saltedHash; byte[] bIV = new byte[16]; // 16-byte initialization vector as a byte array. byte[] bJsonUserData; /* Uncomment to enable decrypting for debugging/testing byte[] decrypted = null; */ // Encode the user_data object into a JSON string JavaScriptSerializer s = new JavaScriptSerializer(); string json_data = s.Serialize(user_data); bJsonUserData = Encoding.ASCII.GetBytes(json_data); // Generate a random initialization vector RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(bIV); // Use an AesManaged object to do the encryption using (AesManaged aesAlg = new AesManaged()) { aesAlg.IV = bIV; aesAlg.KeySize = 128; // Create the 16-byte salted hash SHA1 sha1 = SHA1.Create(); saltedHash = sha1.ComputeHash(Encoding.ASCII.GetBytes(api_key + site_key), 0, (api_key + site_key).Length); // Trim saltedHash to 16 bytes. Array.Resize(ref saltedHash, 16); // Use salted has as the AES key. aesAlg.Key = saltedHash; // Encrypt using the AES Managed object ICryptoTransform encryptor = aesAlg.CreateEncryptor(); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { csEncrypt.Write(bJsonUserData, 0, bJsonUserData.Length); csEncrypt.FlushFinalBlock(); } encrypted = msEncrypt.ToArray(); } /* * Uncomment to enable decrypting for debugging/testing * // Decrypt using AES Managed object ICryptoTransform decryptor = aesAlg.CreateDecryptor(); using (MemoryStream msDecrypt = new MemoryStream()) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write)) { csDecrypt.Write(encrypted, 0, encrypted.Length); csDecrypt.FlushFinalBlock(); } decrypted = msDecrypt.ToArray(); } string decryptedString = Encoding.ASCII.GetString(decrypted); */ } // Pre-pend the encrypted data with the IV. byte[] ivPlusEncrypted = bIV.Concat(encrypted).ToArray(); // Return the Base64-encoded encrypted data string encryptedBase64 = Convert.ToBase64String(ivPlusEncrypted, Base64FormattingOptions.None); return encryptedBase64; }
// From https://github.com/codetheweb/tuyapi/blob/master/index.js#L300 byte[] EncryptedBytesFromJSONForDevice(string JSON, Device device) { Log.Format("Request.EncryptedBytesFromJSONForDevice()"); // Key. byte[] key = Encoding.UTF8.GetBytes(device.localKey); // Encrypt with key. string encryptedJSONBase64String; using (AesManaged aes = new AesManaged() { Mode = CipherMode.ECB, Key = key }) using (MemoryStream encryptedStream = new MemoryStream()) using (CryptoStream cryptoStream = new CryptoStream(encryptedStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { byte[] JSONBytes = Encoding.UTF8.GetBytes(JSON); cryptoStream.Write(JSONBytes, 0, JSONBytes.Length); cryptoStream.Close(); encryptedJSONBase64String = Convert.ToBase64String(encryptedStream.ToArray()); } // Create hash. string hashString; using (MD5 md5 = MD5.Create()) using (MemoryStream hashBaseStream = new MemoryStream()) { byte[] encryptedPayload = Encoding.UTF8.GetBytes($"data={encryptedJSONBase64String}||lpv={device.protocolVersion}||"); hashBaseStream.Write(encryptedPayload, 0, encryptedPayload.Length); hashBaseStream.Write(key, 0, key.Length); byte[] hashBytes = md5.ComputeHash(hashBaseStream.ToArray()); string hash = BitConverter.ToString(hashBytes).Replace("-", string.Empty).ToLower(); hashString = hash.Substring(8, 16); } // Stitch together. return(Encoding.UTF8.GetBytes($"{device.protocolVersion}{hashString}{encryptedJSONBase64String}")); }
public int Do_Aes(string[] args, Program.Properties props) { byte[] iv; byte[] key; int keylen; long offset = 0; long len = 0; Properties subprops = new Properties() { keylen = 256, }; CryptoStream Cs; ToolsArgMap argMap = new ToolsArgMap(); argMap.Init_args_Aes(args, ref subprops); if (props.help) { PrintHelp(); return(0); } keylen = subprops.keylen; iv = new byte[16]; key = new byte[keylen / 8]; // keylenはbit値、128または256 /* * check/build iv and key */ /* iv */ if (subprops.iv == null || subprops.iv.Length == 0) // if iv is not specified or blank { /* use default array of iv (filled by '0') */ Console.Error.WriteLine( Lang.Resource.Main_Warning_Prefix + Lang.Tools.AesRes.Warning_NoIV); } else // if iv is specified { if (!subprops.hex_iv && subprops.iv.Length > iv.Length) { Console.Error.WriteLine( Lang.Resource.Main_Error_Prefix + Lang.Tools.AesRes.Error_LongIVLen); return(1); } else if (subprops.hex_iv) { if (subprops.iv.Length % 2 != 0) { Console.Error.WriteLine( Lang.Resource.Main_Error_Prefix + Lang.Tools.AesRes.Error_InvalidIVLenHex); return(1); } if (subprops.iv.Length > iv.Length * 2) { Console.Error.WriteLine( Lang.Resource.Main_Error_Prefix + Lang.Tools.AesRes.Error_LongIVLenHex); } } if (subprops.hex_iv) { for (int i = 0; i < (subprops.iv.Length / 2); i++) { iv[i] = Convert.ToByte(subprops.iv.Substring(i * 2, 2), 16); } } else { byte[] tmp_iv = Encoding.ASCII.GetBytes(subprops.iv); Array.Copy(tmp_iv, iv, tmp_iv.Length); } } /* iv end */ /* key */ if (subprops.key == null || subprops.key.Length == 0) { Console.Error.WriteLine( Lang.Resource.Main_Error_Prefix + Lang.Tools.AesRes.Error_NoKey); return(1); } if (!subprops.hex_key && subprops.key.Length > key.Length) { Console.Error.WriteLine( Lang.Resource.Main_Error_Prefix + Lang.Tools.AesRes.Error_LongKeyLen, key.Length); return(1); } else if (subprops.hex_key) { if (subprops.key.Length % 2 != 0) { Console.Error.WriteLine( Lang.Resource.Main_Error_Prefix + Lang.Tools.AesRes.Error_InvalidKeyLenHex); return(1); } if (subprops.key.Length > key.Length * 2) { Console.Error.WriteLine( Lang.Resource.Main_Error_Prefix + Lang.Tools.AesRes.Error_LongKeyLenHex, key.Length, key.Length * 2); return(1); } } if (subprops.hex_key) { for (int i = 0; i < (subprops.key.Length / 2); i++) { key[i] = Convert.ToByte(subprops.key.Substring(i * 2, 2), 16); } } else { byte[] tmp_key = Encoding.ASCII.GetBytes(subprops.key); Array.Copy(tmp_key, key, tmp_key.Length); //if (tmp_key.Length < keylen / 8) // Console.Error.WriteLine("specified key is too short, padded by '0'"); } /* key end */ /* * check/build iv and key end */ FileStream inFs; FileStream outFs; FileMode outMode = File.Exists(props.outFile) ? FileMode.Truncate : FileMode.Create; try { inFs = new FileStream(props.inFile, FileMode.Open, FileAccess.Read, FileShare.Write); outFs = new FileStream(props.outFile, outMode, FileAccess.Write, FileShare.None); } catch (IOException e) { Console.Error.WriteLine(e.Message); return(1); } /* check offset/length */ if (subprops.offset > inFs.Length) { Console.Error.WriteLine( Lang.Resource.Main_Warning_Prefix + Lang.Tools.AesRes.Warning_LargeOffset); } else { offset = subprops.offset; } if (subprops.len != null && // something is specified for len (Program.StrToLong(subprops.len, out len, 0) != 0 || // fail to convert (invalid chars for num) len <= 0 || // equal or smaller than 0 len > inFs.Length - offset)) // larger than valid length { Console.Error.WriteLine( Lang.Resource.Main_Warning_Prefix + Lang.Tools.AesRes.Warning_InvalidLength); subprops.len = null; } if (subprops.len != null ? len % 16 != 0 : // if "length" specified (inFs.Length - offset) % 16 != 0) // no length specified { if (subprops.decrypt) { Console.Error.WriteLine( Lang.Resource.Main_Error_Prefix + Lang.Tools.AesRes.Error_InvalidDecLen); return(1); } else { Console.Error.WriteLine( Lang.Resource.Main_Warning_Prefix + Lang.Tools.AesRes.Warning_ShortEncLen); } } /* check offset/length end */ PrintInfo(subprops, key, iv, subprops.len != null ? len : inFs.Length - offset); AesManaged aes = new AesManaged { KeySize = keylen, IV = iv, Key = key, Mode = CipherMode.CBC, Padding = PaddingMode.Zeros }; ICryptoTransform endec = subprops.decrypt ? aes.CreateDecryptor(aes.Key, aes.IV) : aes.CreateEncryptor(aes.Key, aes.IV); Cs = new CryptoStream(outFs, endec, CryptoStreamMode.Write); inFs.Seek(offset, SeekOrigin.Begin); byte[] buf = new byte[0x10000]; int readlen; while ((readlen = inFs.Read(buf, 0, buf.Length)) > 0) { if (subprops.len == null) { Cs.Write(buf, 0, readlen); } else if (len > readlen) { len -= readlen; Cs.Write(buf, 0, readlen); } else { Cs.Write(buf, 0, (int)len); break; } } Cs.Close(); inFs.Close(); outFs.Close(); return(0); }
// Fernet: from https://github.com/fernet/spec/blob/master/Spec.md // return value is base64 url encoded // trimEnd is to force trimming of return value public static string EncryptFernet(byte[] key, byte[] data, DateTime?timestamp = null, byte[] iv = null, bool trimEnd = false) { // Fernet: from https://github.com/fernet/spec/blob/master/Spec.md if (key == null) { throw new ArgumentNullException(nameof(key)); } if (key.Length != 32) { throw new ArgumentException(nameof(key)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } if (iv != null && iv.Length != 16) { throw new ArgumentException(nameof(iv)); } if (timestamp == null) { timestamp = DateTime.UtcNow; } byte[] result = new byte[57 + ((data.Length + 16) / 16 * 16)]; result[0] = 0x80; { // BigEndian to LittleEndian long timestamp2 = new DateTimeOffset(timestamp.Value).ToUnixTimeSeconds(); timestamp2 = IPAddress.NetworkToHostOrder(timestamp2); byte[] timestamp3 = BitConverter.GetBytes(timestamp2); Buffer.BlockCopy(timestamp3, 0, result, 1, timestamp3.Length); } using (var aes = new AesManaged()) { aes.Mode = CipherMode.CBC; byte[] encryptionKey = new byte[16]; Buffer.BlockCopy(key, 16, encryptionKey, 0, 16); aes.Key = encryptionKey; if (iv != null) { aes.IV = iv; } else { aes.GenerateIV(); } Buffer.BlockCopy(aes.IV, 0, result, 9, 16); aes.Padding = PaddingMode.PKCS7; using (var encryptor = aes.CreateEncryptor()) { byte[] encrypted = encryptor.TransformFinalBlock(data, 0, data.Length); Buffer.BlockCopy(encrypted, 0, result, 25, encrypted.Length); } } byte[] signingKey = new byte[16]; Buffer.BlockCopy(key, 0, signingKey, 0, 16); using (var hmac = new HMACSHA256(signingKey)) { hmac.TransformFinalBlock(result, 0, result.Length - 32); Buffer.BlockCopy(hmac.Hash, 0, result, result.Length - 32, 32); } return(Base64UrlEncode(result, trimEnd)); }
/// <summary> /// Reads the contents of the specified input stream and writes an encrypted version of the contents to the specified output stream. /// </summary> /// <param name="inputStream">The stream that contains the unencrypted data.</param> /// <param name="outputStream">The stream to write the encrypted data to.</param> /// <param name="key">The keyword to derive the encryption key from.</param> /// <param name="salt">The key salt to derive the encryption key from.</param> public override void EncryptStream(Stream inputStream, Stream outputStream, string key, byte[] salt) { DateTime dtMetric = DateTime.UtcNow; byte[] bytes = null; AesManaged aesAlg = null; // Create the streams used for encryption. CryptoStream crypto = null; BinaryWriter binaryWriter = null; BinaryReader binaryReader = null; GZipStream gzip = null; try { if (inputStream != null && inputStream.Length > 0) { aesAlg = GetAesManaged(key, salt); // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); binaryReader = new BinaryReader(inputStream); crypto = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write); gzip = new GZipStream(crypto, CompressionMode.Compress); binaryWriter = new BinaryWriter(gzip); // process through stream in small chunks to keep peak memory usage down. bytes = binaryReader.ReadBytes(BUFFER_SIZE); while (bytes.Length > 0) { binaryWriter.Write(bytes); bytes = binaryReader.ReadBytes(BUFFER_SIZE); } } } finally { if (binaryWriter != null) { binaryWriter.Close(); } if (gzip != null) { gzip.Close(); } if (crypto != null) { crypto.Close(); } if (binaryReader != null) { binaryReader.Close(); } //FIXME: http://support.MonoCross.com/discussions/data-stack/47-v28-encryptor-cache-causes-file-locking-problem-in-windows //// Clear the RijndaelManaged object. //if ( aesAlg != null ) // aesAlg.Clear(); } Device.Log.Metric(string.Format("AesEncryption.EncryptStream(stream, key, salt): Time: {0} milliseconds", DateTime.UtcNow.Subtract(dtMetric).TotalMilliseconds)); }
public static byte[] Encrypt(this AesManaged aes, byte[] buf) => Transform(buf, 0, buf.Length, aes.CreateEncryptor());
/// <summary> /// Return an encrypted entity. This method is used for encrypting entity properties. /// </summary> internal Dictionary <string, EntityProperty> EncryptEntity(IDictionary <string, EntityProperty> properties, string partitionKey, string rowKey, Func <string, string, string, bool> encryptionResolver) { CommonUtility.AssertNotNull("properties", properties); // The Key should be set on the policy for encryption. Otherwise, throw an error. if (this.Key == null) { throw new InvalidOperationException(SR.KeyMissingError, null); } EncryptionData encryptionData = new EncryptionData(); encryptionData.EncryptionAgent = new EncryptionAgent(Constants.EncryptionConstants.EncryptionProtocolV1, EncryptionAlgorithm.AES_CBC_256); encryptionData.KeyWrappingMetadata = new Dictionary <string, string>(); Dictionary <string, EntityProperty> encryptedProperties = new Dictionary <string, EntityProperty>(); HashSet <string> encryptionPropertyDetailsSet = new HashSet <string>(); #if WINDOWS_DESKTOP && !WINDOWS_PHONE using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider()) { using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider()) #else using (AesManaged myAes = new AesManaged()) { using (SHA256Managed sha256 = new SHA256Managed()) #endif { encryptionData.ContentEncryptionIV = myAes.IV; // Wrap always happens locally, irrespective of local or cloud key. So it is ok to call it synchronously. Tuple <byte[], string> wrappedKey = this.Key.WrapKeyAsync(myAes.Key, null /* algorithm */, CancellationToken.None).Result; encryptionData.WrappedContentKey = new WrappedKey(this.Key.Kid, wrappedKey.Item1, wrappedKey.Item2); foreach (KeyValuePair <string, EntityProperty> kvp in properties) { if (encryptionResolver != null && encryptionResolver(partitionKey, rowKey, kvp.Key)) { // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity case // where a user adds a new property as follows - ent.Properties.Add("foo2", null); if (kvp.Value == null) { throw new InvalidOperationException(SR.EncryptingNullPropertiesNotAllowed); } kvp.Value.IsEncrypted = true; } // IsEncrypted is set to true when either the EncryptPropertyAttribute is set on a property or when it is // specified in the encryption resolver or both. if (kvp.Value != null && kvp.Value.IsEncrypted) { // Throw if users try to encrypt non-string properties. if (kvp.Value.PropertyType != EdmType.String) { throw new InvalidOperationException(string.Format(SR.UnsupportedPropertyTypeForEncryption, kvp.Value.PropertyType)); } byte[] columnIV = sha256.ComputeHash(CommonUtility.BinaryAppend(encryptionData.ContentEncryptionIV, Encoding.UTF8.GetBytes(string.Join(partitionKey, rowKey, kvp.Key)))); Array.Resize <byte>(ref columnIV, 16); myAes.IV = columnIV; using (ICryptoTransform transform = myAes.CreateEncryptor()) { // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity or POCO // case when the property value is null. if (kvp.Value.IsNull) { throw new InvalidOperationException(SR.EncryptingNullPropertiesNotAllowed); } byte[] src = Encoding.UTF8.GetBytes(kvp.Value.StringValue); byte[] dest = transform.TransformFinalBlock(src, 0, src.Length); // Store the encrypted properties as binary values on the service instead of base 64 encoded strings because strings are stored as a sequence of // WCHARs thereby further reducing the allowed size by half. During retrieve, it is handled by the response parsers correctly // even when the service does not return the type for JSON no-metadata. encryptedProperties.Add(kvp.Key, new EntityProperty(dest)); encryptionPropertyDetailsSet.Add(kvp.Key); } } else { encryptedProperties.Add(kvp.Key, kvp.Value); } } // Encrypt the property details set and add it to entity properties. byte[] metadataIV = sha256.ComputeHash(CommonUtility.BinaryAppend(encryptionData.ContentEncryptionIV, Encoding.UTF8.GetBytes(string.Join(partitionKey, rowKey, Constants.EncryptionConstants.TableEncryptionPropertyDetails)))); Array.Resize <byte>(ref metadataIV, 16); myAes.IV = metadataIV; using (ICryptoTransform transform = myAes.CreateEncryptor()) { byte[] src = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(encryptionPropertyDetailsSet)); byte[] dest = transform.TransformFinalBlock(src, 0, src.Length); encryptedProperties.Add(Constants.EncryptionConstants.TableEncryptionPropertyDetails, new EntityProperty(dest)); } } } // Add the key details to entity properties. encryptedProperties.Add(Constants.EncryptionConstants.TableEncryptionKeyDetails, new EntityProperty(JsonConvert.SerializeObject(encryptionData))); return(encryptedProperties); }
private static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload) { //User Error Checks if (cryptKey == null || cryptKey.Length != KeyBitSize / 8) { throw new ArgumentException($"Key needs to be {KeyBitSize} bit!", nameof(cryptKey)); } if (authKey == null || authKey.Length != KeyBitSize / 8) { throw new ArgumentException($"Key needs to be {KeyBitSize} bit!", nameof(authKey)); } if (secretMessage == null || secretMessage.Length < 1) { throw new ArgumentException("Secret Message Required!", nameof(secretMessage)); } nonSecretPayload = nonSecretPayload ?? new byte[] { }; using (var aes = new AesManaged { KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { aes.GenerateIV(); var iv = aes.IV; byte[] cipherText; using (var encrypter = aes.CreateEncryptor(cryptKey, iv)) { using (var cipherStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) { using (var binaryWriter = new BinaryWriter(cryptoStream)) binaryWriter.Write(secretMessage); } cipherText = cipherStream.ToArray(); } } using (var hmac = new HMACSHA512(authKey)) { using (var encryptedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(encryptedStream)) { binaryWriter.Write(nonSecretPayload); binaryWriter.Write(iv); binaryWriter.Write(cipherText); binaryWriter.Flush(); var tag = hmac.ComputeHash(encryptedStream.ToArray()); binaryWriter.Write(tag); } return(encryptedStream.ToArray()); } } } }
/// <summary> /// Encrypts one stream to another. /// </summary> /// <param name="decrypted">The decrypted input stream.</param> /// <param name="encrypted">The encrypted output stream.</param> public void EncryptStream(Stream decrypted, Stream encrypted) { Covenant.Requires <ArgumentNullException>(decrypted != null, nameof(decrypted)); Covenant.Requires <ArgumentNullException>(encrypted != null, nameof(encrypted)); aes.GenerateIV(); // Always generate a new IV before encrypting. // Wrap the input and output streams with [RelayStream] instances // so that we can prevent the [CryptoStream] instances from disposing // them (since these don't implement [leaveOpen]). using (var hmac = new HMACSHA512(aes.Key)) { using (var decryptedRelay = new RelayStream(decrypted, leaveOpen: true)) { using (var encryptedRelay = new RelayStream(encrypted, leaveOpen: true)) { long hmacPos; // Write the unencrypted header. using (var writer = new BinaryWriter(encryptedRelay, Encoding.UTF8, leaveOpen: true)) { // Write the magic number and IV to the output stream. writer.Write((int)Magic); writer.Write((short)aes.IV.Length); writer.Write(aes.IV); // Write the HMAC512 length followed by that many zeros // as a placeholder for the computed HMAC. We'll record // the absolute position of these bytes so we can easily // go back and overwrite them with the actual HMAC after // we completed the data encryption. writer.Write((short)hmacZeros.Length); writer.Flush(); // Ensure that the underlying stream position is up-to-date hmacPos = encryptedRelay.Position; writer.Write(hmacZeros); } // Encrypt the input stream to the output while also computing the HMAC. using (var hmacStream = new CryptoStream(encryptedRelay, hmac, CryptoStreamMode.Write)) { using (var encryptor = aes.CreateEncryptor()) { using (var encryptorStream = new CryptoStream(hmacStream, encryptor, CryptoStreamMode.Write)) { // Write the variable length random padding. var paddingLength = random.NextIndex(maxPaddingBytes); var paddingBytes = new byte[paddingLength]; random.NextBytes(paddingBytes); using (var writer = new BinaryWriter(encryptorStream, Encoding.UTF8, leaveOpen: true)) { writer.Write((short)paddingLength); writer.Write(paddingBytes); } // Encrypt the user data: decryptedRelay.CopyTo(encryptorStream); } } } // Go back and persist the computed HMAC. encryptedRelay.Position = hmacPos; Covenant.Assert(hmac.Hash.Length == CryptoHelper.HMAC512ByteCount); encrypted.Write(hmac.Hash); } } } }
internal AesEncryptionResult EncryptWithFileStream(string sourceFilePath, string encryptedFilePath, byte[] key = null, byte[] IV = null, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7, bool deleteSourceFile = false, int kBbufferSize = 4) { if (!File.Exists(sourceFilePath)) { return(new AesEncryptionResult() { Success = false, Message = $"{MessageDictionary.Instance["Common.FileNotFound"]} \"{sourceFilePath}\"." }); } if (string.IsNullOrWhiteSpace(encryptedFilePath)) { return(new AesEncryptionResult() { Success = false, Message = MessageDictionary.Instance["Encryption.EncryptedFilePathError"] }); } var destinationDirectory = Path.GetDirectoryName(encryptedFilePath); if (!Directory.Exists(destinationDirectory)) { return(new AesEncryptionResult() { Success = false, Message = $"{MessageDictionary.Instance["Encryption.DestinationDirectoryNotFound"]} \"{destinationDirectory}\"." }); } _key = key ?? _key; _IV = IV ?? _IV; bool pathsEqual = encryptedFilePath.Equals(sourceFilePath, StringComparison.InvariantCultureIgnoreCase); try { using (var aesManaged = new AesManaged()) { if (_key == null) { aesManaged.GenerateKey(); _key = aesManaged.Key; } else { if (aesManaged.ValidKeySize((_key.Length * 8))) { aesManaged.Key = _key; } else { return(new AesEncryptionResult() { Success = false, Message = $"{MessageDictionary.Instance["Common.InvalidKeySizeError"]} ({(_key.Length * 8)})." }); } } if (_IV == null || _IV.Length == 0) { aesManaged.GenerateIV(); _IV = aesManaged.IV; } else { aesManaged.IV = _IV; } aesManaged.Mode = cipherMode; aesManaged.Padding = paddingMode; using (var encryptor = aesManaged.CreateEncryptor(_key, _IV)) { using (FileStream sourceFs = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (FileStream encryptedFs = File.Open((pathsEqual ? encryptedFilePath + "_tmpcrypt" : encryptedFilePath), FileMode.Create, FileAccess.Write, FileShare.None)) { using (CryptoStream cs = new CryptoStream(encryptedFs, encryptor, CryptoStreamMode.Write)) { //plain.CopyTo(cs); byte[] buffer = new byte[kBbufferSize * 1024]; int read; int percentageDone = 0; while ((read = sourceFs.Read(buffer, 0, buffer.Length)) > 0) { cs.Write(buffer, 0, read); var tmpPercentageDone = (int)(sourceFs.Position * 100 / sourceFs.Length); if (tmpPercentageDone != percentageDone) { percentageDone = tmpPercentageDone; RaiseOnEncryptionProgress(percentageDone, (percentageDone != 100 ? $"Encrypting ({percentageDone}%)..." : $"Encrypted ({percentageDone}%).")); } } } } } } } if (pathsEqual) { CommonMethods.ClearFileAttributes(sourceFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below File.Delete(sourceFilePath); File.Move(encryptedFilePath + "_tmpcrypt", encryptedFilePath); } if (deleteSourceFile && !pathsEqual) { CommonMethods.ClearFileAttributes(sourceFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below File.Delete(sourceFilePath); } //var message = $"File \"{sourceFilePath}\" successfully encrypted to \"{encryptedFilePath}\"."; var message = string.Format(MessageDictionary.Instance["Encryption.FileEncryptSuccess"], sourceFilePath, encryptedFilePath); message += (deleteSourceFile && !pathsEqual ? $"\n{string.Format(MessageDictionary.Instance["Encryption.FileDeleted"], sourceFilePath)}" : ""); return(new AesEncryptionResult() { Success = true, Message = message, Key = _key, IV = _IV, AesCipherMode = (AesCipherMode)cipherMode, PaddingMode = paddingMode }); } catch (Exception ex) { return(new AesEncryptionResult() { Success = false, Message = $"{MessageDictionary.Instance["Encryption.ExceptionError"]}\n{ex.ToString()}" }); } }
/// <summary> /// Use this constructor to perform encryption/decryption with custom options. /// See AESCryptOptions documentation for details. /// </summary> /// <param name="passPhrase"> /// Passphrase (in string format) from which a pseudo-random password will be derived. The derived password will be used to generate the encryption key. /// </param> /// <param name="initVector"> /// Initialization vector (IV). This value is required to encrypt the first block of plaintext data. IV must be exactly 16 ASCII characters long. /// </param> /// <param name="options"> /// A set of customized (or default) options to use for the encryption/decryption: see AESCryptOptions documentation for details. /// </param> public AesCryptoProvider(string passPhrase, string initVector, AesCryptOptions options) { // store the options object locally. this._options = options; // Checks for the correct (or null) size of cryptographic key. if (_options.FixedKeySize.HasValue && _options.FixedKeySize != 128 && _options.FixedKeySize != 192 && _options.FixedKeySize != 256) { throw new NotSupportedException("ERROR: options.FixedKeySize must be NULL (for auto-detect) or have a value of 128, 192 or 256"); } // Initialization vector converted to a byte array. // Salt used for password hashing (to generate the key, not during // encryption) converted to a byte array. // Get bytes of initialization vector. var initVectorBytes = initVector == null ? new byte[0] : Encoding.UTF8.GetBytes(initVector); // Gets the KeySize var keySize = _options.FixedKeySize ?? GetAesKeySize(passPhrase); // Get bytes of password (hashing it or not) byte[] keyBytes; if (_options.PasswordHash == AesHashType.None) { // Convert passPhrase to a byte array keyBytes = Encoding.UTF8.GetBytes(passPhrase); } else { // Get bytes of password hash salt var saltValueBytes = _options.PasswordHashSalt == null ? new byte[0] : Encoding.UTF8.GetBytes(options.PasswordHashSalt); // Generate password, which will be used to derive the key. //var password = new PasswordDeriveBytes( // passPhrase, // saltValueBytes, // _options.PasswordHash.ToString().ToUpper().Replace("-", ""), // _options.PasswordHashIterations); var password = new Rfc2898DeriveBytes(passPhrase, saltValueBytes, _options.PasswordHashIterations, HashAlgorithmName.SHA256); // Convert key to a byte array adjusting the size from bits to bytes. keyBytes = password.GetBytes(keySize / 8); } // Initialize AES key object. var symmetricKey = new AesManaged { Padding = _options.PaddingMode, Mode = (initVectorBytes.Length == 0) ? CipherMode.ECB : CipherMode.CBC }; // Sets the padding mode // Use the unsafe ECB cypher mode (not recommended) if no IV has been provided, otherwise use the more secure CBC mode. // Create the encryptor and decryptor objects, which we will use for cryptographic operations. _encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes); _decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes); }
internal AesEncryptionResult EncryptWithMemoryStream(byte[] sourceData, byte[] key = null, byte[] IV = null, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7) { if (sourceData == null || sourceData.Length == 0) { return(new AesEncryptionResult() { Success = false, Message = MessageDictionary.Instance["Encryption.InputRequired"] }); } _key = key ?? _key; _IV = IV ?? _IV; byte[] encryptedData = null; try { using (AesManaged aesManaged = new AesManaged()) { if (_key == null) { aesManaged.GenerateKey(); _key = aesManaged.Key; } else { if (aesManaged.ValidKeySize((_key.Length * 8))) { aesManaged.Key = _key; } else { return(new AesEncryptionResult() { Success = false, Message = $"{MessageDictionary.Instance["Common.InvalidKeySizeError"]} ({(_key.Length * 8)})." }); } } if (_IV == null) { aesManaged.GenerateIV(); _IV = aesManaged.IV; } else { aesManaged.IV = _IV; } aesManaged.Mode = cipherMode; aesManaged.Padding = paddingMode; using (var encryptor = aesManaged.CreateEncryptor(_key, _IV)) { using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { using (var bw = new BinaryWriter(cs)) { bw.Write(sourceData); } } encryptedData = ms.ToArray(); } } } } catch (Exception ex) { return(new AesEncryptionResult() { Success = false, Message = $"{MessageDictionary.Instance["Encryption.ExceptionError"]}\n{ex.ToString()}" }); } return(new AesEncryptionResult() { Success = true, Message = MessageDictionary.Instance["Encryption.EncryptSuccess"], EncryptedDataBytes = encryptedData, EncryptedDataBase64String = Convert.ToBase64String(encryptedData), Key = _key, IV = _IV, AesCipherMode = (AesCipherMode)cipherMode, PaddingMode = paddingMode }); }
static void Encrypt() { Console.WriteLine("begin to encrypt..."); var aes = new AesManaged(); aes.BlockSize = 128; aes.KeySize = 128; aes.Mode = CipherMode.CBC; aes.Key = Encoding.UTF8.GetBytes(secretKey); aes.Padding = PaddingMode.PKCS7; aes.IV = Encoding.UTF8.GetBytes(secretKey); Console.WriteLine("begin to encrypt 1M file..."); Stopwatch sw = new Stopwatch(); sw.Start(); using (FileStream fout = new FileStream("test1_en.dat", FileMode.Create, FileAccess.Write)) { using (CryptoStream cryptostream = new CryptoStream(fout, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write)) { using (FileStream fin = new FileStream("test1.dat", FileMode.Open, FileAccess.Read)) { fin.CopyTo(cryptostream); } } } sw.Stop(); Console.WriteLine("file encrypt complete, time elapsed:{0} ms", sw.ElapsedMilliseconds); Console.WriteLine("begin to encrypt 100M file..."); sw = new Stopwatch(); sw.Start(); using (FileStream fout = new FileStream("test2_en.dat", FileMode.Create, FileAccess.Write)) { using (CryptoStream cryptostream = new CryptoStream(fout, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write)) { using (FileStream fin = new FileStream("test2.dat", FileMode.Open, FileAccess.Read)) { fin.CopyTo(cryptostream); } } } sw.Stop(); Console.WriteLine("file encrypt complete, time elapsed:{0} ms", sw.ElapsedMilliseconds); Console.WriteLine("begin to encrypt 1G file..."); sw = new Stopwatch(); sw.Start(); using (FileStream fout = new FileStream("test3_en.dat", FileMode.Create, FileAccess.Write)) { using (CryptoStream cryptostream = new CryptoStream(fout, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write)) { using (FileStream fin = new FileStream("test3.dat", FileMode.Open, FileAccess.Read)) { fin.CopyTo(cryptostream); } } } sw.Stop(); Console.WriteLine("file encrypt complete, time elapsed:{0} ms", sw.ElapsedMilliseconds); }
private void ParsingXml(string xml) { XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(xml); //LogWrite(xDoc.OuterXml.ToString()); XmlNodeList xnList = xDoc.SelectNodes("/authdata/http"); //접근할 노드 foreach (XmlNode xn in xnList) { svr.enrmtKey = xn["enrmtKey"].InnerText; // oneM2M 인증 KeyID를 생성하기 위한 Key svr.entityId = xn["entityId"].InnerText; // oneM2M에서 사용하는 단말 ID svr.token = xn["token"].InnerText; // 인증구간 통신을 위해 발급하는 Token } //LogWrite("enrmtKey = " + svr.enrmtKey); //LogWrite("entityId = " + svr.entityId); //LogWrite("token = " + svr.token); lbEnrmtKey.Text = svr.enrmtKey; lbEntityId.Text = svr.entityId; lbToken.Text = svr.token; // EKI값 계산하기 // short uuid구하기 string suuid = svr.entityId.Substring(10, 10); //LogWrite("suuid = " + suuid); // KeyData Base64URL Decoding string output = svr.enrmtKey; output = output.Replace('-', '+'); // 62nd char of encoding output = output.Replace('_', '/'); // 63rd char of encoding switch (output.Length % 4) // Pad with trailing '='s { case 0: break; // No pad chars in this case case 2: output += "=="; break; // Two pad chars case 3: output += "="; break; // One pad char default: throw new ArgumentOutOfRangeException( nameof(svr.enrmtKey), "Illegal base64url string!"); } var converted = Convert.FromBase64String(output); // Standard base64 decoder // keyData로 AES 128비트 비밀키 생성 System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); AesManaged tdes = new AesManaged(); tdes.Key = converted; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform crypt = tdes.CreateEncryptor(); byte[] plain = Encoding.UTF8.GetBytes(suuid); byte[] cipher = crypt.TransformFinalBlock(plain, 0, plain.Length); String enrmtKeyId = Convert.ToBase64String(cipher); enrmtKeyId = enrmtKeyId.Split('=')[0]; // Remove any trailing '='s enrmtKeyId = enrmtKeyId.Replace('+', '-'); // 62nd char of encoding enrmtKeyId = enrmtKeyId.Replace('/', '_'); // 63rd char of encoding lbEnrmtKeyId.Text = enrmtKeyId; svr.enrmtKeyId = enrmtKeyId; //LogWrite("svr.enrmtKeyId = " + svr.enrmtKeyId); }
/// <summary> /// Encrypts an array of bytes and stores the encrypted playload in the specified file path /// </summary> /// <remarks> /// This method is implemented primarily to fascilitate re-encryption of a file when changing certificates /// </remarks> /// <param name="memBytes">The byte array to encrypt</param> /// <param name="cipherText">The file path in which to store the encrypted payload</param> /// <example> /// <code> /// string thumbprint = @"ccdc673c40ebb2a433300c0c8a2ba6f443da5688"; /// <see cref="X509Context"/> certStore = <see cref="X509Context"/>.<see cref="X509Context.UserReadOnly"/>; /// byte[] fileBytes = File.ReadAllBytes(@"C:\data\example.txt"); /// string ciphertextFilePath = @"C:\data\example_encrypted.ctx"; /// /// using (<see cref="X509CryptoAgent"/> agent = new <see cref="X509CryptoAgent"/>(thumbprint, certStore)) /// { /// agent.EncryptFileFromByteArray(fileBytes, ciphertextFilePath); /// } /// </code> /// </example> public void EncryptFileFromByteArray(byte[] memBytes, string cipherText) { using (AesManaged aesManaged = new AesManaged()) { aesManaged.KeySize = CryptoConstants.AESKeySize; aesManaged.BlockSize = CryptoConstants.AESBlockSize; aesManaged.Mode = CipherMode.CBC; using (ICryptoTransform transform = aesManaged.CreateEncryptor()) { byte[] keyEncrypted = publicKey.Encrypt(aesManaged.Key, RSAEncryptionPadding.OaepSHA384); //Contain the length values of the key and IV respectively byte[] KeyLengthIndicator = new byte[CryptoConstants.AESBytes]; byte[] IVLengthIndicator = new byte[CryptoConstants.AESBytes]; int keyLength = keyEncrypted.Length; KeyLengthIndicator = BitConverter.GetBytes(keyLength); int IVLength = aesManaged.IV.Length; IVLengthIndicator = BitConverter.GetBytes(IVLength); using (FileStream outFS = new FileStream(cipherText, FileMode.Create)) { outFS.Write(KeyLengthIndicator, 0, CryptoConstants.AESBytes); outFS.Write(IVLengthIndicator, 0, CryptoConstants.AESBytes); outFS.Write(keyEncrypted, 0, keyLength); outFS.Write(aesManaged.IV, 0, IVLength); using (CryptoStream outStreamEncrypted = new CryptoStream(outFS, transform, CryptoStreamMode.Write)) { int count = 0; int offset = 0; int blockSizeInBytes = aesManaged.BlockSize / CryptoConstants.AESWords; byte[] data = new byte[blockSizeInBytes]; int bytesRead = 0; using (MemoryStream memStream = new MemoryStream(memBytes)) { do { count = memStream.Read(data, 0, blockSizeInBytes); offset += count; outStreamEncrypted.Write(data, 0, count); bytesRead += blockSizeInBytes; }while (count > 0); } outStreamEncrypted.FlushFinalBlock(); outStreamEncrypted.Close(); } outFS.Close(); } } if (!File.Exists(cipherText)) { throw new FileNotFoundException(string.Format("\"{0}\": Ciphertext file not created", cipherText)); } } }
public static byte[] EncryptBytes(byte[] bytes, string password) { try { using (Aes aes = new AesManaged()) { Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, Keys); aes.Key = deriveBytes.GetBytes(128 / 8); aes.IV = aes.Key; using (MemoryStream encryptionStream = new MemoryStream()) { using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { encrypt.Write(bytes, 0, bytes.Length); encrypt.FlushFinalBlock(); } return(encryptionStream.ToArray()); } } } catch { return(null); } }
private void CalEncHash_Click(object sender, EventArgs e) { if (HashAlg.Text == "SHA1") { string inName = EncFile.Text; FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); byte[] HashData; byte[] CypherText; SHA1 sha = new SHA1CryptoServiceProvider(); HashData = sha.ComputeHash(fin); fin.Close(); System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); SendRsaKey = rsa.ToXmlString(true); ARsaKey.Text = SendRsaKey; rsa.FromXmlString(SendRsaKey); CypherText = rsa.Encrypt(HashData, false); EncHash.Text = Convert.ToBase64String(HashData); EncRsaHash.Text = Convert.ToBase64String(CypherText); if (EncAlg.Text == "DES") { DES des = new DESCryptoServiceProvider(); byte[] key = new byte[8]; for (int i = 0; i < 8; i++) { key[i] = (byte)EncKey.Text[i]; } byte[] inputByteArray = Convert.FromBase64String(EncRsaHash.Text); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, key), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } EncAlgHash.Text = Convert.ToBase64String(ms.ToArray()); } else if (EncAlg.Text == "AES") { AesManaged aes = new AesManaged(); byte[] key = new byte[16]; for (int i = 0; i < 16; i++) { key[i] = (byte)EncKey.Text[i]; } byte[] inputByteArray = Convert.FromBase64String(EncRsaHash.Text); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(key, key), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } EncAlgHash.Text = Convert.ToBase64String(ms.ToArray()); } else { MessageBox.Show("请选择加密算法"); } } if (HashAlg.Text == "MD5") { string inName = EncFile.Text; FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); byte[] HashData; byte[] CypherText; MD5 md5 = new MD5CryptoServiceProvider(); HashData = md5.ComputeHash(fin); fin.Close(); System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); SendRsaKey = rsa.ToXmlString(true); ARsaKey.Text = SendRsaKey; rsa.FromXmlString(SendRsaKey); CypherText = rsa.Encrypt(HashData, false); EncHash.Text = Convert.ToBase64String(HashData); EncRsaHash.Text = Convert.ToBase64String(CypherText); if (EncAlg.Text == "DES") { DES des = new DESCryptoServiceProvider(); byte[] key = new byte[8]; for (int i = 0; i < 8; i++) { key[i] = (byte)EncKey.Text[i]; } byte[] inputByteArray = Convert.FromBase64String(EncRsaHash.Text); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, key), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } EncAlgHash.Text = Convert.ToBase64String(ms.ToArray()); } else if (EncAlg.Text == "AES") { AesManaged aes = new AesManaged(); byte[] key = new byte[16]; for (int i = 0; i < 16; i++) { key[i] = (byte)EncKey.Text[i]; } byte[] inputByteArray = Convert.FromBase64String(EncRsaHash.Text); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(key, key), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } EncAlgHash.Text = Convert.ToBase64String(ms.ToArray()); } else { MessageBox.Show("请选择加密算法"); } } }
public static byte[] AES_ECB_ENC(bool encrypt, byte[] cipherData, byte[] key) { try { //RijndaelManaged using (SymmetricAlgorithm rijndaelManaged = new AesManaged { KeySize = 256, BlockSize = 128, Mode = CipherMode.ECB, Padding = PaddingMode.None, Key = key, IV = new byte[16], }) { using (MemoryStream memoryStream = new MemoryStream(cipherData)) using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encrypt ? rijndaelManaged.CreateEncryptor() : rijndaelManaged.CreateDecryptor() , CryptoStreamMode.Read)) { byte[] bx = ReadFully(cryptoStream); return(bx); } } } catch (Exception e) { Console.WriteLine("A Cryptographic error occurred: {0}", e.Message); return(null); } }
/// <summary> /// AES Encryption using HMAC authent. on UTF-8. /// </summary> /// <param name="plain">Plain message</param> /// <param name="cryptKey">Crypt key</param> /// <param name="authKey">Auth key</param> /// <param name="nonSecretPayload">Non-Secret payload</param> /// <returns>Encrypted Message</returns> /// <exception cref="ArgumentException">Argument error</exception> private static byte[] SimpleEncrypt(byte[] plain, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null) { // Check arguments null if (plain == null || plain.Length < 1) { throw new ArgumentException("Need message", "message"); } if (cryptKey == null || cryptKey.Length != KeyBitSize / 8) { throw new ArgumentException(string.Format("Key must be {0} bits", KeyBitSize / 8), "cryptKey"); } if (authKey == null || authKey.Length != KeyBitSize / 8) { throw new ArgumentException(string.Format("Key must be {0} bits", KeyBitSize / 8), "authkey"); } // Non-secret payload optional // If defined left, else right nonSecretPayload = nonSecretPayload ?? new byte[] { }; // Holds encrypted text byte[] encrypted; // Holds iv byte[] iv; // Create AES managed using (AesManaged aes = new AesManaged { KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { // Make IV aes.GenerateIV(); iv = aes.IV; // Create crypto transform and memory stream using (ICryptoTransform encryptor = aes.CreateEncryptor(cryptKey, iv)) using (MemoryStream cipherStream = new MemoryStream()) { // Create crypto stream and binary writer using (CryptoStream csStream = new CryptoStream(cipherStream, encryptor, CryptoStreamMode.Write)) using (BinaryWriter bWriter = new BinaryWriter(csStream)) { // Encrypt data bWriter.Write(plain); } // Get encrypted encrypted = cipherStream.ToArray(); } } // Add authentication // Make MAC and memory stream using (HMACSHA256 hmac = new HMACSHA256(authKey)) using (MemoryStream encryptedStream = new MemoryStream()) { // Make binary writer using (BinaryWriter bWriter = new BinaryWriter(encryptedStream)) { // Write non-secret payload bWriter.Write(nonSecretPayload); // Write iv bWriter.Write(iv); // Write text bWriter.Write(encrypted); // Flusch bWriter.Flush(); // Authenticate byte[] tag = hmac.ComputeHash(encryptedStream.ToArray()); // Write tag bWriter.Write(tag); } // Return memory stream to byte array return(encryptedStream.ToArray()); } }
/// <summary> /// AES Basit Şifreleme /// </summary> /// <param name="secretMessage">Şifrelenecek mesaj</param> /// <param name="cryptKey">Şifreleme anahtarı</param> /// <param name="authKey">Kimlik anahtarı</param> /// <returns> /// Şifreli mesaj /// </returns> /// <exception cref="System.ArgumentException">Şifrelenecek mesaj olmak zorunda</exception> public override string Encrypt(string plainText)//UTF 8 plain text { #region Kontroller if (string.IsNullOrEmpty(plainText)) { throw new ArgumentException("Şifrelenecek mesajı giriniz!", "şifrelecekMesaj"); } //girilen plainText byte array e çevirilir. var byteArray = Encoding.UTF8.GetBytes(plainText); //Kullanıcı hata kontrolleri yapılır if (cryptKey == null || cryptKey.Length != base.GetKeySize() / 8) { throw new ArgumentException(String.Format("Şifreci Anahtar {0} bit olmalı!", base.GetKeySize()), "cryptKey"); } if (authKey == null || authKey.Length != base.GetKeySize() / 8) { throw new ArgumentException(String.Format("Yetki anahtarı {0} bit olmalı!", base.GetKeySize()), "authKey"); } if (byteArray == null || byteArray.Length < 1) { throw new ArgumentException("Şifrelenecek mesajı giriniz!", "şifrelecekMesaj"); } #endregion byte[] cipherText;//byte array tipinden şifreli metnin tutulacağı değişken byte[] iv; using (var aes = new AesManaged { KeySize = base.GetKeySize(), BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { //Simetrik algoritmayı kullanmak için rastgele IV üretilir aes.GenerateIV(); iv = aes.IV; using (var encrypter = aes.CreateEncryptor(cryptKey, iv)) //aes şifreci oluşturulur. using (var cipherStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) using (var binaryWriter = new BinaryWriter(cryptoStream)) { binaryWriter.Write(plainText); } cipherText = cipherStream.ToArray();//burada şifreli mesaj oluşturulur } } //Şifreli mesajı oluşturmak ve kimlik eklemek authentication using (var hmac = new HMACSHA256(authKey)) using (var encryptedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(encryptedStream)) { binaryWriter.Write(new byte[] { }); binaryWriter.Write(iv); binaryWriter.Write(cipherText); binaryWriter.Flush(); //Tüm verilerin kimlik doğrulamasını yap var tag = hmac.ComputeHash(encryptedStream.ToArray()); binaryWriter.Write(tag); } return(Convert.ToBase64String(encryptedStream.ToArray())); } }
public static string EncryptString(string Str, string Password, string Salt) { try { using (Aes aes = new AesManaged()) { Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Password, Encoding.UTF8.GetBytes(Salt)); aes.Key = deriveBytes.GetBytes(128 / 8); aes.IV = aes.Key; using (MemoryStream encryptionStream = new MemoryStream()) { using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { byte[] utfD1 = UTF8Encoding.UTF8.GetBytes(Str); encrypt.Write(utfD1, 0, utfD1.Length); encrypt.FlushFinalBlock(); } return(Convert.ToBase64String(encryptionStream.ToArray())); } } } catch { return(""); } }
/// <summary> /// Note: /// 1. X509Cert includes: name, issuer, md5&sha and a public key /// 2. How they can be parsed and used in secure context /// </summary> static void X509ContentDemonstration() { /// Review how to perform a synmetric encryption: /// - Use managed provider from System.Security namespace /// - Use 32-bit length key /// - Use 16-bit length vector to randomize cipher result (at 1st of block chain) var key = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2 }; var iv = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 }; var content = "abcdefg"; var contentBytes = Encoding.UTF8.GetBytes(content); var cipher = string.Empty; var cipherBytes = new byte[] { }; Action __review = () => { using (var aes = new AesManaged()) { // Encryption var encryptor = aes.CreateEncryptor(key, iv); using (var stream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(contentBytes, 0, contentBytes.Length); } cipherBytes = stream.ToArray(); cipher = Convert.ToBase64String(cipherBytes); } Console.WriteLine(string.Format("{0} => {1}", content, cipher)); // Decryption cipherBytes = Convert.FromBase64String(cipher); var decryptor = aes.CreateDecryptor(key, iv); using (var stream = new MemoryStream(cipherBytes)) { using (var cryptoStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { using (var reader = new StreamReader(cryptoStream)) { content = reader.ReadToEnd(); } } } Console.WriteLine(string.Format("{0} => {1}", cipher, content)); } }; __review(); /// Use windows sdk to create self-signed cert /// - makecert -r -sv test.pvk -n "CN=KTLiang" test.cer /// - pvk2pfx -pvk test.pvk -spc test.cer -pfx test.pfx -po 123 /// - cer: public key file (no private key) /// - pvk: private key file /// - pfx: x509 complete format (public key + private key) var pvkFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.pvk"); var cerFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.cer"); var pfxFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.pfx"); /// Recipient /// - Cert file has been sent from server and received by client /// - Only public key info is included in the cert var clientReceivedCert = new X509Certificate2(cerFile, "123"); var cerRSA = clientReceivedCert.GetRSAPublicKey(); /// Client accepts the cert and raise a challenge to server /// - Use public key to encrypt a text /// - If server is the holder of private key, it should be able to decrypt and show back the content content = "hello, server."; contentBytes = Encoding.UTF8.GetBytes(content); cipherBytes = cerRSA.Encrypt(contentBytes, RSAEncryptionPadding.OaepSHA1); cipher = Convert.ToBase64String(cipherBytes); Console.WriteLine("Challenge: {0} with lengh {1}", cipher, cipherBytes.Length); var serverCert = new X509Certificate2(pfxFile, "123"); var pvkRSA = serverCert.GetRSAPrivateKey(); contentBytes = pvkRSA.Decrypt(cipherBytes, RSAEncryptionPadding.OaepSHA1); content = Encoding.UTF8.GetString(contentBytes); Console.WriteLine(string.Format("Challenge accepted, you just said \"{0}\" (I'm the key owner)", content)); /// Client will nominate an asyn key from now on /// - Using the same mechanism contentBytes = new byte[key.Length + iv.Length]; key.CopyTo(contentBytes, 0); iv.CopyTo(contentBytes, key.Length); content = Convert.ToBase64String(contentBytes); cipherBytes = cerRSA.Encrypt(contentBytes, RSAEncryptionPadding.OaepSHA1); cipher = Convert.ToBase64String(cipherBytes); Console.WriteLine("key planned: {0}", content); contentBytes = pvkRSA.Decrypt(cipherBytes, RSAEncryptionPadding.OaepSHA1); content = Convert.ToBase64String(contentBytes); var serverKey = new byte[key.Length]; var serverIV = new byte[iv.Length]; Array.Copy(contentBytes, serverKey, 32); Array.Copy(contentBytes, 32, serverIV, 0, 16); Console.WriteLine("key confirm: {0}", content); /// Now going to send the detail information text between client and server /// content = "client said: it's a sceret conversation."; contentBytes = Encoding.UTF8.GetBytes(content); /// Instead of using encoding, contentBytes should be the cipherBytes /// created by AesManaged. Becase now key and iv are both known to each parties var hashBytes = SHA1.Create().ComputeHash(contentBytes); var serverSignature = pvkRSA.SignHash(hashBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); /// Client will: /// - Received contentBytes and compute the hash the same way var clientComputedHashBytes = SHA1.Create().ComputeHash(contentBytes); var authenticated = pvkRSA.VerifyHash(clientComputedHashBytes, serverSignature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1); Console.WriteLine(string.Format("Authentication of this content: {0}", authenticated)); /// This marks the end of imitation of SSL under the dispatch of X509-standard PPK info /// - Only private key owner can sigh and declare the content's Confidentiality, Integrity and Availability /// - Public key can continuously used to verify the signature from private key owner /// - If both part must be involved in authentication, exchange of both certs is needed }
public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null) { //User Error Checks if (cryptKey == null || cryptKey.Length != KeyBitSize / 8) { throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "cryptKey"); } if (authKey == null || authKey.Length != KeyBitSize / 8) { throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "authKey"); } if (secretMessage == null || secretMessage.Length < 1) { throw new ArgumentException("Secret Message Required!", "secretMessage"); } //non-secret payload optional nonSecretPayload = nonSecretPayload ?? new byte[] { }; byte[] cipherText; byte[] iv; using (var aes = new AesManaged { KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { //Use random IV aes.GenerateIV(); iv = aes.IV; using (var encrypter = aes.CreateEncryptor(cryptKey, iv)) using (var cipherStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) using (var binaryWriter = new BinaryWriter(cryptoStream)) { //Encrypt Data binaryWriter.Write(secretMessage); } cipherText = cipherStream.ToArray(); } } //Assemble encrypted message and add authentication using (var hmac = new HMACSHA256(authKey)) using (var encryptedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(encryptedStream)) { //Prepend non-secret payload if any binaryWriter.Write(nonSecretPayload); //Prepend IV binaryWriter.Write(iv); //Write Ciphertext binaryWriter.Write(cipherText); binaryWriter.Flush(); //Authenticate all data var tag = hmac.ComputeHash(encryptedStream.ToArray()); //Postpend tag binaryWriter.Write(tag); } return(encryptedStream.ToArray()); } }
static void Main(string[] args) { var password = "******"; var salt = "s@lt"; //generate secret key and IV var rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt)); var algorithm = new AesManaged(); var rgbKey = rgb.GetBytes(algorithm.KeySize / 8); var rgbIV = rgb.GetBytes(algorithm.BlockSize / 8); var bufferstream = new FileStream(".\\encrypted.txt", FileMode.OpenOrCreate); //bufferstream.Write(Encoding.ASCII.GetBytes("YO"), 0, 2); //bufferstream.Close(); var algo = algorithm.CreateEncryptor(rgbKey, rgbIV); var cryptostream = new CryptoStream(bufferstream, algo, CryptoStreamMode.Write); byte[] transform = Encoding.Unicode.GetBytes("secret secret, I've got a secret"); cryptostream.Write(transform, 0, transform.Length); cryptostream.FlushFinalBlock(); cryptostream.Close(); bufferstream.Close(); Console.WriteLine("Text is encrypted"); byte[] decryptedbuffer = new byte[100]; var decalgo = algorithm.CreateDecryptor(rgbKey, rgbIV); var filestream = new FileStream(".\\decrypted.txt", FileMode.OpenOrCreate); var decryptStream = new CryptoStream(filestream, decalgo, CryptoStreamMode.Read); decryptStream.Read(decryptedbuffer, 0, 100); string s = Encoding.Unicode.GetString(decryptedbuffer); Console.WriteLine(s); filestream.Write(Encoding.Unicode.GetBytes(s), 0, s.Length); //decryptStream.FlushFinalBlock(); //decryptStream.Close(); filestream.Close(); //Asymmetric var plaintext = "hello world"; var rawBytes = Encoding.Default.GetBytes(plaintext); var decryptedText = string.Empty; using (var rsaProvider = new RSACryptoServiceProvider()) { var useOaepPadding = true; var encryptedBytes = rsaProvider.Encrypt(rawBytes, useOaepPadding); var decryptedBytes = rsaProvider.Decrypt(rawBytes, useOaepPadding); decryptedText = Encoding.Default.GetString(decryptedBytes); } Console.WriteLine("Asymmetric"); Console.WriteLine(decryptedText); /** asdasd * */ Console.ReadKey(); }