使用密码加密字符串 - AES 256 & SHA256






4.95/5 (8投票s)
一个简单的类,允许使用密码(AES/SHA2)加密/解密字符串。
引言
来自德国的问候! 在这个技巧中,我将向您展示一个允许使用密码加密和解密 string
的类。
背景
如果您不知道什么是 AES 或 SHA2,请阅读维基百科的文章...
首先,我使用 SHA2(256 位)从密码创建一个哈希值,该哈希值是 AES 加密中的密钥和 IV。 IV 只能是 128 位,所以我将其截断到合适的长度。
只有拥有密码才能解密它。
Using the Code
SecurityController.cs 类代码
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Encryption
{
class SecurityController
{
public string Encrypt( string key, string data )
{
string encData = null;
byte[][] keys = GetHashKeys(key);
try
{
encData = EncryptStringToBytes_Aes( data, keys[0], keys[1] );
}
catch ( CryptographicException ) { }
catch ( ArgumentNullException ) { }
return encData;
}
public string Decrypt( string key, string data )
{
string decData = null;
byte[][] keys = GetHashKeys(key);
try
{
decData = DecryptStringFromBytes_Aes( data, keys[0], keys[1] );
}
catch ( CryptographicException ) { }
catch ( ArgumentNullException ) { }
return decData;
}
private byte[][] GetHashKeys( string key )
{
byte[][] result = new byte[2][];
Encoding enc = Encoding.UTF8;
SHA256 sha2 = new SHA256CryptoServiceProvider();
byte[] rawKey = enc.GetBytes(key);
byte[] rawIV = enc.GetBytes(key);
byte[] hashKey = sha2.ComputeHash(rawKey);
byte[] hashIV = sha2.ComputeHash(rawIV);
Array.Resize( ref hashIV, 16 );
result[0] = hashKey;
result[1] = hashIV;
return result;
}
//source: https://msdn.microsoft.com/de-de/library/system.security.cryptography.aes(v=vs.110).aspx
private static string EncryptStringToBytes_Aes( string plainText, byte[] Key, byte[] IV )
{
if ( plainText == null || plainText.Length <= 0 )
throw new ArgumentNullException( "plainText" );
if ( Key == null || Key.Length <= 0 )
throw new ArgumentNullException( "Key" );
if ( IV == null || IV.Length <= 0 )
throw new ArgumentNullException( "IV" );
byte[] encrypted;
using ( AesManaged aesAlg = new AesManaged() )
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using ( MemoryStream msEncrypt = new MemoryStream() )
{
using ( CryptoStream csEncrypt =
new CryptoStream( msEncrypt, encryptor, CryptoStreamMode.Write ) )
{
using ( StreamWriter swEncrypt = new StreamWriter( csEncrypt ) )
{
swEncrypt.Write( plainText );
}
encrypted = msEncrypt.ToArray();
}
}
}
return Convert.ToBase64String( encrypted );
}
//source: https://msdn.microsoft.com/de-de/library/system.security.cryptography.aes(v=vs.110).aspx
private static string DecryptStringFromBytes_Aes( string cipherTextString, byte[] Key, byte[] IV )
{
byte[] cipherText = Convert.FromBase64String(cipherTextString);
if ( cipherText == null || cipherText.Length <= 0 )
throw new ArgumentNullException( "cipherText" );
if ( Key == null || Key.Length <= 0 )
throw new ArgumentNullException( "Key" );
if ( IV == null || IV.Length <= 0 )
throw new ArgumentNullException( "IV" );
string plaintext = null;
using ( Aes aesAlg = Aes.Create() )
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using ( MemoryStream msDecrypt = new MemoryStream( cipherText ) )
{
using ( CryptoStream csDecrypt =
new CryptoStream( msDecrypt, decryptor, CryptoStreamMode.Read ) )
{
using ( StreamReader srDecrypt = new StreamReader( csDecrypt ) )
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
使用示例
MainForm.cs 类代码
using System.Windows.Forms;
namespace Encryption
{
public partial class MainForm : Form
{
private SecurityController _security;
public MainForm()
{
InitializeComponent();
_security = new SecurityController();
}
private void button_encrypt_Click( object sender, System.EventArgs e )
{
string password = textBox_password.Text;
string notEncryptedText = textBox_text.Text;
string encryptedText = _security.Encrypt( password, notEncryptedText );
textBox_text.Text = encryptedText;
}
private void button_decrypt_Click( object sender, System.EventArgs e )
{
string password = textBox_password.Text;
string encryptedText = textBox_text.Text;
string notEncryptedText = _security.Decrypt( password, encryptedText );
textBox_text.Text = notEncryptedText;
}
}
}
加密前
加密后
解密后
结论
我知道它非常简单,代码不多,但是如果您对加密不太了解并且需要它,这个类将对您有很大帮助!