private const int derivationIterations = 40000; //TODO change to 100000+ (not exactly 100000) /// <summary> /// Returns AES encrypted string /// </summary> /// <param name="text"></param> /// <param name="key"></param> /// <returns>Encrypted string</returns> public static string Encrypt(this string text, string key) { if (String.IsNullOrEmpty(text)) { throw new ArgumentException("string cannot be null or empty", nameof(text)); } if (String.IsNullOrEmpty(key)) { throw new ArgumentException("string cannot be null or empty", nameof(key)); } // 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 = Generate256BitsOfRandomEntropy(); var ivStringBytes = Generate256BitsOfRandomEntropy(); var plainTextBytes = Encoding.UTF8.GetBytes(text); using var password = new Rfc2898DeriveBytes(key, saltStringBytes, derivationIterations); var keyBytes = password.GetBytes(keySize / 8); var engine = new RijndaelEngine(256); var blockCipher = new CbcBlockCipher(engine); var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); var keyParam = new KeyParameter(keyBytes); var keyParamWithIv = new ParametersWithIV(keyParam, ivStringBytes, 0, 32); cipher.Init(true, keyParamWithIv); var comparisonBytes = new byte[cipher.GetOutputSize(plainTextBytes.Length)]; var length = cipher.ProcessBytes(plainTextBytes, comparisonBytes, 0); cipher.DoFinal(comparisonBytes, length); return(Convert.ToBase64String(saltStringBytes.Concat(ivStringBytes).Concat(comparisonBytes).ToArray())); }
public byte[] EncryptRijndael(byte[] plain, string password) { var engine = new RijndaelEngine(rijndaelKeyBitSize); var encryptorParameters = GenerateParameters(password, rijndaelKeyBitSize); return(Encrypt(plain, engine, encryptorParameters)); }
public byte[] DecryptRijndael(byte[] cipher, string password) { var engine = new RijndaelEngine(rijndaelKeyBitSize); var decryptorParameters = GenerateParameters(password, rijndaelKeyBitSize); return(Decrypt(cipher, engine, decryptorParameters)); }
public 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 = Generate256BitsOfRandomEntropy(); var ivStringBytes = Generate256BitsOfRandomEntropy(); var plainTextBytes = Encoding.UTF8.GetBytes(plainText); using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations)) { var keyBytes = password.GetBytes(Keysize / 8); var engine = new RijndaelEngine(256); var blockCipher = new CbcBlockCipher(engine); var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); var keyParam = new KeyParameter(keyBytes); var keyParamWithIV = new ParametersWithIV(keyParam, ivStringBytes, 0, 32); cipher.Init(true, keyParamWithIV); var comparisonBytes = new byte[cipher.GetOutputSize(plainTextBytes.Length)]; var length = cipher.ProcessBytes(plainTextBytes, comparisonBytes, 0); cipher.DoFinal(comparisonBytes, length); // return Convert.ToBase64String(comparisonBytes); return(Convert.ToBase64String(saltStringBytes.Concat(ivStringBytes).Concat(comparisonBytes).ToArray())); } }
private void Initialize() { rijndael = new RijndaelEngine(); aesInitializationVector = new byte[CRYPTO_BLOCK_SIZE]; int rawLength = 2 * password.Length; byte[] rawPassword = new byte[rawLength + 8]; byte[] passwordBytes = Encoding.UTF8.GetBytes(password); for (int i = 0; i < password.Length; i++) { rawPassword[i * 2] = passwordBytes[i]; rawPassword[i * 2 + 1] = 0; } for (int i = 0; i < salt.Length; i++) { rawPassword[i + rawLength] = salt[i]; } const int noOfRounds = (1 << 18); IList <byte> bytes = new List <byte>(); byte[] digest; //TODO slow code below, find ways to optimize for (int i = 0; i < noOfRounds; i++) { bytes.AddRange(rawPassword); bytes.AddRange(new[] { (byte)i, (byte)(i >> 8), (byte)(i >> CRYPTO_BLOCK_SIZE) }); if (i % (noOfRounds / CRYPTO_BLOCK_SIZE) == 0) { digest = ComputeHash(bytes.ToArray()); aesInitializationVector[i / (noOfRounds / CRYPTO_BLOCK_SIZE)] = digest[19]; } } digest = ComputeHash(bytes.ToArray()); //slow code ends byte[] aesKey = new byte[CRYPTO_BLOCK_SIZE]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { aesKey[i * 4 + j] = (byte) (((digest[i * 4] * 0x1000000) & 0xff000000 | (uint)((digest[i * 4 + 1] * 0x10000) & 0xff0000) | (uint)((digest[i * 4 + 2] * 0x100) & 0xff00) | (uint)(digest[i * 4 + 3] & 0xff)) >> (j * 8)); } } rijndael.Init(false, new KeyParameter(aesKey)); }
private void Initialize() { _rijndael = new RijndaelEngine(); _aesInitializationVector = new byte[CRYPTO_BLOCK_SIZE]; int rawLength = 2 * _password.Length; byte[] rawPassword = new byte[rawLength + 8]; byte[] passwordBytes = Encoding.UTF8.GetBytes(_password); for (int i = 0; i < _password.Length; i++) { rawPassword[i * 2] = passwordBytes[i]; rawPassword[i * 2 + 1] = 0; } for (int i = 0; i < _salt.Length; i++) { rawPassword[i + rawLength] = _salt[i]; } const int noOfRounds = (1 << 18); const int iblock = 3; byte[] digest; byte[] data = new byte[(rawPassword.Length + iblock) * noOfRounds]; //TODO slow code below, find ways to optimize for (int i = 0; i < noOfRounds; i++) { rawPassword.CopyTo(data, i * (rawPassword.Length + iblock)); data[i * (rawPassword.Length + iblock) + rawPassword.Length + 0] = (byte)i; data[i * (rawPassword.Length + iblock) + rawPassword.Length + 1] = (byte)(i >> 8); data[i * (rawPassword.Length + iblock) + rawPassword.Length + 2] = (byte)(i >> CRYPTO_BLOCK_SIZE); if (i % (noOfRounds / CRYPTO_BLOCK_SIZE) == 0) { digest = SHA1.Create().ComputeHash(data, 0, (i + 1) * (rawPassword.Length + iblock)); _aesInitializationVector[i / (noOfRounds / CRYPTO_BLOCK_SIZE)] = digest[19]; } } digest = SHA1.Create().ComputeHash(data); //slow code ends byte[] aesKey = new byte[CRYPTO_BLOCK_SIZE]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { aesKey[i * 4 + j] = (byte) (((digest[i * 4] * 0x1000000) & 0xff000000 | (uint)((digest[i * 4 + 1] * 0x10000) & 0xff0000) | (uint)((digest[i * 4 + 2] * 0x100) & 0xff00) | (uint)(digest[i * 4 + 3] & 0xff)) >> (j * 8)); } } _rijndael.Init(false, new KeyParameter(aesKey)); }
/// <param name="encryptedText">Encrypted string</param> /// <param name="key"></param> /// <returns>Decrypted string</returns> public static string Decrypt(this string encryptedText, string key) { if (String.IsNullOrEmpty(encryptedText)) { throw new ArgumentException("string cannot be null or empty", nameof(encryptedText)); } if (String.IsNullOrEmpty(key)) { throw new ArgumentException("string cannot be null or empty", nameof(key)); } // Get the complete stream of bytes that represent: // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText] var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(encryptedText); // Get the saltBytes by extracting the first 32 bytes from the supplied cipherText bytes. var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(keySize / 8).ToArray(); // Get the IV bytes by extracting the next 32 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(key, saltStringBytes, derivationIterations); var keyBytes = password.GetBytes(keySize / 8); var engine = new RijndaelEngine(256); var blockCipher = new CbcBlockCipher(engine); var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); var keyParam = new KeyParameter(keyBytes); var keyParamWithIv = new ParametersWithIV(keyParam, ivStringBytes, 0, 32); cipher.Init(false, keyParamWithIv); var comparisonBytes = new byte[cipher.GetOutputSize(cipherTextBytes.Length)]; var length = cipher.ProcessBytes(cipherTextBytes, comparisonBytes, 0); cipher.DoFinal(comparisonBytes, length); var nullIndex = comparisonBytes.Length - 1; while (comparisonBytes[nullIndex] == 0) { nullIndex--; } comparisonBytes = comparisonBytes.Take(nullIndex + 1).ToArray(); var result = Encoding.UTF8.GetString(comparisonBytes, 0, comparisonBytes.Length); return(result); }
public void ConstructorSecureString() { string clearText = GenerateClearText(); SecureString key = ToSS(GeneratePassPhrase()); ICryptoEngine engine = new RijndaelEngine(key); string encrypted = engine.Encrypt(clearText); string decrypted = engine.Decrypt(encrypted); Assert.NotEqual(clearText, encrypted); Assert.Equal(clearText, decrypted); }
/// <summary> /// Encrypted the data. /// </summary> /// <param name="data">The data to encrypted.</param> /// <param name="passphrase">The passphrase key used to mask the data.</param> /// <param name="blocksize">The blocksize in bits, must be 128, 192, or 256.</param> /// <returns>The encrypted data; else null.</returns> /// <remarks>The passphrase must be between 0 and 32 bytes in length.</remarks> public byte[] Encrypt(byte[] data, string passphrase, int blocksize = 256) { // Create the key length. byte[] key = GeneratePasswordBytes(passphrase); if (!VerifyKeySize(key)) { return(null); } // Create the key parameters. Key.Crypto.Parameters.KeyParameter keyParameter = new KeyParameter(key); // Initialise the cryptography engine. Key.Crypto.Engines.RijndaelEngine rijndael = new RijndaelEngine(blocksize); rijndael.Init(true, keyParameter); int dataLength = data.Length; int blockSize = rijndael.GetBlockSize(); int modBlockSize = dataLength % blockSize; int blockCount = dataLength / blockSize; // If there is a remained then add en extra block count. if ((modBlockSize) > 0) { // Add one extra block. blockCount++; } // Encrypted data store. byte[] encryptedData = new byte[blockCount * blockSize]; byte[] decryptedData = new byte[blockCount * blockSize]; // Copy the decrypted data. for (int j = 0; j < dataLength; j++) { // Assign the data. decryptedData[j] = data[j]; } // For each block size in the the data. for (int i = 0; i < blockCount; i++) { // Encrypt the block. rijndael.ProcessBlock(decryptedData, (i * blockSize), encryptedData, (i * blockSize)); } // Return the encrypted data. return(encryptedData); }
/// <summary> /// Create the cipher to handle encryption and decryption /// </summary> /// <param name="password">A string containing the password, which will be used /// to derive all our encryption parameters</param> /// <param name="encrypt">A boolean value specifying whether we should go into /// encryption mode (true) or decryption mode (false)</param> /// <returns>A BufferedBlockCipher in the specified mode</returns> /// <exception cref="Exception">Thrown whenever anything bad happens</exception> private static BufferedBlockCipher CreateCipher(string password, bool encrypt) { // I tried a dozen different things, none of which seemed to work // all that well. I finally resorted to doing everyting the Bouncy // Castle way, simply because it brought things a lot closer to being // consistent. Trying to do things entirely within .NET or Java just // wasn't cutting it. There are, however, differences between the // implementations, which are denoted below. try { // Get the password's raw UTF-8 bytes: byte[] pwd = Encoding.UTF8.GetBytes(password); byte[] salt = GenerateSaltFromPassword(password); // From the BC JavaDoc: "Generator for PBE derived keys and IVs as // defined by PKCS 5 V2.0 Scheme 2. This generator uses a SHA-1 // HMac as the calculation function." This is apparently a standard, // which makes my old .NET SecureFile class seem a bit embarrassing. Pkcs5S2ParametersGenerator generator = new Pkcs5S2ParametersGenerator(); // Initialize the generator with our password and salt. Note the // iteration count value. Examples I found around the net set this // as a hex value, but I'm not sure why advantage there is to that. // I changed it to decimal for clarity. 1000 iterations may seem // a bit excessive, and I saw some real sluggishness on the Android // emulator that could be caused by this. In the final program, // this should probably be set in a global app constant. generator.Init(pwd, salt, KEY_ITERATION_COUNT); // Generate our parameters. We want to do AES-256, so we'll set // that as our key size. That also implies a 128-bit IV. Note // that the 2-int method used here is considered deprecated in the // .NET library, which could be a problem in the long term. This // is where .NET and Java diverge in BC; this is the only method // available in Java, and the comparable method is deprecated in // .NET. I'm not sure how this will work going forward. We need // to watch this, as this could be a failure point down the road. ParametersWithIV iv = ((ParametersWithIV)generator.GenerateDerivedParameters(KEY_SIZE, IV_SIZE)); // Create our AES (i.e. Rijndael) engine and create the actual // cipher object from it. We'll use CBC padding. RijndaelEngine engine = new RijndaelEngine(); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine)); // Pick our mode, encryption or decryption: cipher.Init(encrypt, iv); // Return the cipher: return(cipher); } // Don't handle exploding things here; pass the buck to the caller: catch (Exception e) { throw e; } }
public void SetInitVectorString() { string clearText = GenerateClearText(); string key = GeneratePassPhrase(); string init = GenerateInitVector(); ICryptoEngine engine = new RijndaelEngine(key) .SetInitVector(init); string encrypted = engine.Encrypt(clearText); string decrypted = engine.Decrypt(encrypted); Assert.NotEqual(clearText, encrypted); Assert.Equal(clearText, decrypted); }
public static string DecryptString(byte[] message, byte[] key, byte[] iv) { var engine = new RijndaelEngine(256); var blockCipher = new CbcBlockCipher(engine); var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); var keyParam = new KeyParameter(key); var keyParamWithIv = new ParametersWithIV(keyParam, iv, 0, 32); cipher.Init(false, keyParamWithIv); var comparisonBytes = new byte[cipher.GetOutputSize(message.Length)]; var length = cipher.ProcessBytes(message, comparisonBytes, 0); cipher.DoFinal(comparisonBytes, length); return(Encoding.UTF8.GetString(comparisonBytes)); }
/// <summary> /// decrypt data using rijdael /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public byte[] Decrypt(byte[] data, byte[] key, byte[] iv) { this.Check(key, iv); //Set up //AesEngine engine = new AesEngine(); RijndaelEngine engine = new RijndaelEngine(256); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); //Default scheme is PKCS5/PKCS7 KeyParameter keyParam = new KeyParameter(key.SubByte(0, 32)); ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 32); cipher.Init(false, keyParamWithIV); byte[] outputBytes = new byte[cipher.GetOutputSize(data.Length)]; int length = cipher.ProcessBytes(data, outputBytes, 0); cipher.DoFinal(outputBytes, length); //Do the final block return(outputBytes); }
private ICryptoEngine GenerateEngine() { var engine = new RijndaelEngine(txtKey.Text); if (cbxUseKeySize.Checked) { var keySize = EnumerationConversions.GetEnumName<RijndaelKeySize>(cmbKeySize.SelectedItem.ToString()); engine.SetKeySize(keySize); } if (cbxUseInitVector.Checked) { engine.SetInitVector(txtInitVector.Text); } if (cbxUseKeySalt.Checked) { engine.SetSalt(txtSalt.Text); } if (cbxUseRandomSalt.Checked) { engine.SetRandomSaltLength((int)nudSaltMin.Value, (int)nudSaltMax.Value); } if (cbxUsePasswordIterations.Checked) { engine.SetIterations((int)nudIterations.Value); } if (cbxUseEncoding.Checked) { engine.SetEncoding(cmbEncoding.SelectedItem as Encoding); } if (cbxUseHashAlgorithm.Checked) { engine.SetHashAlgorithm((HashType)cmbHashAlgorithm.SelectedItem); } return engine; }
public string Decrypt(string cipherText, string passPhrase) { // Get the complete stream of bytes that represent: // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText] var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText); // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes. var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray(); // Get the IV bytes by extracting the next 32 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); var engine = new RijndaelEngine(256); var blockCipher = new CbcBlockCipher(engine); var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); var keyParam = new KeyParameter(keyBytes); var keyParamWithIV = new ParametersWithIV(keyParam, ivStringBytes, 0, 32); cipher.Init(false, keyParamWithIV); var comparisonBytes = new byte[cipher.GetOutputSize(cipherTextBytes.Length)]; var length = cipher.ProcessBytes(cipherTextBytes, comparisonBytes, 0); cipher.DoFinal(comparisonBytes, length); //cipher.DoFinal(comparisonBytes); //return Convert.ToBase64String(saltStringBytes.Concat(ivStringBytes).Concat(comparisonBytes).ToArray()); var nullIndex = comparisonBytes.Length - 1; while (comparisonBytes[nullIndex] == (byte)0) { nullIndex--; } comparisonBytes = comparisonBytes.Take(nullIndex + 1).ToArray(); var result = Encoding.UTF8.GetString(comparisonBytes, 0, comparisonBytes.Length); return(result); } }
public static string EncryptString(string message, byte[] key, ref string iv) { var rawMessage = Encoding.ASCII.GetBytes(message); var newiv = iv == null?Encoding.ASCII.GetBytes(RandomString(32)) : Convert.FromBase64String(iv); var engine = new RijndaelEngine(256); var blockCipher = new CbcBlockCipher(engine); var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); var keyParam = new KeyParameter(key); var keyParamWithIv = new ParametersWithIV(keyParam, newiv, 0, 32); cipher.Init(true, keyParamWithIv); var comparisonBytes = new byte[cipher.GetOutputSize(rawMessage.Length)]; var length = cipher.ProcessBytes(rawMessage, comparisonBytes, 0); cipher.DoFinal(comparisonBytes, length); iv = Convert.ToBase64String(newiv); return(Convert.ToBase64String(comparisonBytes)); }
public string Encrypt(string text, string keyString, EncryptionAlgorithm algorithm, int keyIndex) { var aes = new RijndaelEngine();// AesEngine(); var blockCipher = new SicBlockCipher(aes); var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); var iv = CreateRandomByteArray(_iVSizeInBytes); var key = HexStringToByteArray(keyString); var keyParam = new KeyParameter(key); cipher.Init(true, new ParametersWithIV(keyParam, iv)); var textAsBytes = Encoding.ASCII.GetBytes(text); var encryptedBytes = new byte[cipher.GetOutputSize(textAsBytes.Length)]; var length = cipher.ProcessBytes(textAsBytes, encryptedBytes, 0); cipher.DoFinal(encryptedBytes, length); var encryptedAsString = ByteArrayToString(encryptedBytes); return($"[{((int)algorithm)},{keyIndex}]{ByteArrayToString(iv)}{encryptedAsString}"); }
public string Decrypt(string cipherText, string keyString, EncryptionAlgorithm algorithm) { var aes = new RijndaelEngine(); var blockCipher = new SicBlockCipher(aes); var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); var ivString = cipherText.Substring(0, _iVSizeInBytes * 2); var ivBytes = HexStringToByteArray(ivString); var cipherNoIV = cipherText.Substring(_iVSizeInBytes * 2, cipherText.Length - _iVSizeInBytes * 2); var cipherBytes = HexStringToByteArray(cipherNoIV); var key = HexStringToByteArray(keyString); var keyParam = new KeyParameter(key); cipher.Init(false, new ParametersWithIV(keyParam, ivBytes)); var decryptedBytes = new byte[cipher.GetOutputSize(cipherBytes.Length)]; var length = cipher.ProcessBytes(cipherBytes, 0, cipherBytes.Length, decryptedBytes, 0); cipher.DoFinal(decryptedBytes, length); return(Encoding.ASCII.GetString(decryptedBytes)); }
public void SetRandomSaltLength() { string clearText = GenerateClearText(); string key = GeneratePassPhrase(); string init = GenerateInitVector(); var minSalt = (byte)DataGenerator.NextInteger(4, 100); var maxSalt = (byte)DataGenerator.NextInteger(100, 250); ICryptoEngine engine = new RijndaelEngine(key) .SetInitVector(init) .SetRandomSaltLength(minSalt, maxSalt); string encrypted = engine.Encrypt(clearText); string decrypted = engine.Decrypt(encrypted); Assert.NotEqual(clearText, encrypted); Assert.Equal(clearText, decrypted); }
public void SetHashAlgorithm_To_Test_Backwards_Compatability() { ICryptoEngine engine = new RijndaelEngine("ggsssdsdgfsdfgagawrgarg345gae5gdsargfsxgzfsga") .SetHashAlgorithm(HashType.SHA1) .SetIterations(1); var plain = engine.Decrypt("ByFZ5i5rMdprzBE/WVoUJQ=="); Assert.Equal("Hello There!!", plain); }
/// <summary> /// Build the engine /// </summary> /// <param name="algorithm">SymmetricBlockAlgorithm enum, algorithm name</param> /// <returns>IBlockCipher with the algorithm Engine</returns> internal IBlockCipher getCipherEngine(SymmetricBlockAlgorithm algorithm) { IBlockCipher engine = null; switch (algorithm) { case SymmetricBlockAlgorithm.AES: engine = new AesEngine(); break; case SymmetricBlockAlgorithm.BLOWFISH: engine = new BlowfishEngine(); break; case SymmetricBlockAlgorithm.CAMELLIA: engine = new CamelliaEngine(); break; case SymmetricBlockAlgorithm.CAST5: engine = new Cast5Engine(); break; case SymmetricBlockAlgorithm.CAST6: engine = new Cast6Engine(); break; case SymmetricBlockAlgorithm.DES: engine = new DesEngine(); break; case SymmetricBlockAlgorithm.TRIPLEDES: engine = new DesEdeEngine(); break; case SymmetricBlockAlgorithm.DSTU7624_128: engine = new Dstu7624Engine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.DSTU7624_128, this.error)); break; case SymmetricBlockAlgorithm.DSTU7624_256: engine = new Dstu7624Engine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.DSTU7624_256, this.error)); break; case SymmetricBlockAlgorithm.DSTU7624_512: engine = new Dstu7624Engine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.DSTU7624_512, this.error)); break; case SymmetricBlockAlgorithm.GOST28147: engine = new Gost28147Engine(); break; case SymmetricBlockAlgorithm.NOEKEON: engine = new NoekeonEngine(); break; case SymmetricBlockAlgorithm.RC2: engine = new RC2Engine(); break; case SymmetricBlockAlgorithm.RC532: engine = new RC532Engine(); break; case SymmetricBlockAlgorithm.RC564: engine = new RC564Engine(); break; case SymmetricBlockAlgorithm.RC6: engine = new RC6Engine(); break; case SymmetricBlockAlgorithm.RIJNDAEL_128: engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_128, this.error)); break; case SymmetricBlockAlgorithm.RIJNDAEL_160: engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_160, this.error)); break; case SymmetricBlockAlgorithm.RIJNDAEL_192: engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_192, this.error)); break; case SymmetricBlockAlgorithm.RIJNDAEL_224: engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_224, this.error)); break; case SymmetricBlockAlgorithm.RIJNDAEL_256: engine = new RijndaelEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.RIJNDAEL_256, this.error)); break; case SymmetricBlockAlgorithm.SEED: engine = new SeedEngine(); break; case SymmetricBlockAlgorithm.SERPENT: engine = new SerpentEngine(); break; case SymmetricBlockAlgorithm.SKIPJACK: engine = new SkipjackEngine(); break; case SymmetricBlockAlgorithm.SM4: engine = new SM4Engine(); break; case SymmetricBlockAlgorithm.TEA: engine = new TeaEngine(); break; case SymmetricBlockAlgorithm.THREEFISH_256: engine = new ThreefishEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.THREEFISH_256, this.error)); break; case SymmetricBlockAlgorithm.THREEFISH_512: engine = new ThreefishEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.THREEFISH_512, this.error)); break; case SymmetricBlockAlgorithm.THREEFISH_1024: engine = new ThreefishEngine(SymmetricBlockAlgorithmUtils.getBlockSize(SymmetricBlockAlgorithm.THREEFISH_1024, this.error)); break; case SymmetricBlockAlgorithm.TWOFISH: engine = new TwofishEngine(); break; case SymmetricBlockAlgorithm.XTEA: engine = new XteaEngine(); break; default: this.error.setError("SB020", "Cipher " + algorithm + " not recognised."); break; } return(engine); }
public void InvalidDecryption() { string randomData = GenerateClearText(); string fake = Convert.ToBase64String(Encoding.UTF8.GetBytes(randomData)); string key = GeneratePassPhrase(); string init = GenerateInitVector(); ICryptoEngine engine = new RijndaelEngine(key) .SetInitVector(init); Assert.Throws<CryptographicException>(delegate { engine.Decrypt(fake); }); }
public void SetEncoding(Encodings encodingType) { Encoding encoding = null; switch (encodingType) { //case Encodings.None: case Encodings.ASCII: encoding = Encoding.ASCII; break; case Encodings.UTF7: encoding = Encoding.UTF7; break; case Encodings.UTF8: encoding = Encoding.UTF8; break; } string clearText = GenerateClearText(); string key = GeneratePassPhrase(); ICryptoEngine engine = new RijndaelEngine(key) .SetEncoding(encoding); string encrypted = engine.Encrypt(clearText); string decrypted = engine.Decrypt(encrypted); Assert.NotEqual(clearText, encrypted); Assert.Equal(clearText, decrypted); }
public void SetPasswordIterations() { string clearText = GenerateClearText(); string key = GeneratePassPhrase(); string init = GenerateInitVector(); var minSalt = (byte)DataGenerator.NextInteger(4, 100); var maxSalt = (byte)DataGenerator.NextInteger(100, 250); string saltKey = GenerateRandomSalt(); var iterations = (byte)DataGenerator.NextInteger(1, 10); ICryptoEngine engine = new RijndaelEngine(key) .SetInitVector(init) .SetRandomSaltLength(minSalt, maxSalt) .SetSalt(saltKey) .SetKeySize(RijndaelKeySize.Key256Bit) .SetIterations(iterations); string encrypted = engine.Encrypt(clearText); string decrypted = engine.Decrypt(encrypted); Assert.NotEqual(clearText, encrypted); Assert.Equal(clearText, decrypted); }
public void SetPasswordIterationsInvalid(int times) { string key = GeneratePassPhrase(); ICryptoEngine engine = new RijndaelEngine(key) .SetIterations(times); Assert.Fail("Should never get here"); }
public void SetSaltSecureStringInvalid() { string key = GeneratePassPhrase(); SecureString salt = null; ICryptoEngine engine = new RijndaelEngine(key) .SetSalt(salt); Assert.Fail("Should never get here"); }
public void SetRandomSaltLengthInvalid(int min, int max) { string key = GeneratePassPhrase(); ICryptoEngine engine = new RijndaelEngine(key) .SetRandomSaltLength(min, max); Assert.Fail("Should never get here"); }
public void Setup() { _settings = new SymmetricCryptographySettings(); _classUnderTest = new RijndaelEngine(_settings); }
public static IBufferedCipher GetCipher( string algorithm) { if (algorithm == null) { throw new ArgumentNullException("algorithm"); } algorithm = algorithm.ToUpper(CultureInfo.InvariantCulture); string aliased = (string)algorithms[algorithm]; if (aliased != null) { algorithm = aliased; } IBasicAgreement iesAgreement = null; if (algorithm == "IES") { iesAgreement = new DHBasicAgreement(); } else if (algorithm == "ECIES") { iesAgreement = new ECDHBasicAgreement(); } if (iesAgreement != null) { return(new BufferedIesCipher( new IesEngine( iesAgreement, new Kdf2BytesGenerator( new Sha1Digest()), new HMac( new Sha1Digest())))); } if (algorithm.StartsWith("PBE")) { switch (algorithm) { case "PBEWITHSHAAND2-KEYTRIPLEDES-CBC": case "PBEWITHSHAAND3-KEYTRIPLEDES-CBC": return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new DesEdeEngine()))); case "PBEWITHSHAAND128BITRC2-CBC": case "PBEWITHSHAAND40BITRC2-CBC": return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new RC2Engine()))); case "PBEWITHSHAAND128BITAES-CBC-BC": case "PBEWITHSHAAND192BITAES-CBC-BC": case "PBEWITHSHAAND256BITAES-CBC-BC": case "PBEWITHSHA256AND128BITAES-CBC-BC": case "PBEWITHSHA256AND192BITAES-CBC-BC": case "PBEWITHSHA256AND256BITAES-CBC-BC": case "PBEWITHMD5AND128BITAES-CBC-OPENSSL": case "PBEWITHMD5AND192BITAES-CBC-OPENSSL": case "PBEWITHMD5AND256BITAES-CBC-OPENSSL": return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new AesFastEngine()))); case "PBEWITHSHA1ANDDES-CBC": return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new DesEngine()))); case "PBEWITHSHA1ANDRC2-CBC": return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new RC2Engine()))); } } string[] parts = algorithm.Split('/'); IBlockCipher blockCipher = null; IAsymmetricBlockCipher asymBlockCipher = null; IStreamCipher streamCipher = null; switch (parts[0]) { case "AES": blockCipher = new AesFastEngine(); break; case "ARC4": streamCipher = new RC4Engine(); break; case "BLOWFISH": blockCipher = new BlowfishEngine(); break; case "CAMELLIA": blockCipher = new CamelliaEngine(); break; case "CAST5": blockCipher = new Cast5Engine(); break; case "CAST6": blockCipher = new Cast6Engine(); break; case "DES": blockCipher = new DesEngine(); break; case "DESEDE": blockCipher = new DesEdeEngine(); break; case "ELGAMAL": asymBlockCipher = new ElGamalEngine(); break; case "GOST28147": blockCipher = new Gost28147Engine(); break; case "HC128": streamCipher = new HC128Engine(); break; case "HC256": streamCipher = new HC256Engine(); break; #if INCLUDE_IDEA case "IDEA": blockCipher = new IdeaEngine(); break; #endif case "NOEKEON": blockCipher = new NoekeonEngine(); break; case "PBEWITHSHAAND128BITRC4": case "PBEWITHSHAAND40BITRC4": streamCipher = new RC4Engine(); break; case "RC2": blockCipher = new RC2Engine(); break; case "RC5": blockCipher = new RC532Engine(); break; case "RC5-64": blockCipher = new RC564Engine(); break; case "RC6": blockCipher = new RC6Engine(); break; case "RIJNDAEL": blockCipher = new RijndaelEngine(); break; case "RSA": asymBlockCipher = new RsaBlindedEngine(); break; case "SALSA20": streamCipher = new Salsa20Engine(); break; case "SEED": blockCipher = new SeedEngine(); break; case "SERPENT": blockCipher = new SerpentEngine(); break; case "SKIPJACK": blockCipher = new SkipjackEngine(); break; case "TEA": blockCipher = new TeaEngine(); break; case "TWOFISH": blockCipher = new TwofishEngine(); break; case "VMPC": streamCipher = new VmpcEngine(); break; case "VMPC-KSA3": streamCipher = new VmpcKsa3Engine(); break; case "XTEA": blockCipher = new XteaEngine(); break; default: throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } if (streamCipher != null) { if (parts.Length > 1) { throw new ArgumentException("Modes and paddings not used for stream ciphers"); } return(new BufferedStreamCipher(streamCipher)); } bool cts = false; bool padded = true; IBlockCipherPadding padding = null; IAeadBlockCipher aeadBlockCipher = null; if (parts.Length > 2) { if (streamCipher != null) { throw new ArgumentException("Paddings not used for stream ciphers"); } switch (parts[2]) { case "NOPADDING": padded = false; break; case "": case "RAW": break; case "ISO10126PADDING": case "ISO10126D2PADDING": case "ISO10126-2PADDING": padding = new ISO10126d2Padding(); break; case "ISO7816-4PADDING": case "ISO9797-1PADDING": padding = new ISO7816d4Padding(); break; case "ISO9796-1": case "ISO9796-1PADDING": asymBlockCipher = new ISO9796d1Encoding(asymBlockCipher); break; case "OAEP": case "OAEPPADDING": asymBlockCipher = new OaepEncoding(asymBlockCipher); break; case "OAEPWITHMD5ANDMGF1PADDING": asymBlockCipher = new OaepEncoding(asymBlockCipher, new MD5Digest()); break; case "OAEPWITHSHA1ANDMGF1PADDING": case "OAEPWITHSHA-1ANDMGF1PADDING": asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha1Digest()); break; case "OAEPWITHSHA224ANDMGF1PADDING": case "OAEPWITHSHA-224ANDMGF1PADDING": asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha224Digest()); break; case "OAEPWITHSHA256ANDMGF1PADDING": case "OAEPWITHSHA-256ANDMGF1PADDING": asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha256Digest()); break; case "OAEPWITHSHA384ANDMGF1PADDING": case "OAEPWITHSHA-384ANDMGF1PADDING": asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha384Digest()); break; case "OAEPWITHSHA512ANDMGF1PADDING": case "OAEPWITHSHA-512ANDMGF1PADDING": asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha512Digest()); break; case "PKCS1": case "PKCS1PADDING": asymBlockCipher = new Pkcs1Encoding(asymBlockCipher); break; case "PKCS5": case "PKCS5PADDING": case "PKCS7": case "PKCS7PADDING": // NB: Padding defaults to Pkcs7Padding already break; case "TBCPADDING": padding = new TbcPadding(); break; case "WITHCTS": cts = true; break; case "X9.23PADDING": case "X923PADDING": padding = new X923Padding(); break; case "ZEROBYTEPADDING": padding = new ZeroBytePadding(); break; default: throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } } string mode = ""; if (parts.Length > 1) { mode = parts[1]; int di = GetDigitIndex(mode); string modeName = di >= 0 ? mode.Substring(0, di) : mode; switch (modeName) { case "": case "ECB": case "NONE": break; case "CBC": blockCipher = new CbcBlockCipher(blockCipher); break; case "CCM": aeadBlockCipher = new CcmBlockCipher(blockCipher); break; case "CFB": { int bits = (di < 0) ? 8 * blockCipher.GetBlockSize() : int.Parse(mode.Substring(di)); blockCipher = new CfbBlockCipher(blockCipher, bits); break; } case "CTR": blockCipher = new SicBlockCipher(blockCipher); break; case "CTS": cts = true; blockCipher = new CbcBlockCipher(blockCipher); break; case "EAX": aeadBlockCipher = new EaxBlockCipher(blockCipher); break; case "GCM": aeadBlockCipher = new GcmBlockCipher(blockCipher); break; case "GOFB": blockCipher = new GOfbBlockCipher(blockCipher); break; case "OFB": { int bits = (di < 0) ? 8 * blockCipher.GetBlockSize() : int.Parse(mode.Substring(di)); blockCipher = new OfbBlockCipher(blockCipher, bits); break; } case "OPENPGPCFB": blockCipher = new OpenPgpCfbBlockCipher(blockCipher); break; case "SIC": if (blockCipher.GetBlockSize() < 16) { throw new ArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)"); } blockCipher = new SicBlockCipher(blockCipher); break; default: throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } } if (aeadBlockCipher != null) { if (cts) { throw new SecurityUtilityException("CTS mode not valid for AEAD ciphers."); } if (padded && parts.Length > 1 && parts[2] != "") { throw new SecurityUtilityException("Bad padding specified for AEAD cipher."); } return(new BufferedAeadBlockCipher(aeadBlockCipher)); } if (blockCipher != null) { if (cts) { return(new CtsBlockCipher(blockCipher)); } if (!padded || blockCipher.IsPartialBlockOkay) { return(new BufferedBlockCipher(blockCipher)); } if (padding != null) { return(new PaddedBufferedBlockCipher(blockCipher, padding)); } return(new PaddedBufferedBlockCipher(blockCipher)); } if (asymBlockCipher != null) { return(new BufferedAsymmetricBlockCipher(asymBlockCipher)); } throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); }
public void InvalidDecryption() { string randomData = GenerateClearText(); string fake = Convert.ToBase64String(Encoding.UTF8.GetBytes(randomData)); string key = GeneratePassPhrase(); string init = GenerateInitVector(); ICryptoEngine engine = new RijndaelEngine(key) .SetInitVector(init); engine.Decrypt(fake); Assert.Fail("Should never get here"); }
public void SetInitVectorStringInvalid(string invalidValue) { string key = GeneratePassPhrase(); ICryptoEngine engine = new RijndaelEngine(key) .SetInitVector(invalidValue); Assert.Fail("Should never get here"); }
public void SetInitVectorSecureStringInvalid(string invalidValue) { string key = GeneratePassPhrase(); SecureString invalidSecureString = string.IsNullOrEmpty(invalidValue) ? null : ToSS(invalidValue); ICryptoEngine engine = new RijndaelEngine(key) .SetInitVector(invalidSecureString); Assert.Fail("Should never get here"); }
public static IBufferedCipher GetCipher( string algorithm) { if (algorithm == null) { throw new ArgumentNullException("algorithm"); } algorithm = Platform.ToUpperInvariant(algorithm); { string aliased = (string)algorithms[algorithm]; if (aliased != null) { algorithm = aliased; } } IBasicAgreement iesAgreement = null; if (algorithm == "IES") { iesAgreement = new DHBasicAgreement(); } else if (algorithm == "ECIES") { iesAgreement = new ECDHBasicAgreement(); } if (iesAgreement != null) { return(new BufferedIesCipher( new IesEngine( iesAgreement, new Kdf2BytesGenerator( new Sha1Digest()), new HMac( new Sha1Digest())))); } if (Platform.StartsWith(algorithm, "PBE")) { if (Platform.EndsWith(algorithm, "-CBC")) { if (algorithm == "PBEWITHSHA1ANDDES-CBC") { return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new DesEngine()))); } else if (algorithm == "PBEWITHSHA1ANDRC2-CBC") { return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new RC2Engine()))); } else if (Strings.IsOneOf(algorithm, "PBEWITHSHAAND2-KEYTRIPLEDES-CBC", "PBEWITHSHAAND3-KEYTRIPLEDES-CBC")) { return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new DesEdeEngine()))); } else if (Strings.IsOneOf(algorithm, "PBEWITHSHAAND128BITRC2-CBC", "PBEWITHSHAAND40BITRC2-CBC")) { return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new RC2Engine()))); } } else if (Platform.EndsWith(algorithm, "-BC") || Platform.EndsWith(algorithm, "-OPENSSL")) { if (Strings.IsOneOf(algorithm, "PBEWITHSHAAND128BITAES-CBC-BC", "PBEWITHSHAAND192BITAES-CBC-BC", "PBEWITHSHAAND256BITAES-CBC-BC", "PBEWITHSHA256AND128BITAES-CBC-BC", "PBEWITHSHA256AND192BITAES-CBC-BC", "PBEWITHSHA256AND256BITAES-CBC-BC", "PBEWITHMD5AND128BITAES-CBC-OPENSSL", "PBEWITHMD5AND192BITAES-CBC-OPENSSL", "PBEWITHMD5AND256BITAES-CBC-OPENSSL")) { return(new PaddedBufferedBlockCipher( new CbcBlockCipher(new AesFastEngine()))); } } } string[] parts = algorithm.Split('/'); IBlockCipher blockCipher = null; IAsymmetricBlockCipher asymBlockCipher = null; IStreamCipher streamCipher = null; string algorithmName = parts[0]; { string aliased = (string)algorithms[algorithmName]; if (aliased != null) { algorithmName = aliased; } } CipherAlgorithm cipherAlgorithm; try { cipherAlgorithm = (CipherAlgorithm)Enums.GetEnumValue(typeof(CipherAlgorithm), algorithmName); } catch (ArgumentException) { throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } switch (cipherAlgorithm) { case CipherAlgorithm.AES: blockCipher = new AesFastEngine(); break; case CipherAlgorithm.ARC4: streamCipher = new RC4Engine(); break; case CipherAlgorithm.BLOWFISH: blockCipher = new BlowfishEngine(); break; case CipherAlgorithm.CAMELLIA: blockCipher = new CamelliaEngine(); break; case CipherAlgorithm.CAST5: blockCipher = new Cast5Engine(); break; case CipherAlgorithm.CAST6: blockCipher = new Cast6Engine(); break; case CipherAlgorithm.DES: blockCipher = new DesEngine(); break; case CipherAlgorithm.DESEDE: blockCipher = new DesEdeEngine(); break; case CipherAlgorithm.ELGAMAL: asymBlockCipher = new ElGamalEngine(); break; case CipherAlgorithm.GOST28147: blockCipher = new Gost28147Engine(); break; case CipherAlgorithm.HC128: streamCipher = new HC128Engine(); break; case CipherAlgorithm.HC256: streamCipher = new HC256Engine(); break; case CipherAlgorithm.IDEA: blockCipher = new IdeaEngine(); break; case CipherAlgorithm.NOEKEON: blockCipher = new NoekeonEngine(); break; case CipherAlgorithm.PBEWITHSHAAND128BITRC4: case CipherAlgorithm.PBEWITHSHAAND40BITRC4: streamCipher = new RC4Engine(); break; case CipherAlgorithm.RC2: blockCipher = new RC2Engine(); break; case CipherAlgorithm.RC5: blockCipher = new RC532Engine(); break; case CipherAlgorithm.RC5_64: blockCipher = new RC564Engine(); break; case CipherAlgorithm.RC6: blockCipher = new RC6Engine(); break; case CipherAlgorithm.RIJNDAEL: blockCipher = new RijndaelEngine(); break; case CipherAlgorithm.RSA: asymBlockCipher = new RsaBlindedEngine(); break; case CipherAlgorithm.SALSA20: streamCipher = new Salsa20Engine(); break; case CipherAlgorithm.SEED: blockCipher = new SeedEngine(); break; case CipherAlgorithm.SERPENT: blockCipher = new SerpentEngine(); break; case CipherAlgorithm.SKIPJACK: blockCipher = new SkipjackEngine(); break; case CipherAlgorithm.TEA: blockCipher = new TeaEngine(); break; case CipherAlgorithm.THREEFISH_256: blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_256); break; case CipherAlgorithm.THREEFISH_512: blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_512); break; case CipherAlgorithm.THREEFISH_1024: blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_1024); break; case CipherAlgorithm.TNEPRES: blockCipher = new TnepresEngine(); break; case CipherAlgorithm.TWOFISH: blockCipher = new TwofishEngine(); break; case CipherAlgorithm.VMPC: streamCipher = new VmpcEngine(); break; case CipherAlgorithm.VMPC_KSA3: streamCipher = new VmpcKsa3Engine(); break; case CipherAlgorithm.XTEA: blockCipher = new XteaEngine(); break; default: throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } if (streamCipher != null) { if (parts.Length > 1) { throw new ArgumentException("Modes and paddings not used for stream ciphers"); } return(new BufferedStreamCipher(streamCipher)); } bool cts = false; bool padded = true; IBlockCipherPadding padding = null; IAeadBlockCipher aeadBlockCipher = null; if (parts.Length > 2) { if (streamCipher != null) { throw new ArgumentException("Paddings not used for stream ciphers"); } string paddingName = parts[2]; CipherPadding cipherPadding; if (paddingName == "") { cipherPadding = CipherPadding.RAW; } else if (paddingName == "X9.23PADDING") { cipherPadding = CipherPadding.X923PADDING; } else { try { cipherPadding = (CipherPadding)Enums.GetEnumValue(typeof(CipherPadding), paddingName); } catch (ArgumentException) { throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } } switch (cipherPadding) { case CipherPadding.NOPADDING: padded = false; break; case CipherPadding.RAW: break; case CipherPadding.ISO10126PADDING: case CipherPadding.ISO10126D2PADDING: case CipherPadding.ISO10126_2PADDING: padding = new ISO10126d2Padding(); break; case CipherPadding.ISO7816_4PADDING: case CipherPadding.ISO9797_1PADDING: padding = new ISO7816d4Padding(); break; case CipherPadding.ISO9796_1: case CipherPadding.ISO9796_1PADDING: asymBlockCipher = new ISO9796d1Encoding(asymBlockCipher); break; case CipherPadding.OAEP: case CipherPadding.OAEPPADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher); break; case CipherPadding.OAEPWITHMD5ANDMGF1PADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher, new MD5Digest()); break; case CipherPadding.OAEPWITHSHA1ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_1ANDMGF1PADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha1Digest()); break; case CipherPadding.OAEPWITHSHA224ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_224ANDMGF1PADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha224Digest()); break; case CipherPadding.OAEPWITHSHA256ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_256ANDMGF1PADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha256Digest()); break; case CipherPadding.OAEPWITHSHA384ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_384ANDMGF1PADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha384Digest()); break; case CipherPadding.OAEPWITHSHA512ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_512ANDMGF1PADDING: asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha512Digest()); break; case CipherPadding.PKCS1: case CipherPadding.PKCS1PADDING: asymBlockCipher = new Pkcs1Encoding(asymBlockCipher); break; case CipherPadding.PKCS5: case CipherPadding.PKCS5PADDING: case CipherPadding.PKCS7: case CipherPadding.PKCS7PADDING: padding = new Pkcs7Padding(); break; case CipherPadding.TBCPADDING: padding = new TbcPadding(); break; case CipherPadding.WITHCTS: cts = true; break; case CipherPadding.X923PADDING: padding = new X923Padding(); break; case CipherPadding.ZEROBYTEPADDING: padding = new ZeroBytePadding(); break; default: throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } } string mode = ""; if (parts.Length > 1) { mode = parts[1]; int di = GetDigitIndex(mode); string modeName = di >= 0 ? mode.Substring(0, di) : mode; try { CipherMode cipherMode = modeName == "" ? CipherMode.NONE : (CipherMode)Enums.GetEnumValue(typeof(CipherMode), modeName); switch (cipherMode) { case CipherMode.ECB: case CipherMode.NONE: break; case CipherMode.CBC: blockCipher = new CbcBlockCipher(blockCipher); break; case CipherMode.CCM: aeadBlockCipher = new CcmBlockCipher(blockCipher); break; case CipherMode.CFB: { int bits = (di < 0) ? 8 * blockCipher.GetBlockSize() : int.Parse(mode.Substring(di)); blockCipher = new CfbBlockCipher(blockCipher, bits); break; } case CipherMode.CTR: blockCipher = new SicBlockCipher(blockCipher); break; case CipherMode.CTS: cts = true; blockCipher = new CbcBlockCipher(blockCipher); break; case CipherMode.EAX: aeadBlockCipher = new EaxBlockCipher(blockCipher); break; case CipherMode.GCM: aeadBlockCipher = new GcmBlockCipher(blockCipher); break; case CipherMode.GOFB: blockCipher = new GOfbBlockCipher(blockCipher); break; case CipherMode.OCB: aeadBlockCipher = new OcbBlockCipher(blockCipher, CreateBlockCipher(cipherAlgorithm)); break; case CipherMode.OFB: { int bits = (di < 0) ? 8 * blockCipher.GetBlockSize() : int.Parse(mode.Substring(di)); blockCipher = new OfbBlockCipher(blockCipher, bits); break; } case CipherMode.OPENPGPCFB: blockCipher = new OpenPgpCfbBlockCipher(blockCipher); break; case CipherMode.SIC: if (blockCipher.GetBlockSize() < 16) { throw new ArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)"); } blockCipher = new SicBlockCipher(blockCipher); break; default: throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } } catch (ArgumentException) { throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } } if (aeadBlockCipher != null) { if (cts) { throw new SecurityUtilityException("CTS mode not valid for AEAD ciphers."); } if (padded && parts.Length > 2 && parts[2] != "") { throw new SecurityUtilityException("Bad padding specified for AEAD cipher."); } return(new BufferedAeadBlockCipher(aeadBlockCipher)); } if (blockCipher != null) { if (cts) { return(new CtsBlockCipher(blockCipher)); } if (padding != null) { return(new PaddedBufferedBlockCipher(blockCipher, padding)); } if (!padded || blockCipher.IsPartialBlockOkay) { return(new BufferedBlockCipher(blockCipher)); } return(new PaddedBufferedBlockCipher(blockCipher)); } if (asymBlockCipher != null) { return(new BufferedAsymmetricBlockCipher(asymBlockCipher)); } throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); }
public static IBufferedCipher GetCipher(string algorithm) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0469: Unknown result type (might be due to invalid IL or missing references) //IL_0495: Unknown result type (might be due to invalid IL or missing references) //IL_07f1: Unknown result type (might be due to invalid IL or missing references) if (algorithm == null) { throw new ArgumentNullException("algorithm"); } algorithm = Platform.ToUpperInvariant(algorithm); string text = (string)algorithms.get_Item((object)algorithm); if (text != null) { algorithm = text; } IBasicAgreement basicAgreement = null; if (algorithm == "IES") { basicAgreement = new DHBasicAgreement(); } else if (algorithm == "ECIES") { basicAgreement = new ECDHBasicAgreement(); } if (basicAgreement != null) { return(new BufferedIesCipher(new IesEngine(basicAgreement, new Kdf2BytesGenerator(new Sha1Digest()), new HMac(new Sha1Digest())))); } if (Platform.StartsWith(algorithm, "PBE")) { if (Platform.EndsWith(algorithm, "-CBC")) { if (algorithm == "PBEWITHSHA1ANDDES-CBC") { return(new PaddedBufferedBlockCipher(new CbcBlockCipher(new DesEngine()))); } if (algorithm == "PBEWITHSHA1ANDRC2-CBC") { return(new PaddedBufferedBlockCipher(new CbcBlockCipher(new RC2Engine()))); } if (Strings.IsOneOf(algorithm, "PBEWITHSHAAND2-KEYTRIPLEDES-CBC", "PBEWITHSHAAND3-KEYTRIPLEDES-CBC")) { return(new PaddedBufferedBlockCipher(new CbcBlockCipher(new DesEdeEngine()))); } if (Strings.IsOneOf(algorithm, "PBEWITHSHAAND128BITRC2-CBC", "PBEWITHSHAAND40BITRC2-CBC")) { return(new PaddedBufferedBlockCipher(new CbcBlockCipher(new RC2Engine()))); } } else if ((Platform.EndsWith(algorithm, "-BC") || Platform.EndsWith(algorithm, "-OPENSSL")) && Strings.IsOneOf(algorithm, "PBEWITHSHAAND128BITAES-CBC-BC", "PBEWITHSHAAND192BITAES-CBC-BC", "PBEWITHSHAAND256BITAES-CBC-BC", "PBEWITHSHA256AND128BITAES-CBC-BC", "PBEWITHSHA256AND192BITAES-CBC-BC", "PBEWITHSHA256AND256BITAES-CBC-BC", "PBEWITHMD5AND128BITAES-CBC-OPENSSL", "PBEWITHMD5AND192BITAES-CBC-OPENSSL", "PBEWITHMD5AND256BITAES-CBC-OPENSSL")) { return(new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesFastEngine()))); } } string[] array = algorithm.Split(new char[1] { '/' }); IBlockCipher blockCipher = null; IAsymmetricBlockCipher asymmetricBlockCipher = null; IStreamCipher streamCipher = null; string text2 = array[0]; string text3 = (string)algorithms.get_Item((object)text2); if (text3 != null) { text2 = text3; } CipherAlgorithm cipherAlgorithm; try { cipherAlgorithm = (CipherAlgorithm)Enums.GetEnumValue(typeof(CipherAlgorithm), text2); } catch (ArgumentException) { throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } switch (cipherAlgorithm) { case CipherAlgorithm.AES: blockCipher = new AesFastEngine(); break; case CipherAlgorithm.ARC4: streamCipher = new RC4Engine(); break; case CipherAlgorithm.BLOWFISH: blockCipher = new BlowfishEngine(); break; case CipherAlgorithm.CAMELLIA: blockCipher = new CamelliaEngine(); break; case CipherAlgorithm.CAST5: blockCipher = new Cast5Engine(); break; case CipherAlgorithm.CAST6: blockCipher = new Cast6Engine(); break; case CipherAlgorithm.DES: blockCipher = new DesEngine(); break; case CipherAlgorithm.DESEDE: blockCipher = new DesEdeEngine(); break; case CipherAlgorithm.ELGAMAL: asymmetricBlockCipher = new ElGamalEngine(); break; case CipherAlgorithm.GOST28147: blockCipher = new Gost28147Engine(); break; case CipherAlgorithm.HC128: streamCipher = new HC128Engine(); break; case CipherAlgorithm.HC256: streamCipher = new HC256Engine(); break; case CipherAlgorithm.IDEA: blockCipher = new IdeaEngine(); break; case CipherAlgorithm.NOEKEON: blockCipher = new NoekeonEngine(); break; case CipherAlgorithm.PBEWITHSHAAND128BITRC4: case CipherAlgorithm.PBEWITHSHAAND40BITRC4: streamCipher = new RC4Engine(); break; case CipherAlgorithm.RC2: blockCipher = new RC2Engine(); break; case CipherAlgorithm.RC5: blockCipher = new RC532Engine(); break; case CipherAlgorithm.RC5_64: blockCipher = new RC564Engine(); break; case CipherAlgorithm.RC6: blockCipher = new RC6Engine(); break; case CipherAlgorithm.RIJNDAEL: blockCipher = new RijndaelEngine(); break; case CipherAlgorithm.RSA: asymmetricBlockCipher = new RsaBlindedEngine(); break; case CipherAlgorithm.SALSA20: streamCipher = new Salsa20Engine(); break; case CipherAlgorithm.SEED: blockCipher = new SeedEngine(); break; case CipherAlgorithm.SERPENT: blockCipher = new SerpentEngine(); break; case CipherAlgorithm.SKIPJACK: blockCipher = new SkipjackEngine(); break; case CipherAlgorithm.TEA: blockCipher = new TeaEngine(); break; case CipherAlgorithm.THREEFISH_256: blockCipher = new ThreefishEngine(256); break; case CipherAlgorithm.THREEFISH_512: blockCipher = new ThreefishEngine(512); break; case CipherAlgorithm.THREEFISH_1024: blockCipher = new ThreefishEngine(1024); break; case CipherAlgorithm.TNEPRES: blockCipher = new TnepresEngine(); break; case CipherAlgorithm.TWOFISH: blockCipher = new TwofishEngine(); break; case CipherAlgorithm.VMPC: streamCipher = new VmpcEngine(); break; case CipherAlgorithm.VMPC_KSA3: streamCipher = new VmpcKsa3Engine(); break; case CipherAlgorithm.XTEA: blockCipher = new XteaEngine(); break; default: throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } if (streamCipher != null) { if (array.Length > 1) { throw new ArgumentException("Modes and paddings not used for stream ciphers"); } return(new BufferedStreamCipher(streamCipher)); } bool flag = false; bool flag2 = true; IBlockCipherPadding blockCipherPadding = null; IAeadBlockCipher aeadBlockCipher = null; if (array.Length > 2) { if (streamCipher != null) { throw new ArgumentException("Paddings not used for stream ciphers"); } string text4 = array[2]; CipherPadding cipherPadding; if (text4 == "") { cipherPadding = CipherPadding.RAW; } else if (text4 == "X9.23PADDING") { cipherPadding = CipherPadding.X923PADDING; } else { try { cipherPadding = (CipherPadding)Enums.GetEnumValue(typeof(CipherPadding), text4); } catch (ArgumentException) { throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } } switch (cipherPadding) { case CipherPadding.NOPADDING: flag2 = false; break; case CipherPadding.ISO10126PADDING: case CipherPadding.ISO10126D2PADDING: case CipherPadding.ISO10126_2PADDING: blockCipherPadding = new ISO10126d2Padding(); break; case CipherPadding.ISO7816_4PADDING: case CipherPadding.ISO9797_1PADDING: blockCipherPadding = new ISO7816d4Padding(); break; case CipherPadding.ISO9796_1: case CipherPadding.ISO9796_1PADDING: asymmetricBlockCipher = new ISO9796d1Encoding(asymmetricBlockCipher); break; case CipherPadding.OAEP: case CipherPadding.OAEPPADDING: asymmetricBlockCipher = new OaepEncoding(asymmetricBlockCipher); break; case CipherPadding.OAEPWITHMD5ANDMGF1PADDING: asymmetricBlockCipher = new OaepEncoding(asymmetricBlockCipher, new MD5Digest()); break; case CipherPadding.OAEPWITHSHA1ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_1ANDMGF1PADDING: asymmetricBlockCipher = new OaepEncoding(asymmetricBlockCipher, new Sha1Digest()); break; case CipherPadding.OAEPWITHSHA224ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_224ANDMGF1PADDING: asymmetricBlockCipher = new OaepEncoding(asymmetricBlockCipher, new Sha224Digest()); break; case CipherPadding.OAEPWITHSHA256ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_256ANDMGF1PADDING: asymmetricBlockCipher = new OaepEncoding(asymmetricBlockCipher, new Sha256Digest()); break; case CipherPadding.OAEPWITHSHA384ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_384ANDMGF1PADDING: asymmetricBlockCipher = new OaepEncoding(asymmetricBlockCipher, new Sha384Digest()); break; case CipherPadding.OAEPWITHSHA512ANDMGF1PADDING: case CipherPadding.OAEPWITHSHA_512ANDMGF1PADDING: asymmetricBlockCipher = new OaepEncoding(asymmetricBlockCipher, new Sha512Digest()); break; case CipherPadding.PKCS1: case CipherPadding.PKCS1PADDING: asymmetricBlockCipher = new Pkcs1Encoding(asymmetricBlockCipher); break; case CipherPadding.PKCS5: case CipherPadding.PKCS5PADDING: case CipherPadding.PKCS7: case CipherPadding.PKCS7PADDING: blockCipherPadding = new Pkcs7Padding(); break; case CipherPadding.TBCPADDING: blockCipherPadding = new TbcPadding(); break; case CipherPadding.WITHCTS: flag = true; break; case CipherPadding.X923PADDING: blockCipherPadding = new X923Padding(); break; case CipherPadding.ZEROBYTEPADDING: blockCipherPadding = new ZeroBytePadding(); break; default: throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); case CipherPadding.RAW: break; } } string text5 = ""; if (array.Length > 1) { text5 = array[1]; int digitIndex = GetDigitIndex(text5); string text6 = ((digitIndex >= 0) ? text5.Substring(0, digitIndex) : text5); try { switch ((text6 == "") ? CipherMode.NONE : ((CipherMode)Enums.GetEnumValue(typeof(CipherMode), text6))) { case CipherMode.CBC: blockCipher = new CbcBlockCipher(blockCipher); break; case CipherMode.CCM: aeadBlockCipher = new CcmBlockCipher(blockCipher); break; case CipherMode.CFB: { int bitBlockSize = ((digitIndex < 0) ? (8 * blockCipher.GetBlockSize()) : int.Parse(text5.Substring(digitIndex))); blockCipher = new CfbBlockCipher(blockCipher, bitBlockSize); break; } case CipherMode.CTR: blockCipher = new SicBlockCipher(blockCipher); break; case CipherMode.CTS: flag = true; blockCipher = new CbcBlockCipher(blockCipher); break; case CipherMode.EAX: aeadBlockCipher = new EaxBlockCipher(blockCipher); break; case CipherMode.GCM: aeadBlockCipher = new GcmBlockCipher(blockCipher); break; case CipherMode.GOFB: blockCipher = new GOfbBlockCipher(blockCipher); break; case CipherMode.OCB: aeadBlockCipher = new OcbBlockCipher(blockCipher, CreateBlockCipher(cipherAlgorithm)); break; case CipherMode.OFB: { int blockSize = ((digitIndex < 0) ? (8 * blockCipher.GetBlockSize()) : int.Parse(text5.Substring(digitIndex))); blockCipher = new OfbBlockCipher(blockCipher, blockSize); break; } case CipherMode.OPENPGPCFB: blockCipher = new OpenPgpCfbBlockCipher(blockCipher); break; case CipherMode.SIC: if (blockCipher.GetBlockSize() < 16) { throw new ArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)"); } blockCipher = new SicBlockCipher(blockCipher); break; default: throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); case CipherMode.ECB: case CipherMode.NONE: break; } } catch (ArgumentException) { throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } } if (aeadBlockCipher != null) { if (flag) { throw new SecurityUtilityException("CTS mode not valid for AEAD ciphers."); } if (flag2 && array.Length > 2 && array[2] != "") { throw new SecurityUtilityException("Bad padding specified for AEAD cipher."); } return(new BufferedAeadBlockCipher(aeadBlockCipher)); } if (blockCipher != null) { if (flag) { return(new CtsBlockCipher(blockCipher)); } if (blockCipherPadding != null) { return(new PaddedBufferedBlockCipher(blockCipher, blockCipherPadding)); } if (!flag2 || blockCipher.IsPartialBlockOkay) { return(new BufferedBlockCipher(blockCipher)); } return(new PaddedBufferedBlockCipher(blockCipher)); } if (asymmetricBlockCipher != null) { return(new BufferedAsymmetricBlockCipher(asymmetricBlockCipher)); } throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); }