/// <summary> /// RC2加密 /// </summary> /// <param name="plainStr">明文字符串</param> /// <param name="key">加密密钥支持40~128长度,可以每8位递增(5到16个长度的字符串)</param> /// <param name="iv">加密向量64位以上(8个字节上去字符串)</param> /// <param name="isBase64Code">是否是Base64编码,否则是16进制编码</param> /// <param name="mode">加密模式</param> /// <param name="padding">填充模式</param> /// <returns>密文</returns> public static string RC2Encrypt(string plainStr, string key = DefaultRC2Key, string iv = DefaultRC2IV, bool isBase64Code = true, CipherMode mode = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) { byte[] bKey = Encoding.UTF8.GetBytes(key); byte[] bIV = Encoding.UTF8.GetBytes(iv); byte[] byteArray = Encoding.UTF8.GetBytes(plainStr); string encrypt = null; var rc2 = new RC2CryptoServiceProvider(); try { rc2.Padding = padding; rc2.Mode = mode; using (var mStream = new MemoryStream()) { using (var cStream = new CryptoStream(mStream, rc2.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write)) { cStream.Write(byteArray, 0, byteArray.Length); cStream.FlushFinalBlock(); if (isBase64Code) { encrypt = Convert.ToBase64String(mStream.ToArray()); } else { encrypt = ConvertHelper.ToString(mStream.ToArray()); } } } } catch { } rc2.Clear(); return(encrypt); }
} //compute hash from arguments and return hash value as string private static string GetRC2Hash(string text) { //create variables for computing hash and making it a string UnicodeEncoding UniCode = new UnicodeEncoding(); byte[] HashResult; byte[] msg = UniCode.GetBytes(text); RC2 hashString = new RC2CryptoServiceProvider(); //generate a weak KEY and Initialization Vector for the hash algorithm hashString.GenerateKey(); hashString.GenerateIV(); ICryptoTransform encryptor = hashString.CreateEncryptor(hashString.Key, hashString.IV); string Str = ""; //compute hash with RC2 module and format output as string //convert bytes in HashResult to string values HashResult = encryptor.TransformFinalBlock(msg, 0, msg.Length); foreach (byte x in HashResult) { Str += String.Format("{0:x2}", x); } //clear excess resource usage hashString.Clear(); return(Str); } //compute hash from arguments and return hash value as string
/**===================================================================================================* * ET99加密狗密钥存储区可以存储8个32字节密钥,用于HMAC-MD5计算。实际上相当于种子码算法,通过输入(每次不超过51字节) * 进行计算,产生结果,将结果与应用软件中的数据进行加密处理,产生密文存储在多功能锁中。这样在应用软件使用时,必须通过该 * 把多功能锁中的密钥计算产生的结果与密文进行反向解密处理产生明文,供软件使用。 * * 因为RC2算法默认密钥大小128(Bit)=16字节=加密狗通过密钥存储区内的密钥加密运算后的结果长度 ***===================================================================================================*/ /// <summary> /// RC2 加密(用变长密钥对大量数据进行加密) /// </summary> /// <param name="EncryptString">待加密密文</param> /// <param name="EncryptKey">加密密钥-->即加密狗计算后的16字节数据结果</param> /// <returns>returns</returns> public static string RC2Encrypt(string EncryptString, string EncryptKey) { if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); } if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密钥不得为空")); } if (EncryptKey.Length < 5 || EncryptKey.Length > 16)//RC2算法有效密钥大小40~128(Bit) { throw (new Exception("密钥必须为5-16位")); } string m_strEncrypt = ""; byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider(); try { byte[] m_btEncryptString = Encoding.Default.GetBytes(EncryptString); MemoryStream m_stream = new MemoryStream(); CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write); m_cstream.Write(m_btEncryptString, 0, m_btEncryptString.Length); m_cstream.FlushFinalBlock(); m_strEncrypt = Convert.ToBase64String(m_stream.ToArray()); m_stream.Close(); m_stream.Dispose(); m_cstream.Close(); m_cstream.Dispose(); } catch (IOException ex) { throw ex; } catch (CryptographicException ex) { throw ex; } catch (ArgumentException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { m_RC2Provider.Clear(); } return(m_strEncrypt); }
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // если форму закрывает пользователь (нормальное завершение работы программы) if (e.CloseReason != CloseReason.ApplicationExitCall) { pwd = Encoding.Unicode.GetBytes(passFrase.Edit1.Text); buf = new byte[pwd.Length + randBytes.Length]; // создание объекта для генерации случайной примеси RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider(); // создание буфера для случайной примеси randBytes = new byte[8]; randBytes[1] = 1; randBytes[5] = 1; // получение примеси для секретного ключа //rand.GetBytes(randBytes); // создание объекта для вывода ключа из парольной фразы pdb = new PasswordDeriveBytes(pwd, randBytes); // копирование в буфер примеси randBytes.CopyTo(buf, pwd.Length); // генерация начального вектора для блочного шифрования rc2CSP.GenerateIV(); // вывод ключа шифрования из парольной фразы и примеси rc2CSP.Key = pdb.CryptDeriveKey("RC2", "SHA", rc2CSP.KeySize, rc2CSP.IV); // создание объекта шифрования ICryptoTransform encryptor = rc2CSP.CreateEncryptor(rc2CSP.Key, rc2CSP.IV); // создание нового файла Acc.AccFile = new FileStream(Account.SECFILE, FileMode.Create); // запись в начало зашифрованного файла случайной примеси Acc.AccFile.Write(randBytes, 0, 8); // сохранение в файле начального вектора Acc.AccFile.Write(rc2CSP.IV, 0, rc2CSP.BlockSize / 8); // создание объекта для потока шифрования CrStream = new CryptoStream(Acc.AccFile, encryptor, CryptoStreamMode.Write); // смещение к началу потока в памяти Acc.AccMem.Seek(0, SeekOrigin.Begin); // выделение памяти для буфера ввода-вывода bytes = new byte[Acc.AccMem.Length]; // задание количества непрочитанных байт numBytesToRead = (int)Acc.AccMem.Length; // получение данных из потока в памяти int n = Acc.AccMem.Read(bytes, 0, numBytesToRead); // сохранение фактического количества прочитанных байт numBytesToRead = n; // запись в зашифрованный файл CrStream.Write(bytes, 0, numBytesToRead); // очистка памяти с конфиденциальными данными rc2CSP.Clear(); // закрытие потока шифрования CrStream.Close(); // закрытие файла и потока в памяти Acc.AccMem.Close(); Acc.AccFile.Close(); } }
public static void CreateDecryptor() { // Arrange var provider = new RC2CryptoServiceProvider(); // Act var result = RC2Helper.CreateDecryptor(provider, "sdf2qw2@", 128); // Assert Assert.NotNull(result); result.Dispose(); provider.Clear(); }
/// <summary> /// RC2 解密(用变长密钥对大量数据进行加密) /// </summary> /// <param name="DecryptString">待解密密文</param> /// <param name="DecryptKey">解密密钥</param> /// <returns>returns</returns> public static string RC2Decrypt(string DecryptString, string DecryptKey) { if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); } if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); } if (DecryptKey.Length < 5 || DecryptKey.Length > 16) { throw (new Exception("密钥必须为5-16位")); } byte[] mybtIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; string mystrDecrypt = string.Empty; RC2CryptoServiceProvider myRC2Provider = new RC2CryptoServiceProvider(); try { byte[] mybtDecryptString = Convert.FromBase64String(DecryptString); MemoryStream mystream = new MemoryStream(); CryptoStream mycstream = new CryptoStream(mystream, myRC2Provider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), mybtIV), CryptoStreamMode.Write); mycstream.Write(mybtDecryptString, 0, mybtDecryptString.Length); mycstream.FlushFinalBlock(); mystrDecrypt = Encoding.Default.GetString(mystream.ToArray()); mystream.Close(); mystream.Dispose(); mycstream.Close(); mycstream.Dispose(); } catch (IOException ex) { throw ex; } catch (CryptographicException ex) { throw ex; } catch (ArgumentException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { myRC2Provider.Clear(); } return(mystrDecrypt); }
/// <summary> /// RC2 数据加密 /// </summary> /// <param name="Values">加密后的字符串</param> /// <returns>加密后的字符串</returns> public string RC2Encrypt(string Values) { try { RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); rc2CSP.Mode = CipherMode.CBC; byte[] byt; //Key 和 IV 为 16或24字节 if (null == this._Key) { rc2CSP.GenerateKey(); _Key = Encoding.ASCII.GetString(rc2CSP.Key); } else { if (_Key.Length != 16) { throw new Exception("加密数据出错,详细原因:Key的长度不为 16 byte."); } } if (null == this._IV) { rc2CSP.GenerateIV(); _IV = Encoding.ASCII.GetString(rc2CSP.IV); } else { if (_IV.Length != 8) { throw new Exception("加密数据出错,详细原因:IV的长度不为 8 byte."); } } //return _Key + ":" + Encoding.ASCII.GetBytes(_Key).Length.ToString() + "<br>"+ _IV + ":" + Encoding.ASCII.GetBytes(this._IV).Length.ToString(); byt = Encoding.UTF8.GetBytes(Values); ICryptoTransform ct = rc2CSP.CreateEncryptor(Encoding.ASCII.GetBytes(this._Key), Encoding.ASCII.GetBytes(this._IV)); rc2CSP.Clear(); System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); return(Convert.ToBase64String(ms.ToArray())); } catch (Exception e) { throw new Exception("加密数据出错,详细原因:" + e.Message); } }
/// <summary> /// RC2 解密(用变长密钥对大量数据进行加密) /// </summary> /// <param name="decryptString">待解密密文</param> /// <param name="decryptKey">解密密钥</param> /// <returns>returns</returns> public static string RC2Decrypt(string decryptString, string decryptKey) { if (string.IsNullOrEmpty(decryptString)) { throw (new Exception("密文不得为空")); } if (string.IsNullOrEmpty(decryptKey)) { throw (new Exception("密钥不得为空")); } if (decryptKey.Length < 5 || decryptKey.Length > 16) { throw (new Exception("密钥必须为5-16位")); } string m_strDecrypt = ""; RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider(); try { byte[] m_btDecryptString = Convert.FromBase64String(decryptString); MemoryStream m_stream = new MemoryStream(); CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateDecryptor(Encoding.Default.GetBytes(decryptKey), m_btIV), CryptoStreamMode.Write); m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length); m_cstream.FlushFinalBlock(); m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray()); m_stream.Close(); m_stream.Dispose(); m_cstream.Close(); m_cstream.Dispose(); } catch (IOException ex) { throw ex; } catch (CryptographicException ex) { throw ex; } catch (ArgumentException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { m_RC2Provider.Clear(); } return(m_strDecrypt); }
/// <summary> /// RC2RC2对称分组解密 /// </summary> /// <param name="strDes">解密字符串</param> /// <returns>返回解密后的明文</returns> public static string RC2Decrypt(string strDes) { if (string.IsNullOrEmpty(strDes)) { return(string.Empty); } byte[] objInputByteArray = Convert.FromBase64String(strDes); RC2CryptoServiceProvider objRC2CryptoServiceProvider = new RC2CryptoServiceProvider(); ICryptoTransform objICryptoTransform = objRC2CryptoServiceProvider.CreateDecryptor(RC2KEY, RC2IV); MemoryStream objMemoryStream = new MemoryStream(); CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objICryptoTransform, CryptoStreamMode.Write); objCryptoStream.Write(objInputByteArray, 0, objInputByteArray.Length); objCryptoStream.FlushFinalBlock(); objRC2CryptoServiceProvider.Clear(); return(Encoding.UTF8.GetString(objMemoryStream.ToArray())); }
/// <summary> /// RC2 解密(用变长密钥对大量数据进行加密) /// </summary> /// <param name="DecryptString">待解密密文</param> /// <param name="DecryptKey">解密密钥</param> /// <returns>returns</returns> public static string RC2Decrypt(string DecryptString, string DecryptKey, Encoding EncodingUsing = null) { if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); } if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); } if (DecryptKey.Length < 5 || DecryptKey.Length > 16) { throw (new Exception("密钥必须为5-16位")); } if (EncodingUsing == null) { EncodingUsing = new UTF8Encoding(); } byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; string m_strDecrypt = ""; RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider(); try { byte[] m_btDecryptString = Convert.FromBase64String(DecryptString); MemoryStream m_stream = new MemoryStream(); CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateDecryptor(EncodingUsing.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write); m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length); m_cstream.FlushFinalBlock(); m_strDecrypt = EncodingUsing.GetString(m_stream.ToArray()); m_stream.Close(); m_stream.Dispose(); m_cstream.Close(); m_cstream.Dispose(); } catch (Exception ex) { throw ex; } finally { m_RC2Provider.Clear(); } return(m_strDecrypt); }
/// <summary> /// RC2 加密(用变长密钥对大量数据进行加密) /// </summary> /// <param name="encryptString">待加密密文</param> /// <param name="encryptKey">加密密钥</param> /// <returns>returns</returns> public static string RC2Encrypt(string encryptString, string encryptKey) { if (string.IsNullOrEmpty(encryptString)) { throw (new Exception("密文不得为空")); } if (string.IsNullOrEmpty(encryptKey)) { throw (new Exception("密钥不得为空")); } if (encryptKey.Length < 5 || encryptKey.Length > 16) { throw (new Exception("密钥必须为5-16位")); } string m_strEncrypt = ""; byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider(); try { byte[] m_btencryptString = Encoding.Default.GetBytes(encryptString); using (var m_stream = new MemoryStream()) { using (var m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateEncryptor(Encoding.Default.GetBytes(encryptKey), m_btIV), CryptoStreamMode.Write)) { m_cstream.Write(m_btencryptString, 0, m_btencryptString.Length); m_cstream.FlushFinalBlock(); m_strEncrypt = Convert.ToBase64String(m_stream.ToArray()); } } } catch (Exception ex) { throw ex; } finally { m_RC2Provider.Clear(); } return(m_strEncrypt); }
/// <summary> /// RC2 解密 /// </summary> /// <param name="Values">加密后的字符串</param> /// <returns>解密后的字符串</returns> public string DeRC2Encrypt(string Values) { try { byte[] buffer = Convert.FromBase64String(Values); RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider(); rc2CSP.Mode = CipherMode.CBC; System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer); ICryptoTransform ct = rc2CSP.CreateDecryptor(Encoding.ASCII.GetBytes(this._Key), Encoding.ASCII.GetBytes(this._IV)); rc2CSP.Clear(); CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Read); System.IO.StreamReader sw = new System.IO.StreamReader(cs); return(sw.ReadToEnd()); } catch (Exception e) { throw new Exception("解密数据出错,详细原因:" + e.Message); } }
/// <summary> Function to decrypt an one content bytes /// </summary> /// <param name="content">To be encrypted content</param> /// <returns>Array of bytes</returns> public byte[] Decrypt(byte[] content) { if (IsHashAlgorithm) { throw new CryptographicException(Resources.Cypher_DecryptHash); } if (_key == null) { throw new CryptographicException(Resources.Cypher_NoKey); } if (content == null || content.Equals(String.Empty)) { throw new CryptographicException(Resources.Cypher_NoContent); } string encText = System.Text.Encoding.UTF8.GetString(content, 0, content.Length); if (_encodingType == EncodingType.Base64) { //We need to convert the content to Hex before decryption encText = BytesToHex(System.Convert.FromBase64String(encText)); } byte[] clearBytes = null; int NumBytes = 0; #if !CompactFramework if (_algorithm == Algorithm.RSA) { clearBytes = RSADecrypt(encText); } else #endif { SymmetricAlgorithm provider; switch (_algorithm) { case Algorithm.DES: provider = new DESCryptoServiceProvider(); NumBytes = Convert.ToInt32(AlgorithmKeySize.DES); break; case Algorithm.TripleDES: provider = new TripleDESCryptoServiceProvider(); NumBytes = Convert.ToInt32(AlgorithmKeySize.TripleDES); break; case Algorithm.Rijndael: provider = new RijndaelManaged(); NumBytes = Convert.ToInt32(AlgorithmKeySize.Rijndael); break; case Algorithm.RC2: provider = new RC2CryptoServiceProvider(); NumBytes = Convert.ToInt32(AlgorithmKeySize.RC2); break; default: throw new CryptographicException(Resources.Cypher_InvalidProvider); } try { clearBytes = SymmetricDecrypt(provider, encText, _key, NumBytes); } finally { //Free any resources held by the SymmetricAlgorithm provider provider.Clear(); } } //Now return the plain text content return(clearBytes); }
/// <summary> Function to encrypt an one content bytes /// </summary> /// <param name="content">Function to encrypt an one content bytes</param> /// <returns>Array of bytes</returns> public byte[] Encrypt(byte[] content) { if (!IsHashAlgorithm && _key == null) { throw new CryptographicException(Resources.Cypher_NoKey); } if (content == null || content.Equals(String.Empty)) { throw new CryptographicException(Resources.Cypher_NoContent); } byte[] cipherBytes = null; int NumBytes = 0; #if !CompactFramework if (_algorithm == Algorithm.RSA) { //This is an asymmetric call, which has to be treated differently cipherBytes = RSAEncrypt(content); } else #endif if (IsHashAlgorithm) { string hash = GenerateHash(System.Text.Encoding.UTF8.GetString(content, 0, content.Length)); cipherBytes = System.Text.Encoding.UTF8.GetBytes(hash); } else { SymmetricAlgorithm provider; switch (_algorithm) { case Algorithm.DES: provider = new DESCryptoServiceProvider(); NumBytes = Convert.ToInt32(AlgorithmKeySize.DES); break; case Algorithm.TripleDES: provider = new TripleDESCryptoServiceProvider(); NumBytes = Convert.ToInt32(AlgorithmKeySize.TripleDES); break; case Algorithm.Rijndael: provider = new RijndaelManaged(); NumBytes = Convert.ToInt32(AlgorithmKeySize.Rijndael); break; case Algorithm.RC2: provider = new RC2CryptoServiceProvider(); NumBytes = Convert.ToInt32(AlgorithmKeySize.RC2); break; default: throw new CryptographicException(Resources.Cypher_InvalidProvider); } try { //Encrypt the string cipherBytes = SymmetricEncrypt(provider, content, _key, NumBytes); } finally { //Free any resources held by the SymmetricAlgorithm provider provider.Clear(); } } return(cipherBytes); }
private static byte[] _Decrypt(byte[] Content) { if (!IsHashAlgorithm && _key == null) { throw new CryptographicException(ERR_NO_KEY); } if (_algorithm.Equals(-1)) { throw new CryptographicException(ERR_NO_ALGORITHM); } if (Content == null || Content.Length.Equals(0)) { throw new CryptographicException(ERR_NO_CONTENT); } string encText = Encoding.UTF8.GetString(Content); if (_encodingType == EncodingType.BASE_64) { //We need to convert the content to Hex before decryption encText = BytesToHex(System.Convert.FromBase64String(encText)); } byte[] clearBytes = null; int NumBytes = 0; if (_algorithm == Algorithm.RSA) { try { clearBytes = RSADecrypt(encText); } catch (CryptographicException ex) { throw ex; } } else { SymmetricAlgorithm provider = null; switch (_algorithm) { case Algorithm.DES: provider = new DESCryptoServiceProvider(); NumBytes = KeySize.DES; break; case Algorithm.TripleDES: provider = new TripleDESCryptoServiceProvider(); NumBytes = KeySize.TripleDES; break; case Algorithm.Rijndael: provider = new RijndaelManaged(); NumBytes = KeySize.AES; break; case Algorithm.RC2: provider = new RC2CryptoServiceProvider(); NumBytes = KeySize.RC2; break; default: throw new CryptographicException(ERR_INVALID_PROVIDER); } try { clearBytes = SymmetricDecrypt(provider, encText, _key, NumBytes); } catch (CryptographicException ex) { throw ex; } finally { //Free any resources held by the SymmetricAlgorithm provider provider.Clear(); } } //Now return the plain text content return(clearBytes); }
private static byte[] _Encrypt(byte[] Content) { if (!IsHashAlgorithm && _key == null) { throw new CryptographicException(ERR_NO_KEY); } if (_algorithm.Equals(-1)) { throw new CryptographicException(ERR_NO_ALGORITHM); } if (Content == null || Content.Equals(string.Empty)) { throw new CryptographicException(ERR_NO_CONTENT); } byte[] cipherBytes = null; int NumBytes = 0; if (_algorithm == Algorithm.RSA) { //This is an asymmetric call, which has to be treated differently try { cipherBytes = RSAEncrypt(Content); } catch (CryptographicException ex) { throw ex; } } else { SymmetricAlgorithm provider = null; switch (_algorithm) { case Algorithm.DES: provider = new DESCryptoServiceProvider(); NumBytes = KeySize.DES; break; case Algorithm.TripleDES: provider = new TripleDESCryptoServiceProvider(); NumBytes = KeySize.TripleDES; break; case Algorithm.Rijndael: provider = new RijndaelManaged(); NumBytes = KeySize.AES; break; case Algorithm.RC2: provider = new RC2CryptoServiceProvider(); NumBytes = KeySize.RC2; break; default: throw new CryptographicException(ERR_INVALID_PROVIDER); } try { //Encrypt the string cipherBytes = SymmetricEncrypt(provider, Content, _key, NumBytes); } catch (CryptographicException ex) { throw new CryptographicException(ex.Message, ex.InnerException); } finally { //Free any resources held by the SymmetricAlgorithm provider provider.Clear(); } } return(cipherBytes); }
private void Form1_Shown(object sender, EventArgs e) { // создание формы для ввода парольной фразы для расшифрпования // блок с возможной генерацией исключительных ситуаций try { if (passFrase.ShowDialog() != DialogResult.OK) { throw new Exception("Работа программы невозможна!"); } // создание объекта для криптоалгоритма rc2CSP = new RC2CryptoServiceProvider(); // определение режима блочного шифрования rc2CSP.Mode = CipherMode.CFB; // декодирование парольной фразы pwd = Encoding.Unicode.GetBytes(passFrase.Edit1.Text); // создание буфера для случайной примеси randBytes = new byte[8]; randBytes[1] = 1; randBytes[5] = 1; // выделение памяти для буфера buf = new byte[pwd.Length + randBytes.Length]; // копирование в буфер парольной фразы pwd.CopyTo(buf, 0); // освобождение ресурсов формы для ввода парольной фразы //passFrase.Dispose(); if (!File.Exists(Account.SECFILE)) { // создание нового файла Acc.AccFile = new FileStream(Account.SECFILE, FileMode.Create); // подготовка учетной записи администратора Encoding.Unicode.GetBytes("ADMIN").CopyTo(Acc.UserAcc.UserName, 0); Encoding.Unicode.GetBytes("").CopyTo(Acc.UserAcc.UserPass, 0); Acc.UserAcc.PassLen = 0; Acc.UserAcc.Block = false; Acc.UserAcc.Restrict = true; // запись в файл учетной записи администратора Acc.WriteAccount(); // закрытие файла Acc.AccFile.Close(); // сброс счетчика попыток входа в программу EnterCount = 0; } else { // создание объекта для зашифрованного файла учетных записей Acc.AccFile = new FileStream(Account.SECFILE, FileMode.Open); randBytes = new byte[8]; randBytes[1] = 1; randBytes[5] = 1; // чтение случайной примеси из начала зашифрованного файла Acc.AccFile.Read(randBytes, 0, 8); // создание объекта для вывода ключа из парольной фразы pdb = new PasswordDeriveBytes(pwd, randBytes); // восстановление начального вектора из файла IV = new byte[rc2CSP.BlockSize / 8]; Acc.AccFile.Read(IV, 0, rc2CSP.BlockSize / 8); rc2CSP.IV = IV; // вывод ключа расшифрования rc2CSP.Key = pdb.CryptDeriveKey("RC2", "SHA", rc2CSP.KeySize, rc2CSP.IV); // создание объекта расшифрования ICryptoTransform decryptor = rc2CSP.CreateDecryptor(rc2CSP.Key, rc2CSP.IV); // создание объекта для потока расшифрования CrStream = new CryptoStream(Acc.AccFile, decryptor, CryptoStreamMode.Read); // выделение памяти для буфера ввода-вывода int numerik; numerik = (int)(Acc.AccFile.Length - (8 + (rc2CSP.BlockSize / 8))); bytes = new byte[numerik]; // задание количества непрочитанных байт numBytesToRead = (int)((Acc.AccFile.Length) - (8 + (rc2CSP.BlockSize / 8))); // ввод данных из исходного файла int n = CrStream.Read(bytes, 0, numBytesToRead); // сохранение фактического количества расшифрованных байт numBytesToRead = n; // запись в расшифрованный поток в памяти Acc.AccMem.Write(bytes, 0, numBytesToRead); // очистка памяти с объектом криптоалгоритма rc2CSP.Clear(); // закрытие криптографического потока CrStream.Close(); // закрытие зашифрованного файла Acc.AccFile.Close(); // чтение первой учетной записи (администратора) Acc.AccMem.Seek(0, SeekOrigin.Begin); Acc.ReadAccount(); // если имя первой учетной записи не совпадает с ADMIN if (Encoding.Unicode.GetString(Acc.UserAcc.UserName, 0, 10) != "ADMIN") { throw new Exception("Неверный ключ расшифрования!"); } } } // обработка исключения catch (Exception ex) { // вывод сообщения об ошибке MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); // завершение работы программы Application.Exit(); } /* если файл с учетными записями пользователей не существует * (первый запуск программы) */ }
/// <summary> /// 복호화 /// </summary> /// <param name="cipherText">암호문</param> /// <param name="DecryptCheck">암호화 해시 함수</param> /// <param name="DecryptType">암호화 알고리즘</param> public static string DecryptText(string cipherText, string DecryptCheck, string DecryptType, string CryptoKey) { byte[] keyArray; byte[] toEncryptArray = Convert.FromBase64String(cipherText); string key = CryptoKey; switch (DecryptCheck.Trim().ToUpper().ToString()) { case "MD5": MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); hashmd5.Clear(); break; case "SHA1": SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); keyArray = sha1.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); sha1.Clear(); break; case "SHA256": SHA256Managed sha256 = new SHA256Managed(); keyArray = sha256.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); sha256.Clear(); break; case "SHA384": SHA384Managed sha384 = new SHA384Managed(); keyArray = sha384.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); sha384.Clear(); break; case "SHA512": SHA512Managed sha512 = new SHA512Managed(); keyArray = sha512.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); sha512.Clear(); break; default: keyArray = UTF8Encoding.UTF8.GetBytes(key); break; } byte[] resultArray = null; if (keyArray.Length > 16) { byte[] temp = new byte[16]; for (int i = 0; i < 16; i++) { temp[i] = keyArray[i]; } keyArray = temp; } if (keyArray.Length < 16) { byte[] temp = new byte[16]; for (int j = keyArray.Length; j < 16; j++) { temp[j] = keyArray[0]; } keyArray = temp; } switch (DecryptType.Trim().ToUpper().ToString()) { case "RC2": RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); rc2.Key = keyArray; rc2.Mode = CipherMode.ECB; rc2.Padding = PaddingMode.PKCS7; ICryptoTransform rc2Transform = rc2.CreateDecryptor(); resultArray = rc2Transform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); rc2.Clear(); break; case "TRIPLE": TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform tdesTransform = tdes.CreateDecryptor(); resultArray = tdesTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); tdes.Clear(); break; case "DES": DESCryptoServiceProvider des = new DESCryptoServiceProvider(); des.Key = UTF8Encoding.UTF8.GetBytes(key.Substring(0, 8).ToString().Trim()); des.Mode = CipherMode.ECB; des.Padding = PaddingMode.PKCS7; ICryptoTransform desTransform = des.CreateDecryptor(); resultArray = desTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); des.Clear(); break; case "AES": RijndaelManaged Rijndae = new RijndaelManaged(); Rijndae.Key = keyArray; Rijndae.Mode = CipherMode.ECB; Rijndae.Padding = PaddingMode.PKCS7; ICryptoTransform RijndaeTransform = Rijndae.CreateDecryptor(); resultArray = RijndaeTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); Rijndae.Clear(); break; } return(UTF8Encoding.UTF8.GetString(resultArray)); }