<commit_before>﻿using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using NBitcoin.DataEncoders;

namespace MagicalCryptoWallet.Crypto
{
	// https://stackoverflow.com/a/10177020/2061103
	public static class StringCipher
	{
		// This constant is used to determine the keysize of the encryption algorithm in bits.
		// We divide this by 8 within the code below to get the equivalent number of bytes.
		private const int Keysize = 128;

		// This constant determines the number of iterations for the password bytes generation function.
		private const int DerivationIterations = 1000;

		public static string Encrypt(string plainText, string passPhrase)
		{
			// Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
			// so that the same Salt and IV values can be used when decrypting.  
			var saltStringBytes = Generate128BitsOfRandomEntropy();
			//Console.WriteLine($"saltStringBytes: {Encoders.Hex.EncodeData(saltStringBytes)}");
			//var ivStringBytes = Generate128BitsOfRandomEntropy();
			//Console.WriteLine($"ivStringBytes: {Encoders.Hex.EncodeData(ivStringBytes)}");
			var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
			using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
			{
				var keyBytes = password.GetBytes(Keysize / 8);
				using (var symmetricKey = new AesManaged())
				{
					symmetricKey.GenerateIV();
					symmetricKey.BlockSize = 128;
					symmetricKey.Mode = CipherMode.CBC;
					symmetricKey.Padding = PaddingMode.PKCS7;
					using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, symmetricKey.IV))
					{
						using (var memoryStream = new MemoryStream())
						{
							using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
							{
								cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
								cryptoStream.FlushFinalBlock();
								// Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
								var cipherTextBytes = saltStringBytes;
								cipherTextBytes = cipherTextBytes.Concat(symmetricKey.IV).ToArray();
								cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
								memoryStream.Close();
								cryptoStream.Close();
								return Convert.ToBase64String(cipherTextBytes);
							}
						}
					}
				}
			}
		}

		public static string Decrypt(string cipherText, string passPhrase)
		{
			// Get the complete stream of bytes that represent:
			// [32 bytes of Salt] + [16 bytes of IV] + [n bytes of CipherText]
			var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
			// Get the saltbytes by extracting the first 16 bytes from the supplied cipherText bytes.
			var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
			// Get the IV bytes by extracting the next 16 bytes from the supplied cipherText bytes.
			var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
			// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
			var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

			using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
			{
				var keyBytes = password.GetBytes(Keysize / 8);
				using (var symmetricKey = new AesManaged())
				{
					symmetricKey.IV = ivStringBytes;
					symmetricKey.BlockSize = 128;
					symmetricKey.Mode = CipherMode.CBC;
					symmetricKey.Padding = PaddingMode.PKCS7;
					using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
					{
						using (var memoryStream = new MemoryStream(cipherTextBytes))
						{
							using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
							{
								var plainTextBytes = new byte[cipherTextBytes.Length];
								var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
								memoryStream.Close();
								cryptoStream.Close();
								return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
							}
						}
					}
				}
			}
		}

		// private static int c = 0;
		// private static byte[] Generate128BitsOfRandomEntropy()
		// {
		// 	var s = (c % 2 == 0) 
		// 		? "ad8d01ed34fcd39e30d06dfa3e7dd9f5"
		// 		: "054afcb1e13a0d258ae423ed2f535f3c";
		// 	c++;
		// 	return Encoders.Hex.DecodeData(s);
		// }

		private static byte[] Generate128BitsOfRandomEntropy()
		{
			var randomBytes = new byte[16]; // 16 Bytes will give us 128 bits.
			using (var rngCsp = new RNGCryptoServiceProvider())
			{
				// Fill the array with cryptographically secure random bytes.
				rngCsp.GetBytes(randomBytes);
			}
			return randomBytes;
		}
	}
}
<commit_msg>Small refactoring and clean up<commit_after>﻿using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using NBitcoin.DataEncoders;

namespace MagicalCryptoWallet.Crypto
{
	// https://stackoverflow.com/a/10177020/2061103
	public static class StringCipher
	{
		// This constant is used to determine the keysize of the encryption algorithm in bits.
		// We divide this by 8 within the code below to get the equivalent number of bytes.
		private const int Keysize = 128;

		// This constant determines the number of iterations for the password bytes generation function.
		private const int DerivationIterations = 1000;

		private static AesManaged CreateAES()
		{
			var aes = new AesManaged();
			aes.BlockSize = 128;
			aes.Mode = CipherMode.CBC;
			aes.Padding = PaddingMode.PKCS7;
			return aes;
		}

		public static string Encrypt(string plainText, string passPhrase)
		{
			// Salt is randomly generated each time, but is preprended to encrypted cipher text
			// so that the same Salt value can be used when decrypting.  
			var saltStringBytes = Generate128BitsOfRandomEntropy();

			var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
			using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
			{
				var keyBytes = password.GetBytes(Keysize / 8);
				using (var aes = CreateAES())
				{
					aes.GenerateIV();
					using (var encryptor = aes.CreateEncryptor(keyBytes, aes.IV))
					{
						using (var memoryStream = new MemoryStream())
						{
							memoryStream.Write(saltStringBytes, 0, saltStringBytes.Length);
							memoryStream.Write(aes.IV, 0, aes.IV.Length);
							using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
							{
								cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
								cryptoStream.FlushFinalBlock();
								cryptoStream.Close();
							}
							var cipherTextBytes = memoryStream.ToArray();
							memoryStream.Close();
							return Convert.ToBase64String(cipherTextBytes);
						}
					}
				}
			}
		}

		public static string Decrypt(string cipherText, string passPhrase)
		{
			var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);

			using (var memoryStream = new MemoryStream(cipherTextBytesWithSaltAndIv))
			{
				using (var reader = new BinaryReader(memoryStream))
				{
					var saltStringBytes = reader.ReadBytes(Keysize / 8);

					using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
					{
						var keyBytes = password.GetBytes(Keysize / 8);
						using (var aes = CreateAES())
						{
							var ivStringBytes = reader.ReadBytes(Keysize / 8);
							using (var decryptor = aes.CreateDecryptor(keyBytes, ivStringBytes))
							{
								using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
								{
									var plainTextBytes = new byte[memoryStream.Length - memoryStream.Position];
									var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
									memoryStream.Close();
									cryptoStream.Close();
									return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
								}
							}
						}
					}
				}
			}
		}


		private static byte[] Generate128BitsOfRandomEntropy()
		{
			var randomBytes = new byte[16]; // 16 Bytes will give us 128 bits.
			using (var rngCsp = new RNGCryptoServiceProvider())
			{
				// Fill the array with cryptographically secure random bytes.
				rngCsp.GetBytes(randomBytes);
			}
			return randomBytes;
		}
	}
}

{'fraction_non_alphanumeric': 0.0905046247512001, 'fraction_numerical': 0.021660227139679196, 'mean_word_length': 3.4008243173621846, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4727927', 'n_tokens_mistral': 3353, 'n_tokens_neox': 2489, 'n_words': 674}