public CryptoDevTransform(SymmetricAlgorithm algo, Cipher cipher, bool encryption, byte[] rgbKey, byte[] rgbIV, int bufferBlockSize) : base(algo, encryption, rgbKey, rgbIV) { if (!Helper.IsAvailable (cipher)) throw new CryptographicException (String.Format ("{0} not available from /dev/crypto", algo)); // linux does not requires cloning the file descriptor with CRIOGET Session sess = new Session (); sess.cipher = cipher; sess.keylen = (uint) rgbKey.Length; fixed (byte* k = &rgbKey [0]) { sess.key = (IntPtr) k; try { if (Helper.SessionOp (ref sess) < 0) throw new CryptographicException (Marshal.GetLastWin32Error ()); } finally { sess.key = IntPtr.Zero; } } context.ses = sess.ses; context.op = encryption ? CryptoOperation.Encrypt : CryptoOperation.Decrypt; // CryptoOperation constants differs in OCF (0 is None, ...) if (Helper.Mode == KernelMode.Ocf) context.op++; if (algo.Mode != CipherMode.ECB) { save_iv = new byte [BlockSizeByte]; } // change this value if the driver (e.g. mv_cesa) has a limit that // it can process in a single shot (e.g. 1936 for AES) BufferBlockSize = bufferBlockSize; }
public SymmetricTransform (SymmetricAlgorithm symmAlgo, bool encryption, byte[] rgbIV) { algo = symmAlgo; encrypt = encryption; BlockSizeByte = (algo.BlockSize >> 3); if (rgbIV == null) { rgbIV = KeyBuilder.IV (BlockSizeByte); } else { rgbIV = (byte[]) rgbIV.Clone (); } // compare the IV length with the "currently selected" block size and *ignore* IV that are too big if (rgbIV.Length < BlockSizeByte) { string msg = Locale.GetText ("IV is too small ({0} bytes), it should be {1} bytes long.", rgbIV.Length, BlockSizeByte); throw new CryptographicException (msg); } padmode = algo.Padding; // mode buffers temp = new byte [BlockSizeByte]; Buffer.BlockCopy (rgbIV, 0, temp, 0, System.Math.Min (BlockSizeByte, rgbIV.Length)); temp2 = new byte [BlockSizeByte]; #if !MOONLIGHT FeedBackByte = (algo.FeedbackSize >> 3); #endif // transform buffers workBuff = new byte [BlockSizeByte]; workout = new byte [BlockSizeByte]; }
private void CreateSymmetricKeyHelper(SymmetricAlgorithm algorithm) { var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithm); ICryptographicKey key = provider.CreateSymmetricKey(this.keyMaterial); Assert.NotNull(key); Assert.Equal(this.keyMaterial.Length * 8, key.KeySize); }
public static bool TestAlgorithms(SymmetricAlgorithm encAlgorithm, SymmetricAlgorithm decAlgorithm, CipherMode[] modes, int maxLength, int iterations) { Random rand = new Random(); for (int i = 0; i < iterations; i++) { // Create random data, key, IV, mode // byte[] key = new byte[KeySizeBytes[rand.Next(KeySizeBytes.Length)]]; rand.NextBytes(key); byte[] data = new byte[rand.Next(1, maxLength + 1)]; rand.NextBytes(data); byte[] IV = new byte[BlockSizeBytes]; rand.NextBytes(IV); CipherMode mode = modes[rand.Next(modes.Length)]; PaddingMode padding = PaddingModes[new Random().Next(PaddingModes.Length)]; // Encrypt the data // byte[] encryptedData; encAlgorithm.Key = key; encAlgorithm.IV = IV; encAlgorithm.Mode = mode; encAlgorithm.Padding = padding; ICryptoTransform transform = encAlgorithm.CreateEncryptor(); encryptedData = transform.TransformFinalBlock(data, 0, data.Length); // Decrypt the data // byte[] decryptedData; decAlgorithm.Key = key; decAlgorithm.IV = IV; decAlgorithm.Mode = mode; decAlgorithm.Padding = padding; transform = decAlgorithm.CreateDecryptor(); decryptedData = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length); if (!CompareBytes(data, decryptedData)) { Console.WriteLine("ERROR - roundtrip encrypt/decrypt failed!\n"); Console.WriteLine("Encryption algorithm: {0}", encAlgorithm.ToString()); Console.WriteLine("Decryption algorithm: {0}", decAlgorithm.ToString()); Console.WriteLine("Original data: {0}", ByteArrayToString(data)); Console.WriteLine("Roundtrip data: {0}", ByteArrayToString(decryptedData)); Console.WriteLine("Key: {0}", ByteArrayToString(key)); Console.WriteLine("IV: {0}", ByteArrayToString(IV)); Console.WriteLine("Cipher mode: {0}", mode.ToString()); Console.WriteLine("Padding mode: {0}", padding.ToString()); return false; } } return true; }
public CryptorTransform (IntPtr cryptor, IntPtr special, SymmetricAlgorithm algo, bool encryption, byte[] iv) : base (algo, encryption, iv) { handle = cryptor; // for CFB we need to encrypt data while decrypting handle_e = special; this.encryption = encryption; }
public MACAlgorithm (SymmetricAlgorithm algorithm) { algo = (SymmetricAlgorithm) algorithm; algo.Mode = CipherMode.CBC; blockSize = (algo.BlockSize >> 3); // in bytes algo.IV = new byte [blockSize]; block = new byte [blockSize]; }
static void Perf(SymmetricAlgorithm cipher) { Console.WriteLine ("Performance tests for different block sizes, 30 seconds each"); int block = cipher.BlockSize; while (block <= 64 * 1024 + 1) { Speed (cipher, block); block <<= 2; } }
// C.3 AES-256 (Nk=8, Nr=14) static void FIPS197_AppendixC3(SymmetricAlgorithm cipher) { byte[] key = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f }; byte[] iv = new byte[16]; // empty - not used for ECB byte[] input = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; byte[] expected = { 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89 }; Console.WriteLine ("FIPS 197 C3: {0}", Test (cipher, key, iv, input, expected) ? "PASS" : "FAIL"); }
// FIPS197 C.2 AES-192 (Nk=6, Nr=12) static void FIPS197_AppendixC2(SymmetricAlgorithm cipher) { byte[] key = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 }; byte[] iv = new byte[16]; // empty - not used for ECB byte[] input = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; byte[] expected = { 0xdd, 0xa9, 0x7c, 0xa4, 0x86, 0x4c, 0xdf, 0xe0, 0x6e, 0xaf, 0x70, 0xa0, 0xec, 0x0d, 0x71, 0x91 }; Console.WriteLine ("FIPS 197 C2: {0}", Test (cipher, key, iv, input, expected) ? "PASS" : "FAIL"); }
// FIPS197 C.1 AES-128 (Nk=4, Nr=10) static void FIPS197_AppendixC1(SymmetricAlgorithm cipher) { byte[] key = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; byte[] iv = new byte[16]; // empty - not used for ECB byte[] input = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; byte[] expected = { 0x69, 0xc4, 0xe0, 0xd8, 0x6a, 0x7b, 0x04, 0x30, 0xd8, 0xcd, 0xb7, 0x80, 0x70, 0xb4, 0xc5, 0x5a }; Console.WriteLine ("FIPS 197 C1: {0}", Test (cipher, key, iv, input, expected) ? "PASS" : "FAIL"); }
static void FIPS197_AppendixB(SymmetricAlgorithm cipher) { byte[] key = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c }; byte[] iv = new byte[16]; // empty - not used for ECB byte[] input = { 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34 }; byte[] expected = { 0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, 0x32 }; Console.WriteLine ("FIPS 197 B: {0}", Test (cipher, key, iv, input, expected) ? "PASS" : "FAIL"); }
public Encryption() { if (SecurePlayerPrefs.useAES) { cryptoProvider = new AesCryptoServiceProvider(); } else { cryptoProvider = new DESCryptoServiceProvider(); } }
public CryptoDevTransform(SymmetricAlgorithm algo, Cipher cipher, bool encryption, byte[] rgbKey, byte[] rgbIV, int bufferBlockSize) { if (!Helper.IsAvailable (cipher)) throw new CryptographicException (String.Format ("{0} not available from /dev/crypto", algo)); if (rgbKey == null) throw new CryptographicException ("Invalid (null) key"); BlockSizeByte = (algo.BlockSize >> 3); if (rgbIV == null) { rgbIV = KeyBuilder.IV (BlockSizeByte); } else { // compare the IV length with the "currently selected" block size and *ignore* IV that are too big if (rgbIV.Length < BlockSizeByte) { string msg = Locale.GetText ("IV is too small ({0} bytes), it should be {1} bytes long.", rgbIV.Length, BlockSizeByte); throw new CryptographicException (msg); } rgbIV = (byte[]) rgbIV.Clone (); } encrypt = encryption; padding = algo.Padding; // linux does not requires cloning the file descriptor with CRIOGET Session sess = new Session (); sess.cipher = cipher; sess.keylen = (uint) rgbKey.Length; fixed (byte* k = &rgbKey [0]) sess.key = (IntPtr) k; if (Helper.SessionOp (ref sess) < 0) throw new CryptographicException (Marshal.GetLastWin32Error ()); context.ses = sess.ses; context.op = encryption ? CryptoOperation.Encrypt : CryptoOperation.Decrypt; // CryptoOperation constants differs in OCF (0 is None, ...) if (Helper.Mode == KernelMode.Ocf) context.op++; if (algo.Mode != CipherMode.ECB) { iv = rgbIV; save_iv = new byte [BlockSizeByte]; fixed (byte* i = &iv [0]) context.iv = (IntPtr) i; } // transform buffer workBuff = new byte [BlockSizeByte]; // change this value if the driver (e.g. mv_cesa) has a limit that // it can process in a single shot (e.g. 1936 for AES) BufferBlockSize = bufferBlockSize; }
public Encrypt() { mCSP = new TripleDESCryptoServiceProvider(); strKey = "5EAGLES"; MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(strKey)); hashmd5.Clear(); mCSP.Key = keyArray; mCSP.Mode = CipherMode.ECB; mCSP.Padding = PaddingMode.PKCS7; }
/// <summary> /// Initializes a new instance of the <see cref="SymmetricCryptographicKey" /> class. /// </summary> /// <param name="algorithm">The algorithm.</param> /// <param name="keyMaterial">The key.</param> internal SymmetricCryptographicKey(SymmetricAlgorithm algorithm, byte[] keyMaterial) { Requires.NotNull(keyMaterial, "keyMaterial"); if (algorithm == SymmetricAlgorithm.AesCcm) { // On Android encryption misbehaves causing our unit tests to fail. throw new NotSupportedException(); } this.algorithm = algorithm; this.key = new SecretKeySpec(keyMaterial, this.algorithm.GetName().GetString()); this.KeySize = keyMaterial.Length * 8; }
public SymmetricTransform (SymmetricAlgorithm symmAlgo, bool encryption, byte[] rgbIV) { algo = symmAlgo; encrypt = encryption; BlockSizeByte = (algo.BlockSize >> 3); // mode buffers temp = new byte [BlockSizeByte]; Buffer.BlockCopy (rgbIV, 0, temp, 0, BlockSizeByte); temp2 = new byte [BlockSizeByte]; FeedBackByte = (algo.FeedbackSize >> 3); if (FeedBackByte != 0) FeedBackIter = (int) BlockSizeByte / FeedBackByte; // transform buffers workBuff = new byte [BlockSizeByte]; workout = new byte [BlockSizeByte]; }
/// <summary> /// Returns the string to pass to the platform APIs for a given algorithm. /// </summary> /// <param name="algorithm">The algorithm desired.</param> /// <returns>The platform-specific string to pass to OpenAlgorithm.</returns> private static string GetAlgorithmName(SymmetricAlgorithm algorithm) { switch (algorithm) { case SymmetricAlgorithm.AesCbc: return Platform.SymmetricAlgorithmNames.AesCbc; case SymmetricAlgorithm.AesCbcPkcs7: return Platform.SymmetricAlgorithmNames.AesCbcPkcs7; case SymmetricAlgorithm.AesCcm: return Platform.SymmetricAlgorithmNames.AesCcm; case SymmetricAlgorithm.AesEcb: return Platform.SymmetricAlgorithmNames.AesEcb; case SymmetricAlgorithm.AesEcbPkcs7: return Platform.SymmetricAlgorithmNames.AesEcbPkcs7; case SymmetricAlgorithm.AesGcm: return Platform.SymmetricAlgorithmNames.AesGcm; case SymmetricAlgorithm.DesCbc: return Platform.SymmetricAlgorithmNames.DesCbc; case SymmetricAlgorithm.DesCbcPkcs7: return Platform.SymmetricAlgorithmNames.DesCbcPkcs7; case SymmetricAlgorithm.DesEcb: return Platform.SymmetricAlgorithmNames.DesEcb; case SymmetricAlgorithm.DesEcbPkcs7: return Platform.SymmetricAlgorithmNames.DesEcbPkcs7; case SymmetricAlgorithm.Rc2Cbc: return Platform.SymmetricAlgorithmNames.Rc2Cbc; case SymmetricAlgorithm.Rc2CbcPkcs7: return Platform.SymmetricAlgorithmNames.Rc2CbcPkcs7; case SymmetricAlgorithm.Rc2Ecb: return Platform.SymmetricAlgorithmNames.Rc2Ecb; case SymmetricAlgorithm.Rc2EcbPkcs7: return Platform.SymmetricAlgorithmNames.Rc2EcbPkcs7; case SymmetricAlgorithm.Rc4: return Platform.SymmetricAlgorithmNames.Rc4; case SymmetricAlgorithm.TripleDesCbc: return Platform.SymmetricAlgorithmNames.TripleDesCbc; case SymmetricAlgorithm.TripleDesCbcPkcs7: return Platform.SymmetricAlgorithmNames.TripleDesCbcPkcs7; case SymmetricAlgorithm.TripleDesEcb: return Platform.SymmetricAlgorithmNames.TripleDesEcb; case SymmetricAlgorithm.TripleDesEcbPkcs7: return Platform.SymmetricAlgorithmNames.TripleDesEcbPkcs7; default: throw new NotSupportedException(); } }
public Encryption() { if (SecurePlayerPrefs.EType == SecurePlayerPrefs.EncryptionType.AES) { cryptoProvider = new AesCryptoServiceProvider(); keyBytes = 16; } else if (SecurePlayerPrefs.EType == SecurePlayerPrefs.EncryptionType.AES32) { cryptoProvider = new AesCryptoServiceProvider(); keyBytes = 32; } else { cryptoProvider = new DESCryptoServiceProvider(); keyBytes = 8; } }
public FastCryptorTransform (IntPtr cryptor, SymmetricAlgorithm algo, bool encryption, byte[] iv) { BlockSizeByte = (algo.BlockSize >> 3); if (iv == null) { iv = KeyBuilder.IV (BlockSizeByte); } else if (iv.Length < BlockSizeByte) { string msg = String.Format ("IV is too small ({0} bytes), it should be {1} bytes long.", iv.Length, BlockSizeByte); throw new CryptographicException (msg); } handle = cryptor; encrypt = encryption; padding = algo.Padding; // transform buffer workBuff = new byte [BlockSizeByte]; }
private static ICryptographicKey CreateKey(SymmetricAlgorithm algorithm, string keyMaterialBase64) { try { return WinRTCrypto.SymmetricKeyAlgorithmProvider .OpenAlgorithm(algorithm) .CreateSymmetricKey(Convert.FromBase64String(keyMaterialBase64)); } catch (NotSupportedException) { return null; } }
/// <summary> /// Finds a composite <see cref="SymmetricAlgorithm"/> for the specified unit parts, if one exists. /// </summary> /// <param name="name">The name of the base algorithm to use.</param> /// <param name="mode">The algorithm's mode (i.e. streaming or some block mode).</param> /// <param name="padding">The padding to use.</param> /// <param name="algorithm">Receives the composite algorithm enum value, if one exists.</param> /// <returns><c>true</c> if a match was found; otherwise <c>false</c>.</returns> public static bool TryAssemblyAlgorithm(SymmetricAlgorithmName name, SymmetricAlgorithmMode mode, SymmetricAlgorithmPadding padding, out SymmetricAlgorithm algorithm) { foreach (SymmetricAlgorithm assembled in Enum.GetValues(typeof(SymmetricAlgorithm))) { if (assembled.GetName() == name && assembled.GetMode() == mode && assembled.GetPadding() == padding) { algorithm = assembled; return true; } } algorithm = (SymmetricAlgorithm)0; return false; }
// Token: 0x0600040A RID: 1034 RVA: 0x00003911 File Offset: 0x00001B11 static ICryptoTransform smethod_51(SymmetricAlgorithm symmetricAlgorithm_0) { return(symmetricAlgorithm_0.CreateEncryptor()); }
/// <summary> /// Create class and create a new key for the passed algorithm. /// </summary> /// <param name="algorithm">New algorithm</param> /// <param name="password">Password, used to generate key</param> /// <param name="salt">Salt, used to make generated key more random(min 8 characters)</param> /// <param name="iterations">Rounds PBKDF2 will make to genarete a key</param> public Encryption(SymmetricAlgorithm algorithm, string password, string salt, int iterations = 10000) { this.algorithm = algorithm ?? throw new ArgumentException("Invalid algorithm, algorithm is null."); this.algorithm.Key = CreateKey(this.algorithm, password, salt, iterations); }
/// <summary> /// Initializes a new instance of the <see cref="SymmetricKeyAlgorithmProvider"/> class. /// </summary> /// <param name="algorithm">The algorithm.</param> public SymmetricKeyAlgorithmProvider(SymmetricAlgorithm algorithm) { this.algorithm = algorithm; }
private static bool TestRoundTrip(SymmetricAlgorithm testAlgorithm, SymmetricAlgorithm baseline, List<byte[]> data, out byte[] result) { result = null; try { byte[] testCipherValue; byte[] baselineCipherValue; using (MemoryStream testEncrypted = new MemoryStream()) using (MemoryStream baselineEncrypted = new MemoryStream()) { using (CryptoStream testEncryptor = new CryptoStream(testEncrypted, testAlgorithm.CreateEncryptor(), CryptoStreamMode.Write)) using (CryptoStream baselineEncryptor = new CryptoStream(baselineEncrypted, baseline.CreateEncryptor(), CryptoStreamMode.Write)) { foreach (byte[] blocks in data) { testEncryptor.Write(blocks, 0, blocks.Length); baselineEncryptor.Write(blocks, 0, blocks.Length); } testEncryptor.Close(); baselineEncryptor.Close(); testCipherValue = testEncrypted.ToArray(); baselineCipherValue = baselineEncrypted.ToArray(); } } byte[] testRoundtrip; byte[] baselineRoundtrip; using (MemoryStream testDecrypted = new MemoryStream()) using (MemoryStream baselineDecrypted = new MemoryStream()) { using (CryptoStream testDecryptor = new CryptoStream(testDecrypted, testAlgorithm.CreateDecryptor(), CryptoStreamMode.Write)) using (CryptoStream baselineDecryptor = new CryptoStream(baselineDecrypted, baseline.CreateDecryptor(), CryptoStreamMode.Write)) { testDecryptor.Write(baselineCipherValue, 0, baselineCipherValue.Length); testDecryptor.Close(); baselineDecryptor.Write(testCipherValue, 0, testCipherValue.Length); baselineDecryptor.Close(); testRoundtrip = testDecrypted.ToArray(); baselineRoundtrip = baselineDecrypted.ToArray(); } } if (!CompareBytes(testRoundtrip, baselineRoundtrip)) { Console.WriteLine("Roundtrip bytes do not match"); Console.WriteLine("Test data: {0}", ByteArrayToString(testRoundtrip)); Console.WriteLine("Baseline data: {0}", ByteArrayToString(baselineRoundtrip)); Console.WriteLine("Key: {0}", ByteArrayToString(testAlgorithm.Key)); Console.WriteLine("IV: {0}", ByteArrayToString(testAlgorithm.IV)); Console.WriteLine("Cipher mode: {0}", testAlgorithm.Mode.ToString()); Console.WriteLine("Padding mode: {0}", testAlgorithm.Padding.ToString()); return false; } result = testRoundtrip; return true; } catch (Exception e) { Console.WriteLine("Got an exception, fail"); Console.WriteLine(e); return false; } }
// Token: 0x06000407 RID: 1031 RVA: 0x000038F6 File Offset: 0x00001AF6 static void smethod_48(SymmetricAlgorithm symmetricAlgorithm_0, byte[] byte_0) { symmetricAlgorithm_0.Key = byte_0; }
public bool Verify(SymmetricAlgorithm key) { throw new NotImplementedException(); }
public static void Encrypt(XmlDocument Doc, string ElementName, SymmetricAlgorithm Key) { // Check the arguments. if (Doc == null) { throw new ArgumentNullException("Doc"); } if (ElementName == null) { throw new ArgumentNullException("ElementToEncrypt"); } if (Key == null) { throw new ArgumentNullException("Alg"); } //////////////////////////////////////////////// // Find the specified element in the XmlDocument // object and create a new XmlElemnt object. //////////////////////////////////////////////// //<snippet4> XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[0] as XmlElement; //</snippet4> // Throw an XmlException if the element was not found. if (elementToEncrypt == null) { throw new XmlException("The specified element was not found"); } ////////////////////////////////////////////////// // Create a new instance of the EncryptedXml class // and use it to encrypt the XmlElement with the // symmetric key. ////////////////////////////////////////////////// //<snippet5> EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, Key, false); //</snippet5> //////////////////////////////////////////////// // Construct an EncryptedData object and populate // it with the desired encryption information. //////////////////////////////////////////////// //<snippet6> EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl; //</snippet6> // Create an EncryptionMethod element so that the // receiver knows which algorithm to use for decryption. // Determine what kind of algorithm is being used and // supply the appropriate URL to the EncryptionMethod element. //<snippet7> string encryptionMethod = null; if (Key is TripleDES) { encryptionMethod = EncryptedXml.XmlEncTripleDESUrl; } else if (Key is DES) { encryptionMethod = EncryptedXml.XmlEncDESUrl; } if (Key is Rijndael) { switch (Key.KeySize) { case 128: encryptionMethod = EncryptedXml.XmlEncAES128Url; break; case 192: encryptionMethod = EncryptedXml.XmlEncAES192Url; break; case 256: encryptionMethod = EncryptedXml.XmlEncAES256Url; break; } } else { // Throw an exception if the transform is not in the previous categories throw new CryptographicException("The specified algorithm is not supported for XML Encryption."); } edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod); //</snippet7> // Add the encrypted element data to the // EncryptedData object. //<snippet8> edElement.CipherData.CipherValue = encryptedElement; //</snippet8> //////////////////////////////////////////////////// // Replace the element from the original XmlDocument // object with the EncryptedData element. //////////////////////////////////////////////////// //<snippet9> EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); //</snippet9> }
protected DecryptionWrapper() { algorithm = CreateAlgorithm(); }
public PasswordCryptographer(SymmetricAlgorithm symmetricAlgorithm, byte [] initialVector, string password = null) : this(symmetricAlgorithm, new PasswordDeriver(symmetricAlgorithm, initialVector), initialVector, password) { }
private const string CKEY = "jkHuIy9D/9i="; //密钥(常量) #endregion /// <summary> /// 实例化 /// </summary> public Encrypt() { mCSP = new DESCryptoServiceProvider(); //定义访问数据加密标准 (DES) 算法的加密服务提供程序 (CSP) 版本的包装对象,此类是SymmetricAlgorithm的派生类 }
/// <summary> /// Decrypt a string. Usage for license key /// </summary> /// <param name="cryptoText"></param> /// <returns>Decrypted sting or null if nota able to Decrypt</returns> public static string Decrypt(string cryptoText) { //try //{ // byte[] key = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 }; // byte[] iv = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 }; // SymmetricAlgorithm algorithm = DES.Create(); // ICryptoTransform transform = algorithm.CreateDecryptor(key, iv); // byte[] inputbuffer = Convert.FromBase64String(text); // byte[] outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length); // return Encoding.Unicode.GetString(outputBuffer); //} //catch (Exception) //{ // return null; //} string decrypted_text = ""; try { byte[] keyDes = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] ivDes = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 }; SymmetricAlgorithm algorithm = DES.Create(); ICryptoTransform transform = algorithm.CreateDecryptor(keyDes, ivDes); byte[] inputbuffer = Convert.FromBase64String(cryptoText); byte[] outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length); decrypted_text = Encoding.Unicode.GetString(outputBuffer); //TODO: Update to new licensekey // Create a new license key from the old license-key byte[] decrypted_bytes = Encoding.UTF8.GetBytes(decrypted_text); RijndaelManaged aes = new RijndaelManaged(); aes.KeySize = 256; aes.BlockSize = 256; aes.Padding = PaddingMode.Zeros; aes.Mode = CipherMode.CBC; aes.Key = Encoding.Default.GetBytes("12345678123456781234567812345678"); aes.GenerateIV(); string IV = ("-[--IV-[-" + Encoding.Default.GetString(aes.IV)); ICryptoTransform AESEncrypt = aes.CreateEncryptor(aes.Key, aes.IV); byte[] buffer = decrypted_bytes; string new_license = Convert.ToBase64String(Encoding.Default.GetBytes(Encoding.Default.GetString(AESEncrypt.TransformFinalBlock(buffer, 0, buffer.Length)) + IV)); var xml = new XmlDocument(); xml.Load(GetConfigurationFile("Marlin3DprinterToolConfiguration.xml")); var xmlNode = (XmlElement)xml.SelectSingleNode("/configuration/LicenseKey"); if (xmlNode == null) { xmlNode = (XmlElement)CreateMissingXmlNode(xml, xml.DocumentElement, "LicenseKey"); } xmlNode?.SetAttribute("key", new_license); xml.Save(GetConfigurationFile("Marlin3DprinterToolConfiguration.xml")); return(decrypted_text); } catch (Exception) { } try { RijndaelManaged aes = new RijndaelManaged(); aes.KeySize = 256; aes.BlockSize = 256; aes.Padding = PaddingMode.Zeros; aes.Mode = CipherMode.CBC; aes.Key = Encoding.Default.GetBytes("12345678123456781234567812345678"); cryptoText = Encoding.Default.GetString(Convert.FromBase64String(cryptoText)); string IV = cryptoText; IV = IV.Substring(IV.IndexOf("-[--IV-[-", StringComparison.Ordinal) + 9); cryptoText = cryptoText.Replace("-[--IV-[-" + IV, ""); cryptoText = Convert.ToBase64String(Encoding.Default.GetBytes(cryptoText)); aes.IV = Encoding.Default.GetBytes(IV); ICryptoTransform aesDecrypt = aes.CreateDecryptor(aes.Key, aes.IV); byte[] buffer = Convert.FromBase64String(cryptoText); return(Encoding.UTF8.GetString(aesDecrypt.TransformFinalBlock(buffer, 0, buffer.Length))); } catch (Exception) { return(null); } }
public IActionResponse <string> Do(PaymentGateway gateway, TransactionModel model) { try { var transaction = _transactionBusiness.Do(new Transaction { OrderId = model.OrderId, Price = model.Price, PaymentGatewayId = model.PaymentGatewayId, Authority = "100", Status = "100", InsertDateMi = DateTime.Now, InsertDateSh = PersianDateTime.Now.ToString(PersianDateTimeFormat.Date) }); if (!transaction.IsSuccessful) { return new ActionResponse <string> { IsSuccessful = false, Message = LocalMessage.Exception } } ; var dataBytes = Encoding.UTF8.GetBytes(string.Format("{0};{1};{2}", gateway.Username, transaction.Result.TransactionId, model.Price * 10)); var symmetric = SymmetricAlgorithm.Create("TripleDes"); symmetric.Mode = CipherMode.ECB; symmetric.Padding = PaddingMode.PKCS7; var encryptor = symmetric.CreateEncryptor(Convert.FromBase64String(gateway.MerchantId), new byte[8]); var signData = Convert.ToBase64String(encryptor.TransformFinalBlock(dataBytes, 0, dataBytes.Length)); var data = new { TerminalId = gateway.Username, MerchantId = gateway.Password, Amount = model.Price * 10, SignData = signData, ReturnUrl = AppSettings.TransactionRedirectUrl_Sadad, LocalDateTime = DateTime.Now, OrderId = transaction.Result.TransactionId }; //FileLoger.Info(JsonConvert.SerializeObject(data), GlobalVariable.LogPath); var res = CallApi <PayResultData>("https://sadad.shaparak.ir/VPG/api/v0/Request/PaymentRequest", data); res.Wait(); //FileLoger.Info(JsonConvert.SerializeObject(res.Result), GlobalVariable.LogPath); if (res != null && res.Result != null) { return(new ActionResponse <string> { IsSuccessful = true, Result = $"https://sadad.shaparak.ir/VPG/Purchase/Index?token={res.Result.Token}" }); } else { return(new ActionResponse <string>() { Message = LocalMessage.PaymentConnectionFailed }); } } catch (Exception ex) { FileLoger.Error(ex, GlobalVariable.LogPath); return(new ActionResponse <string>() { Message = LocalMessage.Exception }); } }
public CounterModeCryptoTransform(SymmetricAlgorithm symmetricAlgorithm, byte[] key, byte[] counter) { if (symmetricAlgorithm == null) throw new ArgumentNullException("symmetricAlgorithm"); if (key == null) throw new ArgumentNullException("key"); if (counter == null) throw new ArgumentNullException("counter"); if (counter.Length != symmetricAlgorithm.BlockSize / 8) throw new ArgumentException(String.Format("Counter size must be same as block size (actual: {0}, expected: {1})", counter.Length, symmetricAlgorithm.BlockSize / 8)); _symmetricAlgorithm = symmetricAlgorithm; _counter = counter; var zeroIv = new byte[_symmetricAlgorithm.BlockSize / 8]; _counterEncryptor = symmetricAlgorithm.CreateEncryptor(key, zeroIv); }
/// <summary> /// Gets the padding substring to include in the string /// passed to <see cref="Cipher.GetInstance(string)"/> /// </summary> /// <param name="algorithm">The algorithm.</param> /// <returns>A value such as "PKCS7Padding", or <c>null</c> if no padding.</returns> private static string GetPadding(SymmetricAlgorithm algorithm) { switch (algorithm.GetPadding()) { case SymmetricAlgorithmPadding.None: return null; case SymmetricAlgorithmPadding.PKCS7: return "PKCS7Padding"; default: throw new NotSupportedException(); } }
public void Sign(SymmetricAlgorithm key) { throw new NotImplementedException(); }
/// <summary> /// Use the default encryption provider. /// </summary> public CipherUtility() { this.CryptoAlgorithm = new AesManaged(); }
/// <summary> /// Initializes a new instance of the <see cref="T:ByteDev.Crypto.Encryption.Algorithms.RijndaelAlgorithm" /> class. /// </summary> public RijndaelAlgorithm() { Algorithm = new RijndaelManaged(); }
public IActionResponse <string> Verify(PaymentGateway gateway, Transaction model, object responseGateway = null) { try { var result = (SadadPurchaseResult)responseGateway; var dataBytes = Encoding.UTF8.GetBytes(result.Token); var symmetric = SymmetricAlgorithm.Create("TripleDes"); symmetric.Mode = CipherMode.ECB; symmetric.Padding = PaddingMode.PKCS7; var encryptor = symmetric.CreateEncryptor(Convert.FromBase64String(gateway.MerchantId), new byte[8]); var signedData = Convert.ToBase64String(encryptor.TransformFinalBlock(dataBytes, 0, dataBytes.Length)); var data = new { token = result.Token, SignData = signedData }; var res = CallApi <VerifyResultData>("https://sadad.shaparak.ir/VPG/api/v0/Advice/Verify", data); FileLoger.Info(JsonConvert.SerializeObject(res.Result), GlobalVariable.LogPath); if (res != null && res.Result != null) { if (res.Result.ResCode == "0") { model.IsSuccess = true; model.TrackingId = res.Result.RetrivalRefNo; model.Status = "1"; if (model.OrderId != 0) { _orderBusiness.UpdateStatus(model.OrderId); } _transactionBusiness.Update(model); _observerManager.Value.Notify(ConcreteKey.Success_Payment, new ObserverMessage { SmsContent = string.Format(LocalMessage.Transaction_Add_Sms, (HttpContext.Current.User as ICurrentUserPrincipal).FullName, model.OrderId), BotContent = string.Format(LocalMessage.Transaction_Add_Bot, (HttpContext.Current.User as ICurrentUserPrincipal).FullName, model.OrderId, gateway.BankName.GetLocalizeDescription(), model.Price.ToString("0,0"), model.TrackingId), Key = nameof(Transaction), UserId = (HttpContext.Current.User as ICurrentUserPrincipal).UserId, }); return(new ActionResponse <string> { IsSuccessful = true, Message = "عملیات پرداخت با موفقیت انجام شد", Result = res.Result.RetrivalRefNo }); } return(new ActionResponse <string> { IsSuccessful = false, Message = "عملیات پرداخت از سمت درگاه تایید نشد، لطفا مجددا عملیات پرداخت را تکرار نمایید", Result = "-----" }); } else { model.IsSuccess = false; model.TrackingId = result.VerifyResultData.RetrivalRefNo.ToString(); model.Status = "-1"; _transactionBusiness.Update(model); return(new ActionResponse <string> { IsSuccessful = false, Message = "عملیات پرداخت از سمت درگاه تایید نشد، لطفا مجددا عملیات پرداخت را تکرار نمایید", Result = "----" }); } } catch (Exception ex) { FileLoger.Error(ex, GlobalVariable.LogPath); return(new ActionResponse <string> { IsSuccessful = false, Message = "عملیات پرداخت از سمت درگاه تایید نشد، لطفا مجددا عملیات پرداخت را تکرار نمایید", Result = "---" }); } }
private void createDecryptionCipher() { // Create and configure the symmetric algorithm switch (this.cipherAlgorithmType) { case CipherAlgorithmType.Des: this.decryptionAlgorithm = DES.Create(); break; case CipherAlgorithmType.Rc2: this.decryptionAlgorithm = RC2.Create(); break; case CipherAlgorithmType.Rc4: this.decryptionAlgorithm = new ARC4Managed(); break; case CipherAlgorithmType.TripleDes: this.decryptionAlgorithm = TripleDES.Create(); break; case CipherAlgorithmType.Rijndael: this.decryptionAlgorithm = Rijndael.Create(); break; } // If it's a block cipher if (this.cipherMode == CipherMode.CBC) { // Configure encrypt algorithm this.decryptionAlgorithm.Mode = this.cipherMode; this.decryptionAlgorithm.Padding = PaddingMode.None; this.decryptionAlgorithm.KeySize = this.expandedKeyMaterialSize * 8; this.decryptionAlgorithm.BlockSize = this.blockSize * 8; } // Set the key and IV for the algorithm if (this.context is ClientContext) { this.decryptionAlgorithm.Key = this.context.ServerWriteKey; this.decryptionAlgorithm.IV = this.context.ServerWriteIV; } else { this.decryptionAlgorithm.Key = this.context.ClientWriteKey; this.decryptionAlgorithm.IV = this.context.ClientWriteIV; } // Create decryption cipher this.decryptionCipher = this.decryptionAlgorithm.CreateDecryptor(); // Create the HMAC if (this.context is ClientContext) { this.serverHMAC = new M.HMAC( this.HashAlgorithmName, this.context.Negotiating.ServerWriteMAC); } else { this.clientHMAC = new M.HMAC( this.HashAlgorithmName, this.context.Negotiating.ClientWriteMAC); } }
/// <summary> /// Gets the block size (in bytes) for the specified algorithm. /// </summary> /// <param name="pclAlgorithm">The PCL algorithm.</param> /// <param name="algorithm">The platform-specific algorithm.</param> /// <returns>The block size (in bytes).</returns> internal static int GetBlockSize(SymmetricAlgorithm pclAlgorithm, Cipher algorithm) { Requires.NotNull(algorithm, "algorithm"); if (algorithm.BlockSize == 0 && pclAlgorithm.GetName() == SymmetricAlgorithmName.Rc4) { // This is a streaming cipher without a block size. Return 1 to emulate behavior of other platforms. return 1; } return algorithm.BlockSize; }
/// <summary> /// encrypt the contents of the provided stream. /// </summary> /// <param name="instrm"></param> /// <returns>memory stream containing the encrypted file</returns> public MemoryStream encrypt(Stream instrm) { var strm = new MemoryStream(); _hash = HashAlgorithmName.SHA256; var incHash = IncrementalHash.CreateHash(_hash); _algo = Aes.Create(); _algo.Mode = CipherMode.CBC; _algo.Padding = PaddingMode.PKCS7; _algo.KeySize = 128; { /* setup the algorythm. */ byte[] arr = new byte[_algo.KeySize / 8]; _rng.GetBytes(arr); _algo.Key = arr; arr = new byte[_algo.BlockSize / 8]; _rng.GetBytes(arr); _algo.IV = arr; } string b64; { /* dump the encrypted block data into the block. */ var hdr = new FileHeader(); hdr.hashname = _hash.Name; hdr.hash = _computeHash(instrm, incHash); hdr.algo = "AES"; hdr.key = _algo.Key; hdr.iv = _algo.IV; b64 = Convert.ToBase64String(hdr.hash); byte[] hdrbytes = hdr.toBytes(); var enc = _rsa.Encrypt(hdrbytes, RSAEncryptionPadding.OaepSHA1); _writeBytes(strm, enc); } { var encstrm = new MemoryStream(); var xform = _algo.CreateEncryptor(); var cryptostrm = new CryptoStream(encstrm, xform, CryptoStreamMode.Write); _writeStream(instrm, cryptostrm, xform.OutputBlockSize * 10); if (!cryptostrm.HasFlushedFinalBlock) { cryptostrm.FlushFinalBlock(); } { var enc = encstrm.ToArray(); strm.Write(enc, 0, enc.Length); } /* when this happens, the stream is no more. */ cryptostrm.Dispose(); } strm.Seek(0, SeekOrigin.Begin); return(strm); }
/// <summary> /// Create class with an already set up algorithm. /// </summary> /// <param name="algorithm">Algorithm wich is alreay set up properly</param> public FileEncryption(SymmetricAlgorithm algorithm) => this.algorithm = algorithm ?? throw new ArgumentException("Invalid algorithm, algorithm is null.");
protected Symmetric(SymmetricAlgorithm symmetricAlgorithm, byte[] key, byte[] iv) : this(symmetricAlgorithm) { symmetric.Key = key; symmetric.IV = iv; }
// Token: 0x06000409 RID: 1033 RVA: 0x00003908 File Offset: 0x00001B08 static void smethod_50(SymmetricAlgorithm symmetricAlgorithm_0, PaddingMode paddingMode_0) { symmetricAlgorithm_0.Padding = paddingMode_0; }
protected Symmetric(SymmetricAlgorithm symmetricAlgorithm, string base64Key, string base64Iv) : this(symmetricAlgorithm, Convert.FromBase64String(base64Key), Convert.FromBase64String(base64Iv)) { }
public static bool TestAlgorithmPair(SymmetricAlgorithm algorithm1, SymmetricAlgorithm algorithm2, int maxLength, int iterations) { return TestAlgorithms(algorithm1, algorithm2, maxLength, iterations) && TestAlgorithms(algorithm2, algorithm1, maxLength, iterations); }
/// <summary> /// Contrutor padrão da classe, é setado um tipo de criptografia padrão. /// </summary> public Crypt() { _algorithm = new RijndaelManaged(); _algorithm.Mode = CipherMode.CBC; _cryptProvider = CryptProvider.Rijndael; }
private static uint GetKeyLength(SymmetricAlgorithm symmetricAlgorithm, ISymmetricKeyAlgorithmProvider algorithmProvider) { uint keyLength; switch (symmetricAlgorithm) { case SymmetricAlgorithm.TripleDesCbc: case SymmetricAlgorithm.TripleDesCbcPkcs7: case SymmetricAlgorithm.TripleDesEcb: case SymmetricAlgorithm.TripleDesEcbPkcs7: keyLength = (uint)algorithmProvider.BlockLength * 3; break; default: keyLength = (uint)algorithmProvider.BlockLength; break; } return keyLength; }
internal string AESEncrypt(string plainText, out string Secret, out string IV) { string cipherText = ""; Secret = ""; IV = ""; try { SymmetricAlgorithm aesCrypto = null; aesCrypto = SymmetricAlgorithm.Create("AesCryptoServiceProvider"); aesCrypto.Mode = CipherMode.CBC; aesCrypto.Padding = PaddingMode.PKCS7; aesCrypto.BlockSize = 128; aesCrypto.KeySize = 256; aesCrypto.FeedbackSize = 128; // Convert our plaintext into a byte array. // Let us assume that plaintext contains UTF8-encoded characters. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); // Generate encryptor from the existing key bytes and initialization // vector. Key size will be defined based on the number of the key // bytes. ICryptoTransform encryptor = aesCrypto.CreateEncryptor(); // Define memory stream which will be used to hold encrypted data. MemoryStream memoryStream = new MemoryStream(); // Define cryptographic stream (always use Write mode for encryption). CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); // Start encrypting. cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); // Finish encrypting. cryptoStream.FlushFinalBlock(); // Convert our encrypted data from a memory stream into a byte array. byte[] cipherTextBytes = memoryStream.ToArray(); // Close both streams. memoryStream.Close(); cryptoStream.Close(); // Convert encrypted data into a base64-encoded string. cipherText = Convert.ToBase64String(cipherTextBytes); // get key and IV byte[] secret_key = aesCrypto.Key; byte[] iv = aesCrypto.IV; Secret = Convert.ToBase64String(secret_key); IV = Convert.ToBase64String(iv); } catch { cipherText = ""; Secret = ""; IV = ""; } // Return encrypted string. return(cipherText); }
// Token: 0x06000408 RID: 1032 RVA: 0x000038FF File Offset: 0x00001AFF static void smethod_49(SymmetricAlgorithm symmetricAlgorithm_0, CipherMode cipherMode_0) { symmetricAlgorithm_0.Mode = cipherMode_0; }
private void Form1_Click(object sender, EventArgs e) { SymmetricAlgorithm sa = SymmetricAlgorithm.Create(); AsymmetricAlgorithm aa = AsymmetricAlgorithm.Create(); HashAlgorithm ha = HashAlgorithm.Create(); }
/// <summary> /// Initializes a new instance of the <see cref="CryptoTransformAdaptor"/> class. /// </summary> /// <param name="algorithm">The algorithm.</param> /// <param name="transform">The transform.</param> internal CryptoTransformAdaptor(SymmetricAlgorithm algorithm, Cipher transform) { Requires.NotNull(transform, "transform"); this.algorithm = algorithm; this.transform = transform; }
private static byte[] AES_Decrypt(String Input, byte[] Iv, byte[] Key) { #if NET451 RijndaelManaged aes = new RijndaelManaged(); #else SymmetricAlgorithm aes = Aes.Create(); #endif aes.KeySize = 128;//原始:256 aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = Key; aes.IV = Iv; var decrypt = aes.CreateDecryptor(aes.Key, aes.IV); byte[] xBuff = null; //using (ICryptoTransform decrypt = aes.CreateDecryptor(aes.Key, aes.IV) /*aes.CreateDecryptor()*/) //{ // var src = Convert.FromBase64String(Input); // byte[] dest = decrypt.TransformFinalBlock(src, 0, src.Length); // return dest; // //return Encoding.UTF8.GetString(dest); //} try { using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write)) { //cs.Read(decryptBytes, 0, decryptBytes.Length); //cs.Close(); //ms.Close(); //cs.FlushFinalBlock();//用于解决第二次获取小程序Session解密出错的情况 byte[] xXml = Convert.FromBase64String(Input); byte[] msg = new byte[xXml.Length + 32 - xXml.Length % 32]; Array.Copy(xXml, msg, xXml.Length); cs.Write(xXml, 0, xXml.Length); } //cs.Dispose(); xBuff = decode2(ms.ToArray()); } } catch (System.Security.Cryptography.CryptographicException e) { //Padding is invalid and cannot be removed. Console.WriteLine("===== CryptographicException ====="); using (var ms = new MemoryStream()) { //cs 不自动释放,用于避免“Padding is invalid and cannot be removed”的错误 —— 2019.07.27 Jeffrey var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write); { //cs.Read(decryptBytes, 0, decryptBytes.Length); //cs.Close(); //ms.Close(); //cs.FlushFinalBlock();//用于解决第二次获取小程序Session解密出错的情况 byte[] xXml = Convert.FromBase64String(Input); byte[] msg = new byte[xXml.Length + 32 - xXml.Length % 32]; Array.Copy(xXml, msg, xXml.Length); cs.Write(xXml, 0, xXml.Length); } //cs.Dispose(); xBuff = decode2(ms.ToArray()); } } return(xBuff); }
/// <summary> /// Use a specific encryption provider which inherits from base class SymmetricAlgorithm. /// </summary> public CipherUtility(SymmetricAlgorithm cryptoAlgorithm) { this.CryptoAlgorithm = cryptoAlgorithm ?? new AesManaged(); }
/// <summary> /// 对称加密类的构造函数 /// </summary> public Rijndael() { mobjCryptoService = new RijndaelManaged(); Key = "haitian85)(*&^%"; }
/* static DESTransform () { spBoxes = new uint [64 * 8]; int [] pBox = new int [32]; for (int p = 0; p < 32; p++) { for (int i = 0; i < 32; i++) { if (p == pTab [i]) { pBox [p] = i; break; } } } for (int s = 0; s < 8; s++) { // for each S-box int sOff = s << 6; for (int i = 0; i < 64; i++) { // inputs uint sp=0; int indx = (i & 0x20) | ((i & 1) << 4) | ((i >> 1) & 0xF); for (int j = 0; j < 4; j++) { // for each bit in the output if ((sBoxes [sOff + indx] & (8 >> j)) != 0) { sp |= (uint) (1 << (31 - pBox [(s << 2) + j])); } } spBoxes [sOff + i] = sp; } } leftRotTotal = new byte [leftRot.Length]; for (int i = 0; i < leftRot.Length; i++) { int r = 0; for (int j = 0; j <= i; r += leftRot [j++]) { // no statement (confuse the compiler == warning) } leftRotTotal [i] = (byte) r; } InitPermutationTable (ipBits, out ipTab); InitPermutationTable (fpBits, out fpTab); } */ // Default constructor. internal DESTransform (SymmetricAlgorithm symmAlgo, bool encryption, byte[] key, byte[] iv) : base (symmAlgo, encryption, iv) { byte[] clonedKey = null; if (key == null) { key = GetStrongKey (); clonedKey = key; // no need to clone } // note: checking (semi-)weak keys also checks valid key length if (DES.IsWeakKey (key) || DES.IsSemiWeakKey (key)) { string msg = Locale.GetText ("This is a known weak, or semi-weak, key."); throw new CryptographicException (msg); } if (clonedKey == null) clonedKey = (byte[]) key.Clone (); keySchedule = new byte [KEY_BYTE_SIZE * 16]; byteBuff = new byte [BLOCK_BYTE_SIZE]; dwordBuff = new uint [BLOCK_BYTE_SIZE / 4]; SetKey (clonedKey); }
/// <summary> /// Decrypts the current encrypted message using the secret keys /// in skrKeyRing and the given passphrase. /// </summary> /// <param name="skrKeyRing">The secret keyring containing all the /// secret keys know to the sytem.</param> /// <param name="strPassphrase">The passphrase that was used to /// encrypt the secret key material in the key that decrypts /// the message.</param> /// <returns>Returns the message that was encrypted. Usually this is /// an compressed or literal message.</returns> /// <remarks>No remarks</remarks> public Message Decrypt(SecretKeyRing skrKeyRing, string strPassphrase) { TransportableSecretKey tskSecretKey = new TransportableSecretKey(); AsymSessionKeyPacket askpSessionKey = new AsymSessionKeyPacket(); bool bFound = false; // let's see, if we can find a fitting Sessionkey packet IEnumerator ieSessionkeys = esKeys.AsymKeys.GetEnumerator(); while (ieSessionkeys.MoveNext()) { if (!(ieSessionkeys.Current is AsymSessionKeyPacket)) { throw new Exception("Strange Error!"); } AsymSessionKeyPacket askpKey = (AsymSessionKeyPacket)ieSessionkeys.Current; ulong lKeyID = askpKey.KeyID; TransportableSecretKey tskKey = skrKeyRing.Find(lKeyID); if (tskKey != null) { bFound = true; tskSecretKey = tskKey; askpSessionKey = askpKey; } } if (!bFound) { throw new Exception("No fitting secret key was found to decrypt the message!"); } askpSessionKey.DecryptSessionKey(tskSecretKey, strPassphrase); byte[] bKey = askpSessionKey.SessionKey; Packet[] pContent = new Packet[0]; try { SymmetricAlgorithm saAlgo = CipherHelper.CreateSymAlgorithm(askpSessionKey.SymmetricAlgorithm); pContent = sepData.Decrypt(bKey, saAlgo); } catch (Exception e) { throw new System.Exception("Decryption of the Message failed: " + e.Message); } // now we need to look what kind of message was hidden in the // encrypted data // it can be either a literal message LiteralMessage lmLiteral = new LiteralMessage(); try { int iPos = lmLiteral.ParseMessage(pContent); return(lmLiteral); } catch (Exception) {} // or an compressed Message CompressedMessage cmCompressed = new CompressedMessage(); try { int iPos = cmCompressed.ParseMessage(pContent); return(cmCompressed); } catch (Exception) {} throw new System.ArgumentException("Encrypted package content is not a valid message!"); }
protected Symmetric(SymmetricAlgorithm symmetricAlgorithm) { symmetric = symmetricAlgorithm; }
/// <summary> /// decrypt the contents of and encrypted file. /// </summary> /// <param name="instrm">encrypted file</param> /// <param name="strm">output file for decrypted contents.</param> /// <remarks> /// the output stream needs both read and write access /// since the contents will be written to it, /// and then the contents will be verified via the hash /// embeded in the encrypted file's header. /// </remarks> public void decrypt(Stream instrm, FileStream strm) { byte[] origHash = null; IncrementalHash incHash; if (!strm.CanRead) { throw new ArgumentException("Expected to be able to read from output file to verify hash"); } var enchdr = _readBytes(instrm); #if false { /* verify signature. */ var sig = _readBytes(instrm); incHash.AppendData(enchdr); var enchash = _computeHash(instrm, incHash); var sigisok = _rsa.VerifyHash(enchash, sig, _hash, RSASignaturePadding.Pkcs1); if (!sigisok) { throw new System.Security.SecurityException("Hash Signature validation failed."); } } #endif { var dec = _rsa.Decrypt(enchdr, RSAEncryptionPadding.OaepSHA1); var hdr = FileHeader.Create(dec); HashAlgorithmName[] names = new HashAlgorithmName[] { HashAlgorithmName.MD5, HashAlgorithmName.SHA1, HashAlgorithmName.SHA256 }; foreach (var n in names) { if (n.Name == hdr.hashname) { _hash = n; } } origHash = hdr.hash; incHash = IncrementalHash.CreateHash(_hash); if (hdr.algo == "AES") { _algo = Aes.Create(); _algo.Mode = CipherMode.CBC; _algo.Padding = PaddingMode.PKCS7; _algo.KeySize = hdr.key.Length * 8; _algo.Key = hdr.key; _algo.IV = hdr.iv; } } var xform = _algo.CreateDecryptor(); var cryptostrm = new CryptoStream(instrm, xform, CryptoStreamMode.Read); cryptostrm.CopyTo(strm); cryptostrm.Dispose(); { /* verify output file. */ strm.Seek(0, SeekOrigin.Begin); var writtenhash = _computeHash(strm, incHash); for (int i = 0; i < writtenhash.Length; ++i) { if (origHash[i] != writtenhash[i]) { throw new ArgumentException("Written data does not match encrypted data."); } } } }