/// <summary> /// Returns a platform-specific algorithm that conforms to the prescribed platform-neutral algorithm. /// </summary> /// <param name="algorithm">The PCL algorithm.</param> /// <returns> /// The platform-specific algorithm. /// </returns> private static Platform.SymmetricAlgorithm GetAlgorithm(SymmetricAlgorithm algorithm) { #if SILVERLIGHT || __IOS__ switch (algorithm) { case SymmetricAlgorithm.AesCbcPkcs7: return(new Platform.AesManaged()); default: throw new NotSupportedException(); } #else Platform.SymmetricAlgorithm platform = Platform.SymmetricAlgorithm.Create( algorithm.GetName().GetString()); if (platform == null) { throw new NotSupportedException(); } platform.Mode = GetMode(algorithm); platform.Padding = GetPadding(algorithm); return(platform); #endif }
public NetCryptoProviderBase(NetPeer peer, SymmetricAlgorithm algo) : base(peer) { m_algorithm = algo; m_algorithm.GenerateKey(); m_algorithm.GenerateIV(); }
public static string Decrypt(string encryptedText) { try { if (String.IsNullOrWhiteSpace(encryptedText)) { return(""); } byte[] encryptedTextBytes = Convert.FromBase64String(encryptedText); MemoryStream ms = new MemoryStream(); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); byte[] rgbIV = Encoding.ASCII.GetBytes(rgbIVValue); byte[] key = Encoding.ASCII.GetBytes(keyValue); CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length); cs.Close(); return(Encoding.UTF8.GetString(ms.ToArray())); } catch (Exception) { return(encryptedText); } }
public CryptoTransformBase(SymmetricAlgorithm algo, bool encryption, byte[] rgbKey, byte[] rgbIV) { if (rgbKey == null) throw new CryptographicException("Invalid (null) key"); BlockSizeByte = (algo.BlockSize >> 3); if (rgbIV == null) { iv = new byte[BlockSizeByte]; this.Random(iv, 0, 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); } iv = (byte[])rgbIV.Clone(); } encrypt = encryption; padding = algo.Padding; // transform buffer workBuff = new byte[BlockSizeByte]; }
public AccountSettingsProvider() { _algorithm = new RijndaelManaged(); _hashAlgorithm = new SHA384Managed(); _storage = CompositionManager.Get<IStorage>(); SetDocument(_storage.CombineFullPath("Accounts Settings.xml")); }
/// <summary> /// 解密 /// </summary> /// <param name="value">要解密的值</param> /// <returns>解密后值</returns> public static string DecryptString(string value) { ICryptoTransform ct; MemoryStream ms; CryptoStream cs; byte[] byt; //// 设置加密Key string txtKey = "tkGGRmBErvc="; //// 设置加密IV string txtIV = "Kl7ZgtM1dvQ="; mcsp = SetEnc(); byte[] byt2 = Convert.FromBase64String(txtKey); mcsp.Key = byt2; byte[] byt3 = Convert.FromBase64String(txtIV); mcsp.IV = byt3; ct = mcsp.CreateDecryptor(mcsp.Key, mcsp.IV); byt = Convert.FromBase64String(value); ms = new MemoryStream(); cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); return Encoding.UTF8.GetString(ms.ToArray()); }
public static byte[] Decrypt(this byte[] data, DeriveBytes key, SymmetricAlgorithm algorithmUsing = null, string initialVector = "OFRna73m*aze01xY", int keySize = 256) { if (data.IsNull()) return null; algorithmUsing = algorithmUsing.NullCheck(() => new RijndaelManaged()); Guard.NotEmpty(initialVector, "initialVector"); using (DeriveBytes derivedPassword = key) { using (SymmetricAlgorithm symmetricKey = algorithmUsing) { symmetricKey.Mode = CipherMode.CBC; byte[] plainTextBytes; using ( ICryptoTransform decryptor = symmetricKey.CreateDecryptor(derivedPassword.GetBytes(keySize/8), initialVector.ToByteArray())) { using (var memStream = new MemoryStream(data)) { using (var cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read)) { plainTextBytes = cryptoStream.ReadAllBinary(); } } } symmetricKey.Clear(); return plainTextBytes; } } }
/// <summary> /// Constructor for the offline context which allows a symmetric encryption algorithm to be specified. /// </summary> /// <param name="schema">The schema that specifies the set of the collections for the context.</param> /// <param name="scopeName">The scope name used to identify the scope on the service.</param> /// <param name="cachePath">Path in isolated storage where the data will be stored.</param> /// <param name="uri">Uri of the scopeName. Used to intialize the CacheController.</param> /// <param name="encryptionAlgorithm">The symmetric encryption algorithm to use for files on disk</param> /// <remarks> /// If the Uri specified is different from the one that is stored in the cache path, the /// Load method will throw an InvalidOperationException. /// </remarks> public IsolatedStorageOfflineContext(IsolatedStorageSchema schema, string scopeName, string cachePath, Uri uri, SymmetricAlgorithm encryptionAlgorithm) { if (schema == null) { throw new ArgumentNullException("schema"); } if (string.IsNullOrEmpty(scopeName)) { throw new ArgumentNullException("scopeName"); } if (string.IsNullOrEmpty(cachePath)) { throw new ArgumentNullException("cachePath"); } if (uri == null) { throw new ArgumentNullException("uri"); } _isDisposed = false; _schema = schema; _scopeUri = uri; _scopeName = scopeName; _cachePath = cachePath; _storageHandler = new SQLiteStorageHandler(this, schema, cachePath, encryptionAlgorithm); _saveSyncLock = new AutoResetLock(); CreateCacheController(); }
public static string AESDecrypt(string decryptStr, string decryptKey) { string result; if (string.IsNullOrWhiteSpace(decryptStr)) { result = string.Empty; } else { decryptKey = StringHelper.SubString(decryptKey, 32); decryptKey = decryptKey.PadRight(32, ' '); byte[] array = System.Convert.FromBase64String(decryptStr); System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm = System.Security.Cryptography.Rijndael.Create(); symmetricAlgorithm.Key = System.Text.Encoding.UTF8.GetBytes(decryptKey); symmetricAlgorithm.IV = SecureHelper._aeskeys; byte[] array2 = new byte[array.Length]; using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(array)) { using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, symmetricAlgorithm.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read)) { cryptoStream.Read(array2, 0, array2.Length); cryptoStream.Close(); memoryStream.Close(); } } result = System.Text.Encoding.UTF8.GetString(array2).Replace("\0", ""); } return(result); }
public static byte[] EncryptBytes(SymmetricAlgorithm symAlg, byte[] inBlock) { ICryptoTransform xfrm = symAlg.CreateEncryptor(); byte[] outBlock = xfrm.TransformFinalBlock(inBlock, 0, inBlock.Length); return outBlock; }
public static string AESEncrypt(string encryptStr, string encryptKey) { string result; if (string.IsNullOrWhiteSpace(encryptStr)) { result = string.Empty; } else { encryptKey = StringHelper.SubString(encryptKey, 32); encryptKey = encryptKey.PadRight(32, ' '); System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm = System.Security.Cryptography.Rijndael.Create(); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(encryptStr); symmetricAlgorithm.Key = System.Text.Encoding.UTF8.GetBytes(encryptKey); symmetricAlgorithm.IV = SecureHelper._aeskeys; byte[] inArray = null; using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) { using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, symmetricAlgorithm.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) { cryptoStream.Write(bytes, 0, bytes.Length); cryptoStream.FlushFinalBlock(); inArray = memoryStream.ToArray(); cryptoStream.Close(); memoryStream.Close(); } } result = System.Convert.ToBase64String(inArray); } return(result); }
public static byte[] Desencriptar(byte[] mensajeEncriptado, SymmetricAlgorithm algoritmo) { int numeroBytesDesencriptados = 0; // La clase SymmetricAlgorithm delega el proceso de desencriptación de datos // Una instancia de ICryptoTransform transforma texto plano en texto cifrado o vice versa. // Las siguiente sentencia demuestra como crear transformaciones usando CreateDecryptor. byte[] mensajeDesencriptado = new byte[mensajeEncriptado.Length]; // Crear una ICryptoTransform que puede ser usada para desencriptar datos ICryptoTransform desencriptador = algoritmo.CreateDecryptor(); // Procedemos a descifrar el mensaje MemoryStream memoryStream = new MemoryStream(mensajeEncriptado); // Creamos el CryptoStream CryptoStream cryptoStream = new CryptoStream(memoryStream, desencriptador, CryptoStreamMode.Read); // Decrypting data and get the count of plain text bytes. numeroBytesDesencriptados = cryptoStream.Read(mensajeDesencriptado, 0, mensajeDesencriptado.Length); // Liberamos recursos. memoryStream.Close(); cryptoStream.Close(); return mensajeDesencriptado; }
public static string Encryption(string UserID) { try { string EncryptedID = ""; byte[] clearTextBytes = Encoding.UTF8.GetBytes(UserID); System.Security.Cryptography.SymmetricAlgorithm SymmetricAlgorithm = SymmetricAlgorithm.Create(); MemoryStream MemoryStream = new MemoryStream(); byte[] keyByte = Encoding.ASCII.GetBytes(key); CryptoStream cs = new CryptoStream(MemoryStream, SymmetricAlgorithm.CreateEncryptor(keyByte, keyByte), CryptoStreamMode.Write); cs.Write(clearTextBytes, 0, clearTextBytes.Length); cs.Close(); #region Convert byte[] to hex string byte[] byteArray = MemoryStream.ToArray(); var hex = new StringBuilder(byteArray.Length * 2); foreach (var b in byteArray) { hex.AppendFormat("{0:x2}", b); } #endregion EncryptedID = hex.ToString(); return(EncryptedID); } catch (Exception ex) { //Utility.LogError(ex, "Reem", "Encryption"); return(string.Empty); } }
public Main( RemoteHooking.IContext InContext, String InChannelName) { // connect to host... Interface = RemoteHooking.IpcConnectClient<FileMonInterface>(InChannelName); myChannelName = InChannelName; aes = new AesCryptoServiceProvider(); dataIgnition = new byte[MAX_BLOCK_SIZE]; for (int i = 0; i < MAX_BLOCK_SIZE; i++) { dataIgnition[i] = (byte)i; } dataToEncrypt = new byte[MAX_BLOCK_SIZE]; OutputDebugString(Encoding.ASCII.GetString(dataIgnition)); Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(Password, Encoding.ASCII.GetBytes(Salt)); aes.Key = key.GetBytes(aes.KeySize / 8); aes.Padding = PaddingMode.Zeros; byte[] IV = Interface.GetIV(); if (IV == null) { aes.GenerateIV(); Interface.SaveIV(aes.IV); } aes.Mode = CipherMode.CFB; Interface.Ping(); }
public static string DecryptString(string EncryptedText, Type baseOption) { byte[] encryptedTextBytes; if (baseOption == typeof(Int64)) { encryptedTextBytes = Convert.FromBase64String(EncryptedText); } else { encryptedTextBytes = Base32Encoding.ToBytes(EncryptedText); } MemoryStream ms = new MemoryStream(); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); byte[] rgbIV = Encoding.ASCII.GetBytes("lbavittzoaofgcqz"); byte[] key = Encoding.ASCII.GetBytes("rymnwalaspjdbygwagsxhzzcroywhciu"); CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length); cs.Close(); return(Encoding.UTF8.GetString(ms.ToArray())); }
public HashUtilities() { // Default symmetric algorithm _mCryptoService = new RijndaelManaged(); _mCryptoService.Mode = CipherMode.CBC; _mAlgorithm = ServiceProviderEnum.Rijndael; }
public static byte[] Encrypt(string strText, SymmetricAlgorithm key) { // Create a memory stream. MemoryStream ms = new MemoryStream(); // Create a CryptoStream using the memory stream and the // CSP(cryptoserviceprovider) DES key. CryptoStream crypstream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write); // Create a StreamWriter to write a string to the stream. StreamWriter sw = new StreamWriter(crypstream); // Write the strText to the stream. sw.WriteLine(strText); // Close the StreamWriter and CryptoStream. sw.Close(); crypstream.Close(); // Get an array of bytes that represents the memory stream. byte[] buffer = ms.ToArray(); // Close the memory stream. ms.Close(); // Return the encrypted byte array. return buffer; }
public DES(string key, string iv) { if (key.Length > 8) { key = key.Substring(0, 8); } if (iv.Length > 8) { iv = iv.Substring(0, 8); } this.Key = this.TextEncode.GetBytes(key); this.IV = this.TextEncode.GetBytes(iv); try { des = new System.Security.Cryptography.DESCryptoServiceProvider(); des.Mode = CipherMode.ECB; des.Key = Key; des.IV = IV; decryptor = des.CreateDecryptor(this.Key, this.IV); encryptor = des.CreateEncryptor(this.Key, this.IV); } catch (System.Exception ex) { log.Error(ex.ToString()); } }
/// <summary> /// Initialize CipherTextStealingMode with a specific symmetric algorithm /// </summary> /// <param name="symmetricAlgorithm">The symmetric algorithm</param> public CipherTextStealingMode(SymmetricAlgorithm symmetricAlgorithm) { // in CTS Mode there is no padding symmetricAlgorithm.Padding = PaddingMode.None; // set the symmetric algorithm's mode to ECB // (for single block encryption and decryption) symmetricAlgorithm.Mode = CipherMode.ECB; // get the symmetric algorithm's block size in bytes blockSize = symmetricAlgorithm.BlockSize / 8; if (blockSize != symmetricAlgorithm.IV.Length) { throw new ArgumentException( "The IV size should equal to the block size."); } // initialize local IV iv = symmetricAlgorithm.IV; // initialize cipher state using the symmetric algorithms's IV cipherState = new byte[blockSize]; symmetricAlgorithm.IV.CopyTo(cipherState, 0); // create encryptor and decryptor encryptor = symmetricAlgorithm.CreateEncryptor(); decryptor = symmetricAlgorithm.CreateDecryptor(); }
private static string Decrypt(byte[] cipher, string passPhrase, string salt, SymmetricAlgorithm algorithm) { var saltBytes = Encoding.UTF8.GetBytes(salt); algorithm.Padding = PaddingMode.None; using (algorithm) { using (var password = new Rfc2898DeriveBytes(passPhrase, saltBytes)) { algorithm.Key = password.GetBytes(algorithm.KeySize / 8); algorithm.IV = password.GetBytes(algorithm.BlockSize / 8); using (var memStream = new MemoryStream(cipher)) { using ( var cryptoStream = new CryptoStream(memStream, algorithm.CreateDecryptor(), CryptoStreamMode.Read)) { using (var sr = new StreamReader(cryptoStream)) { return sr.ReadToEnd(); } } } } } }
/// <summary> /// Construtor com o tipo de criptografia a ser usada Você pode escolher o tipo pelo Enum chamado CryptProvider. /// </summary> /// <param name="cryptProvider">Tipo de criptografia.</param> public Cryptography( CryptProvider cryptProvider ) { // Seleciona algoritmo simétrico switch ( cryptProvider ) { case CryptProvider.Rijndael: _algorithm = new RijndaelManaged ( ); _cryptProvider = CryptProvider.Rijndael; break; case CryptProvider.RC2: _algorithm = new RC2CryptoServiceProvider ( ); _cryptProvider = CryptProvider.RC2; break; case CryptProvider.DES: _algorithm = new DESCryptoServiceProvider ( ); _cryptProvider = CryptProvider.DES; break; case CryptProvider.TripleDES: _algorithm = new TripleDESCryptoServiceProvider ( ); _cryptProvider = CryptProvider.TripleDES; break; } _algorithm.Mode = CipherMode.CBC; }
public SymCryptography(string serviceProviderName) { // Select symmetric algorithm switch (serviceProviderName.ToLower()) { case "rijndael": serviceProviderName = "Rijndael"; _algorithm = ServiceProviderEnum.Rijndael; break; case "rc2": serviceProviderName = "RC2"; _algorithm = ServiceProviderEnum.RC2; break; case "des": serviceProviderName = "DES"; _algorithm = ServiceProviderEnum.DES; break; case "tripledes": serviceProviderName = "TripleDES"; _algorithm = ServiceProviderEnum.TripleDES; break; } // Set symmetric algorithm _cryptoService = (SymmetricAlgorithm)CryptoConfig.CreateFromName(serviceProviderName); _cryptoService.Mode = CipherMode.CBC; }
public SymCryptography(ServiceProviderEnum serviceProvider) { // Select symmetric algorithm switch (serviceProvider) { case ServiceProviderEnum.Rijndael: mCryptoService = new RijndaelManaged(); mAlgorithm = ServiceProviderEnum.Rijndael; break; case ServiceProviderEnum.RC2: mCryptoService = new RC2CryptoServiceProvider(); mAlgorithm = ServiceProviderEnum.RC2; break; case ServiceProviderEnum.DES: mCryptoService = new DESCryptoServiceProvider(); mAlgorithm = ServiceProviderEnum.DES; break; case ServiceProviderEnum.TripleDES: mCryptoService = new TripleDESCryptoServiceProvider(); mAlgorithm = ServiceProviderEnum.TripleDES; break; } mCryptoService.Mode = CipherMode.CBC; }
public static string DecryptString(string EncryptedText) { if (EncryptedText == "") { return(EncryptedText); } byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText); MemoryStream ms = new MemoryStream(); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); byte[] rgbIV = Encoding.ASCII.GetBytes("ryojvlzmdalyglrj"); byte[] key = Encoding.ASCII.GetBytes("hcxilkqbbhczfeultgbskdmaunivmfuo"); CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length); cs.Close(); return(Encoding.UTF8.GetString(ms.ToArray())); }
/// <summary> /// 通过制定的算法模式来加密一个字符串(不支持中文) /// </summary> /// <param name="Algorithm">解密的算法</param> /// <param name="ValueToDeCrypt">将要被解密的值</param> private static String DeCrypt(SymmetricAlgorithm Algorithm, String ValueToDeCrypt) { // Put the input string into the byte array. Byte[] InputByteArray = new Byte[ValueToDeCrypt.Length / 2]; for (Int32 i = 0; i < ValueToDeCrypt.Length / 2; i++) { Int32 Value = (Convert.ToInt32(ValueToDeCrypt.Substring(i * 2, 2), 16)); InputByteArray[i] = (Byte)Value; } // Create the crypto objects. String EncryptionKey = WhfEncryption.EncryptionKey; // Create the key. Byte[] Key = ASCIIEncoding.ASCII.GetBytes(EncryptionKey); Algorithm.Key = (Byte[])WhfEncryption.ReDim(Key, Algorithm.Key.Length); Algorithm.IV = (Byte[])WhfEncryption.ReDim(Key, Algorithm.IV.Length); MemoryStream MemStream = new MemoryStream(); CryptoStream CrypStream = new CryptoStream(MemStream, Algorithm.CreateDecryptor(), CryptoStreamMode.Write); // Flush the data through the crypto stream into the memory stream. CrypStream.Write(InputByteArray, 0, InputByteArray.Length); CrypStream.FlushFinalBlock(); // Get the decrypted data back from the memory stream. StringBuilder StringBuilder = new StringBuilder(); for (Int32 i = 0; i < MemStream.ToArray().Length; i++) { StringBuilder.Append((Char)MemStream.ToArray()[i]); } return StringBuilder.ToString(); }
/// <summary> /// Initializes a new StringEncryption instance. /// </summary> /// <param name="bulkCipher">The bulk cipher algorithm to use.</param> /// <param name="hash">The hash algorithm to use.</param> /// <exception cref="ArgumentNullException">One of the parameters is a null reference.</exception> public StringEncryption(SymmetricAlgorithm bulkCipher, HashAlgorithm hash) { if (bulkCipher == null) throw new ArgumentNullException("bulkCipher", ResourceController.GetString("Error_ParamNull")); if (hash == null) throw new ArgumentNullException("hash", ResourceController.GetString("Error_ParamNull")); Init(bulkCipher, hash); }
/// <summary> /// 解密数据. /// </summary> /// <param name="Doc"></param> /// <param name="Alg"></param> public static void Decrypt(XmlDocument Doc, SymmetricAlgorithm Alg) { // Check the arguments. if (Doc == null) throw new ArgumentNullException("Doc"); if (Alg == null) throw new ArgumentNullException("Alg"); // Find the EncryptedData element in the XmlDocument. XmlElement encryptedElement = Doc.GetElementsByTagName("EncryptedData")[0] as XmlElement; // If the EncryptedData element was not found, throw an exception. if (encryptedElement == null) { throw new XmlException("The EncryptedData element was not found."); } // Create an EncryptedData object and populate it. EncryptedData edElement = new EncryptedData(); edElement.LoadXml(encryptedElement); // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(); // Decrypt the element using the symmetric key. byte[] rgbOutput = exml.DecryptData(edElement, Alg); // Replace the encryptedData element with the plaintext XML element. exml.ReplaceData(encryptedElement, rgbOutput); }
public Crypter(SymmetricAlgorithm symmetricAlg) { if (symmetricAlg == null) throw new ArgumentNullException(); algorithm = symmetricAlg; }
public AES(string key, string iv) { this.Key = this.TextEncode.GetBytes(key); this.IV = this.TextEncode.GetBytes(iv); //System.Security.Cryptography.Aes aes = new System.Security.Cryptography.AesCryptoServiceProvider(); //aes = new System.Security.Cryptography.AesCryptoServiceProvider(); aes = new System.Security.Cryptography.RijndaelManaged(); aes.Key = Key; aes.IV = IV; aes.KeySize = 128; aes.Mode = CipherMode.CBC; aes.BlockSize = 128; aes.Padding = PaddingMode.Zeros; try { decryptor = aes.CreateDecryptor(this.Key, this.IV); encryptor = aes.CreateEncryptor(this.Key, this.IV); } catch (System.Exception ex) { log.Error(ex.ToString()); } }
public EncryptionWrapper(string algorithmName) { if (string.IsNullOrEmpty(algorithmName)) throw new ArgumentNullException("algorithmName"); algorithm = SymmetricAlgorithm.Create(algorithmName); }
public ColumnsSettingsProvider(string docPath) { _algorithm = new RijndaelManaged(); _hashAlgorithm = new SHA384Managed(); SetDocument(docPath); }
public static string DecryptString(string EncryptedText, string Key) { byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText); //byte[] encryptedTextBytes = Encoding.UTF8.GetBytes(EncryptedText); MemoryStream ms = new MemoryStream(); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); byte[] rgbIV = Encoding.ASCII.GetBytes("ryojvlzmdalyglrj"); byte[] key = Encoding.ASCII.GetBytes(CompleteKey32(Key)); CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length); //ms.Position = 0; string returnValue = Encoding.UTF8.GetString(ms.ToArray()); //string returnValue = Convert.ToBase64String(ms.ToArray()); try { cs.Close(); } catch (Exception ex) { string msg = ex.Message; } return(returnValue); }
public static string DecryptString(string EncryptedText, string iv = "", string key = "") { try { iv = (iv + Röschti).Substring(0, 16); key = (key + Bradwurscht).Substring(0, 32); byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); MemoryStream ms = new MemoryStream(); byte[] ba_rgbIV = Encoding.ASCII.GetBytes(iv); byte[] ba_key = Encoding.ASCII.GetBytes(key); CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(ba_key, ba_rgbIV), CryptoStreamMode.Write); cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length); cs.Close(); rijn.Dispose(); rijn = null; return(Encoding.UTF8.GetString(ms.ToArray())); } catch (Exception) { return(null); } }
/// <summary> /// Returns a platform-specific algorithm that conforms to the prescribed platform-neutral algorithm. /// </summary> /// <returns> /// The platform-specific algorithm. /// </returns> private Platform.SymmetricAlgorithm GetAlgorithm() { #if SILVERLIGHT if (this.Name == SymmetricAlgorithmName.Aes && this.Mode == SymmetricAlgorithmMode.Cbc && this.Padding == SymmetricAlgorithmPadding.PKCS7) { return(new Platform.AesManaged()); } else { throw new NotSupportedException(); } #else Platform.SymmetricAlgorithm platform = null; #if __IOS__ if (this.Name == SymmetricAlgorithmName.Aes) { platform = new Platform.AesManaged(); } #else platform = Platform.SymmetricAlgorithm.Create(this.Name.GetString()); #endif if (platform == null) { throw new NotSupportedException(); } platform.Mode = GetMode(this.Mode); platform.Padding = GetPadding(this.Padding); return(platform); #endif }
private static void ConfigurarAlgoritmo(SymmetricAlgorithm algoritmo) { algoritmo.KeySize = 256; algoritmo.BlockSize = 128; algoritmo.Mode = CipherMode.CBC; algoritmo.Padding = PaddingMode.PKCS7; }
private static byte[] DecryptBytes(SymmetricAlgorithm symAlg, byte[] inBytes) { ICryptoTransform xfrm = symAlg.CreateDecryptor(); byte[] outBlock = xfrm.TransformFinalBlock(inBytes, 0, inBytes.Length); return outBlock; }
private static XmlDocument DecryptXmlDocument(XmlDocument encryptedXmlDocument, SymmetricAlgorithm sharedKey) { // Создание объекта для дешифрации XML var encryptedXml = new GostEncryptedXml(encryptedXmlDocument); var nsManager = new XmlNamespaceManager(encryptedXmlDocument.NameTable); nsManager.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); // Поиск всех зашифрованных XML-элементов var encryptedDataList = encryptedXmlDocument.SelectNodes("//enc:EncryptedData", nsManager); if (encryptedDataList != null) { foreach (XmlElement encryptedData in encryptedDataList) { // Загрузка элемента EncryptedData var elementEncryptedData = new EncryptedData(); elementEncryptedData.LoadXml(encryptedData); // Расшифровка элемента EncryptedData var decryptedData = encryptedXml.DecryptData(elementEncryptedData, sharedKey); // Замена элемента EncryptedData его расшифрованным представлением encryptedXml.ReplaceData(encryptedData, decryptedData); } } return encryptedXmlDocument; }
/// <summary> /// 構造函數,設置加密算法為Rijndael(AES) /// </summary> private EncryptClass() { mCryptoService = new RijndaelManaged(); mCryptoService.Mode = CipherMode.CBC; //默認密碼 mKey = "wqdj~yriu!@*k0_^fa7431%p$#=@hd+&"; }
public void Encrypt( SymmetricAlgorithm algorithm, byte[] buffer, int offset, int length ) { byte[] iv; byte[] cipherText; GenerateIVAndEncrypt( algorithm, buffer, offset, length, out iv, out cipherText ); CipherData.SetCipherValueFragments( iv, cipherText ); }
/// <summary> /// Symmetrics decrpyt. /// </summary> /// <param name="str">The STR to decrpyt.</param> /// <param name="mobjCryptoService">A concrete symmetric algorithm.</param> /// <param name="key">The key.</param> /// <returns>The decrpyted str.</returns> public string SymmetricDecrpyt(string str, SymmetricAlgorithm mobjCryptoService, string key) { Check.Require(str != null, "str could not be null!"); byte[] bytIn = Convert.FromBase64String(str); return UTF8Encoding.Unicode.GetString(SymmetricDecrpyt(bytIn, mobjCryptoService, key)); }
static byte[] ExtractIVAndDecrypt( SymmetricAlgorithm algorithm, byte[] cipherText, int offset, int count ) { byte[] iv = new byte[algorithm.BlockSize / 8]; // // Make sure cipherText has enough bytes after the offset, for Buffer.BlockCopy to copy. // if ( cipherText.Length - offset < iv.Length ) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException( SR.GetString( SR.ID6019, cipherText.Length - offset, iv.Length ) ) ); } Buffer.BlockCopy( cipherText, offset, iv, 0, iv.Length ); algorithm.Padding = PaddingMode.ISO10126; algorithm.Mode = CipherMode.CBC; ICryptoTransform decrTransform = null; byte[] plainText = null; try { decrTransform = algorithm.CreateDecryptor( algorithm.Key, iv ); plainText = decrTransform.TransformFinalBlock( cipherText, offset + iv.Length, count - iv.Length ); } finally { if ( decrTransform != null ) { decrTransform.Dispose(); } } return plainText; }
public static string EncryptString(string Value, string parKey) { mCSP = SetEnc(); string iv = "PenS8UCVF7s="; mCSP.IV = Convert.FromBase64String(iv); string key = SetLengthString(parKey.ToString(), 32); mCSP.Key = Convert.FromBase64String(key); ICryptoTransform ct; MemoryStream ms; CryptoStream cs; Byte[] byt = new byte[64]; try { ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV); byt = Encoding.UTF8.GetBytes(Value); ms = new MemoryStream(); cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); return Convert.ToBase64String(ms.ToArray()); } catch (Exception Ex) { throw (new Exception("An error occurred while encrypting string")); } }
static System.Security.Cryptography.SymmetricAlgorithm CreateCam(string key, string IV, bool rij = true) { System.Security.Cryptography.SymmetricAlgorithm a = null; if (rij) { a = new System.Security.Cryptography.RijndaelManaged(); } else { a = new System.Security.Cryptography.AesCryptoServiceProvider(); } a.Mode = System.Security.Cryptography.CipherMode.CBC; a.Padding = System.Security.Cryptography.PaddingMode.Zeros; a.BlockSize = 128; a.KeySize = 256; if (null != IV) { a.IV = System.Convert.FromBase64String(IV); } else { a.GenerateIV(); } if (null != key) { a.Key = System.Convert.FromBase64String(key); } return(a); }
/// <summary> /// Initializes a new instance of the <see cref="SymmetricCryptographicKey"/> class. /// </summary> /// <param name="algorithm">The algorithm, initialized with the key.</param> /// <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> internal SymmetricCryptographicKey(Platform.SymmetricAlgorithm algorithm, SymmetricAlgorithmName name, SymmetricAlgorithmMode mode, SymmetricAlgorithmPadding padding) { Requires.NotNull(algorithm, "algorithm"); this.algorithm = algorithm; this.Name = name; this.Mode = mode; this.Padding = padding; }
public static byte[] smethod_9(byte[] byte_0, string string_0) { System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm = System.Security.Cryptography.SymmetricAlgorithm.Create(); System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); byte[] bytes = System.Text.Encoding.ASCII.GetBytes(string_0); byte[] rgbIV = bytes; System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, symmetricAlgorithm.CreateEncryptor(bytes, rgbIV), System.Security.Cryptography.CryptoStreamMode.Write); cryptoStream.Write(byte_0, 0, byte_0.Length); cryptoStream.Close(); return(memoryStream.ToArray()); }
/// <summary> /// Method to decrypt the ciphertext, with the symmetric key passed /// </summary> /// <param name="aesAlg"></param> /// <param name="cipherText"></param> /// <returns></returns> static string Decrypt(System.Security.Cryptography.SymmetricAlgorithm aesAlg, byte[] cipherText) { var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (StreamReader srDecrypt = new StreamReader( new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))) { return(srDecrypt.ReadToEnd()); } } }
/// <summary> /// Encrypt a given message, provided with key and IV /// </summary> /// <param name="aesAlg"></param> /// <param name="plainText"></param> /// <returns></returns> static byte[] Encrypt(System.Security.Cryptography.SymmetricAlgorithm aesAlg, string plainText) { var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (StreamWriter swEncrypt = new StreamWriter(new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))) { swEncrypt.Write(plainText); } return(msEncrypt.ToArray()); } }
public static string EncodePassword(string source) { byte[] binarySource = Encoding.UTF8.GetBytes(source); System.Security.Cryptography.SymmetricAlgorithm rijn = System.Security.Cryptography.SymmetricAlgorithm.Create(); MemoryStream ms = new MemoryStream(); byte[] rgbIV = Encoding.ASCII.GetBytes("lkjhasdfyuiwhcnt"); byte[] key = Encoding.ASCII.GetBytes("tkw123aaaa"); CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(binarySource, 0, binarySource.Length); cs.Close(); return(Convert.ToBase64String(ms.ToArray())); }
//private const string key1 = "aaaaaaaaaaaaaaaa"; //private const string key2 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; private string EncryptString(string ClearText) { byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); MemoryStream ms = new MemoryStream(); byte[] rgbIV = Encoding.ASCII.GetBytes(key1); byte[] key = Encoding.ASCII.GetBytes(key2); CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(clearTextBytes, 0, clearTextBytes.Length); cs.Close(); return(Convert.ToBase64String(ms.ToArray())); }
public static void Encrypt(XmlDocument Doc, string ElementName, System.Security.Cryptography.SymmetricAlgorithm Key) { XmlElement inputElement = Doc.GetElementsByTagName(ElementName)[0] as XmlElement; EncryptedXml encryptedXml = new EncryptedXml(); byte[] cipherValue = encryptedXml.EncryptData(inputElement, Key, false); EncryptedData encryptedData = new EncryptedData(); encryptedData.Type = "http://www.w3.org/2001/04/xmlenc#Element"; string algorithm = null; if (Key is System.Security.Cryptography.TripleDES) { algorithm = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"; } else { if (Key is System.Security.Cryptography.DES) { algorithm = "http://www.w3.org/2001/04/xmlenc#des-cbc"; } } if (Key is System.Security.Cryptography.Rijndael) { int keySize = Key.KeySize; if (keySize != 128) { if (keySize != 192) { if (keySize == 256) { algorithm = "http://www.w3.org/2001/04/xmlenc#aes256-cbc"; } } else { algorithm = "http://www.w3.org/2001/04/xmlenc#aes192-cbc"; } } else { algorithm = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"; } } encryptedData.EncryptionMethod = new EncryptionMethod(algorithm); encryptedData.CipherData.CipherValue = cipherValue; EncryptedXml.ReplaceElement(inputElement, encryptedData, false); }
/// <summary> /// Create an instance of the symetric algorithm class. /// </summary> private void CreateCipher() { Cipher = new System.Security.Cryptography.RijndaelManaged(); //Cipher = new System.Security.Cryptography.RC2CryptoServiceProvider(); //Cipher = new System.Security.Cryptography.RC4CryptoServiceProvider(); Cipher.Mode = (System.Security.Cryptography.CipherMode) int.Parse(CipherModeDropDownList.SelectedValue); Cipher.Padding = (System.Security.Cryptography.PaddingMode) int.Parse(PaddingModeDropDownList.SelectedValue); WriteLog("cipher.KeySize: " + Cipher.KeySize.ToString() + " bits"); WriteLog("cipher.BlockSize: " + Cipher.BlockSize.ToString() + " bits"); WriteLog("cipher.Key[" + Cipher.Key.Length.ToString() + "]: " + System.BitConverter.ToString(Cipher.Key).Replace("-", "")); WriteLog("cipher.IV[" + Cipher.IV.Length.ToString() + "]: " + System.BitConverter.ToString(Cipher.IV).Replace("-", "")); WriteLog("cipher.Mode: " + Cipher.Mode.ToString()); WriteLog("cipher.Padding: " + Cipher.Padding.ToString()); // Prepare Data; DataBytes = System.Text.Encoding.UTF8.GetBytes(DataTextBox.Text); }
public string EncryptString(string clearText) { byte[] clearTextBytes = Encoding.UTF8.GetBytes(clearText); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); MemoryStream ms = new MemoryStream(); byte[] rgbIV = Encoding.ASCII.GetBytes("ryojvlzffalyglrj"); byte[] key = Encoding.ASCII.GetBytes("hcxilkqbbffffeultgbskdmaunivmfuo"); CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(clearTextBytes, 0, clearTextBytes.Length); cs.Close(); return(Convert.ToBase64String(ms.ToArray())); }
public static string Encrypt(string PlainText) { byte[] PlainBytes = Encoding.UTF8.GetBytes(PlainText); System.Security.Cryptography.SymmetricAlgorithm Alg = System.Security.Cryptography.SymmetricAlgorithm.Create(); MemoryStream MemStr = new MemoryStream(); byte[] KeyBytes = Encoding.ASCII.GetBytes(KEY); byte[] KeyIIBytes = Encoding.ASCII.GetBytes(KEYII); CryptoStream CryptStr = new CryptoStream(MemStr, Alg.CreateEncryptor(KeyBytes, KeyIIBytes), CryptoStreamMode.Write); CryptStr.Write(PlainBytes, 0, PlainText.Length); CryptStr.Close(); return(Convert.ToBase64String(MemStr.ToArray())); }
public static string DecryptString(string EncryptText) { byte[] encryptedTextBytes = Convert.FromBase64String(EncryptText); MemoryStream ms = new MemoryStream(); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); string key1 = "aaaaaaaaaaaaaaaa"; string key2 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] rgbIV = Encoding.ASCII.GetBytes(key1); byte[] key = Encoding.ASCII.GetBytes(key2); CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length); cs.Close(); return(Encoding.UTF8.GetString(ms.ToArray())); }
private static string Encrypt(string Key, string IV, string DataToEncrypt) { //Initialize a encoder/decoder that obtains the bytes from a string System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding(); string EncryptKey = CheckLength(Key); string EncryptIV = CheckLength(IV); string Data = DataToEncrypt.ToString(); byte[] BKey = new byte[16]; BKey = ConvertToByte(EncryptKey); byte[] BIV = new byte[16]; BIV = ConvertToByte(EncryptIV); byte[] BData = encoder.GetBytes(Data); // initialize the Algorithm object. System.Security.Cryptography.SymmetricAlgorithm myDES = System.Security.Cryptography.Rijndael.Create(); //Set the key and IV. myDES.Key = BKey; myDES.IV = BIV; //myDES.BlockSize = 512; // Create an encryptor object... ICryptoTransform encrypt = myDES.CreateEncryptor(); // use the memory stream to store the cipher text... System.IO.MemoryStream ms = new System.IO.MemoryStream(); // Use a cryptoSctream to encrypt the Data CryptoStream cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write); cs.Write(BData, 0, BData.Length); // Flush any residule in the final block cs.FlushFinalBlock(); // get the output and trim the '\0' bytes byte[] bytOut = ms.GetBuffer(); int i = bytOut.Length - 1; while (bytOut[i] == 0) { i--; } //Convert to Base64 because there is difficulty when it comes to normal characters using the normal string methods. string Result = System.Convert.ToBase64String(bytOut, 0, i + 1); return(Result); }
public static string EncryptString(string ClearText) { byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); MemoryStream ms = new MemoryStream(); byte[] rgbIV = Encoding.ASCII.GetBytes("lbavittzoaofgcqz"); byte[] key = Encoding.ASCII.GetBytes("rymnwalaspjdbygwagsxhzzcroywhciu"); CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(clearTextBytes, 0, clearTextBytes.Length); cs.Close(); return(Base32Encoding.ToString(ms.ToArray())); }
private string Decrypt(string EncryptedText) { byte[] EncryptedBytes; try { EncryptedBytes = Convert.FromBase64String(EncryptedText.Substring(0, EncryptedText.IndexOf('$'))); } catch { return(""); } System.Security.Cryptography.SymmetricAlgorithm Alg = System.Security.Cryptography.SymmetricAlgorithm.Create(); MemoryStream MemStr = new MemoryStream(); byte[] KeyBytes = Encoding.ASCII.GetBytes(KEY); byte[] KeyIIBytes = Encoding.ASCII.GetBytes(KEYII); CryptoStream CryptStr = new CryptoStream(MemStr, Alg.CreateDecryptor(KeyBytes, KeyIIBytes), CryptoStreamMode.Write); CryptStr.Write(EncryptedBytes, 0, EncryptedBytes.Length); CryptStr.Close(); return(Encoding.UTF8.GetString(MemStr.ToArray())); }
public static string EncryptString(string ClearText) { string theKey = SystemInfo.deviceUniqueIdentifier; byte[] salt = new byte[] { 0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c }; Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(theKey, salt); byte[] key = pdb.GetBytes(32); byte[] iv = pdb.GetBytes(16); byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, iv), CryptoStreamMode.Write); cs.Write(clearTextBytes, 0, clearTextBytes.Length); cs.Close(); return(Convert.ToBase64String(ms.ToArray())); }
public static string EncryptString(string ClearText) { string retval; byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write)) { cs.Write(clearTextBytes, 0, clearTextBytes.Length); cs.Close(); } retval = Convert.ToBase64String(ms.ToArray()); } return(retval); }
public static string EncryptString(string ClearText, string Key) { byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText); //byte[] clearTextBytes = Convert.FromBase64String(ClearText); System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); MemoryStream ms = new MemoryStream(); byte[] rgbIV = Encoding.ASCII.GetBytes("ryojvlzmdalyglrj"); byte[] key = Encoding.ASCII.GetBytes(CompleteKey32(Key)); CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write); cs.Write(clearTextBytes, 0, clearTextBytes.Length); //ms.Position = 0; //StreamReader reader = new StreamReader(ms); cs.Close(); // return reader.ReadToEnd(); //return Encoding.UTF8.GetString(ms.ToArray()); return(Convert.ToBase64String(ms.ToArray())); }