Skip to content

Instantly share code, notes, and snippets.

@MAOliver
Created May 11, 2015 02:52
Show Gist options
  • Save MAOliver/5ff7596249b56937151f to your computer and use it in GitHub Desktop.
Save MAOliver/5ff7596249b56937151f to your computer and use it in GitHub Desktop.
Simple encryption rijndael encryption wrapper
/// <summary>
/// Adapted from:
/// http://www.codeproject.com/Articles/5719/Simple-encrypting-and-decrypting-data-in-C
/// </summary>
public class EncryptionService : IEncryptionService
{
private readonly string _password;
private readonly byte[] _salt;
public EncryptionService( string password, string salt )
{
_password = password;
_salt = new ASCIIEncoding().GetBytes(salt);
}
public SymmetricAlgorithm NewRijndael()
{
var alg = Rijndael.Create( );
var key = new Rfc2898DeriveBytes( _password, _salt, 999 );
alg.IV = key.GetBytes( alg.BlockSize / 8 );
alg.Key = key.GetBytes( alg.KeySize / 8 );
return alg;
}
public string Encrypt( string clearText )
{
return Convert.ToBase64String(
Encrypt(
Encoding.Unicode.GetBytes(
clearText
)
)
);
}
public byte[ ] Encrypt( byte[ ] clearData )
{
using(var ms = new MemoryStream( ))
using (var cs = new CryptoStream(ms, NewRijndael().CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write( clearData, 0, clearData.Length );
cs.Close();
return ms.ToArray( );
}
}
public string Decrypt( string cipherText )
{
return Encoding.Unicode.GetString(
Decrypt(
Convert.FromBase64String(
cipherText
)
)
);
}
public byte[ ] Decrypt( byte[ ] cipherData )
{
using ( var ms = new MemoryStream( ) )
using ( var cs = new CryptoStream(ms, NewRijndael().CreateDecryptor(), CryptoStreamMode.Write) )
{
cs.Write( cipherData, 0, cipherData.Length );
cs.Close( );
return ms.ToArray( );
}
}
}
public interface IEncryptionService
{
SymmetricAlgorithm NewRijndael();
string Encrypt( string clearText );
byte[ ] Encrypt( byte[ ] clearData );
string Decrypt( string cipherText );
byte[ ] Decrypt( byte[ ] cipherData );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment