Monday, January 28, 2008

Encrypting and Decrypting Data

Encrypting and decrypting data:
// Test data
string data = "testing data for encryption-12356";
byte[] utfdata = Encoding.UTF8.GetBytes(data);
byte[] saltBytes = Encoding.UTF8.GetBytes("this my salt");
 
// Our symmetric encryption algorithm
RijndaelManaged aes = new RijndaelManaged();
 
// We're using the PBKDF2 standard for password-based key generation
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes("password", saltBytes);
 
// Setting our parameters
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
 
aes.Key = rfc.GetBytes(aes.KeySize / 8);
aes.IV = rfc.GetBytes(aes.BlockSize / 8);
 
// Encryption
ICryptoTransform encryptTransf = aes.CreateEncryptor();
 
// Output stream, can be also a FileStream
MemoryStream encryptStream = new MemoryStream();
CryptoStream encryptor = new CryptoStream(encryptStream, encryptTransf, CryptoStreamMode.Write);
 
encryptor.Write(utfdata, 0, utfdata.Length);
encryptor.FlushFinalBlock();
encryptor.Close();
 
// Showing our encrypted content
byte[] encryptBytes = encryptStream.ToArray();
MessageBox.Show(UTF8Encoding.UTF8.GetString(encryptBytes));
 
// Now, decryption
ICryptoTransform decryptTrans = aes.CreateDecryptor();
 
// Output stream, can be also a FileStream
MemoryStream decryptStream = new MemoryStream();
CryptoStream decryptor = new CryptoStream(decryptStream, decryptTrans, CryptoStreamMode.Write);
 
decryptor.Write(encryptBytes, 0, encryptBytes.Length);
decryptor.Flush();
decryptor.Close();
 
// Showing our decrypted content
byte[] decryptBytes = decryptStream.ToArray();
MessageBox.Show(UTF8Encoding.UTF8.GetString(decryptBytes));
Encrypting and decrypting files:
// Test data
byte[] saltBytes = Encoding.UTF8.GetBytes("this my salt");
 
// Our symmetric encryption algorithm
RijndaelManaged aes = new RijndaelManaged();
 
// We're using the PBKDF2 standard for password-based key generation
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes("password", saltBytes);
 
// Setting our parameters
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
 
aes.Key = rfc.GetBytes(aes.KeySize / 8);
aes.IV = rfc.GetBytes(aes.BlockSize / 8);
 
//----------------------------------------
// Encryption
ICryptoTransform encryptTransf = aes.CreateEncryptor();
 
// Input file
FileStream infile = File.OpenRead("c:\\filename.txt");
BinaryReader br = new BinaryReader(infile);
 
// Output file (encrypted)
FileStream outfile = File.Create("c:\\filenameEnc.bin");
CryptoStream encryptor = new CryptoStream(outfile, encryptTransf, CryptoStreamMode.Write);
 
// Now, encrypting
byte[] b = br.ReadBytes(1000);
while (b.Length > 0)
{    
    encryptor.Write(b, 0, b.Length);
    b = br.ReadBytes(1000);
}
 
// Final
encryptor.FlushFinalBlock();
encryptor.Close();
br.Close();
//----------------------------------------
 
//----------------------------------------
// Now, decryption
ICryptoTransform decryptTrans = aes.CreateDecryptor();
 
// Input encrypted file
infile = File.OpenRead("c:\\filenameEnc.bin");
 
// Output, decrypted file
outfile = File.Create("c:\\filenameDec.txt");
BinaryWriter bw = new BinaryWriter(outfile);
 
CryptoStream decryptor = new CryptoStream(infile, decryptTrans, CryptoStreamMode.Read);
 
// Now, decrypting
int bytes = 1000;
b = new byte[bytes];
do
{
    bytes = decryptor.Read(b, 0, b.Length);
    bw.Write(b, 0, bytes);
 
} while (bytes > 0);
 
// Final
decryptor.Close();
bw.Close();
//----------------------------------------
Encrypting using Asymmetric algorithms:
// Csp: Crytographic Service Provider
// Create a CspParameters object to store our keys permanently in this machine
CspParameters persistantCsp = new CspParameters();
persistantCsp.KeyContainerName = "myAsymmetricKey";
 
// Create an instance of the RSA algorithm object
RSACryptoServiceProvider myRSA = new RSACryptoServiceProvider(persistantCsp);
 
// Specify that the private key should be stored in the CSP
myRSA.PersistKeyInCsp = true;
 
// Create a new RSAParameters object with the private key
RSAParameters privateKey = myRSA.ExportParameters(true);
 
// Showing keys
MessageBox.Show(myRSA.ToXmlString(true));
 
// Now, encrypting some test data
string data = "testing data for encryption-12356";
byte[] encBytes = Encoding.Unicode.GetBytes(data);
 
// Encrypt
byte[] encData = myRSA.Encrypt(encBytes, false);
 
// Decrypt
byte[] decBytes = myRSA.Decrypt(encData, false);
 
// Showing results
MessageBox.Show(Encoding.Unicode.GetString(decBytes));
Calculating hashes:
// SHA1 hash provider
SHA1 myHash = new SHA1CryptoServiceProvider();
 
// Input file
FileStream file = File.OpenRead("c:\\filename.txt");
 
// computing the hash
myHash.ComputeHash(file);
 
// Showing results
MessageBox.Show(Convert.ToBase64String(myHash.Hash));
Using keyed hashes:
// Test data
byte[] saltValueBytes = Encoding.ASCII.GetBytes("This is my sa1t");
 
// We're using the PBKDF2 standard for password-based key generation
Rfc2898DeriveBytes passwordKey = new Rfc2898DeriveBytes("password", saltValueBytes);
byte[] secretKey = passwordKey.GetBytes(16);
 
// SHA1 keyed hash
HMACSHA1 myHash = new HMACSHA1(secretKey);
 
// Input data
FileStream file = File.OpenRead("c:\\filename.txt");
BinaryReader reader = new BinaryReader(file);
 
// Setting data
myHash.ComputeHash(reader.ReadBytes((int)file.Length));
 
// Showing results
MessageBox.Show(Convert.ToBase64String(myHash.Hash));
Signing data:
//---------------------------------------------
// Signing provider
DSACryptoServiceProvider signer = new DSACryptoServiceProvider();
 
// Input data
FileStream file = File.OpenRead("c:\\filename.txt");
BinaryReader reader = new BinaryReader(file);
byte[] data = reader.ReadBytes((int)file.Length);
 
// Getting signature
byte[] signature = signer.SignData(data);
 
// Exporting our public key to share with someone
string publicKey = signer.ToXmlString(false);
 
// Showing results
MessageBox.Show("Signature: " + Convert.ToBase64String(signature));
 
reader.Close();
//---------------------------------------------
 
//---------------------------------------------
// Verifying signature
DSACryptoServiceProvider verifier = new DSACryptoServiceProvider();
 
// Importing our public key
verifier.FromXmlString(publicKey);
 
// Getting original data
FileStream file2 = File.OpenRead("c:\\filename.txt");
BinaryReader reader2 = new BinaryReader(file2);
byte[] data2 = reader2.ReadBytes((int)file2.Length);
 
// Showing results
if (verifier.VerifyData(data2, signature))
    MessageBox.Show("Signature OK");
else
    MessageBox.Show("Bad Signature");
 
reader2.Close();
//---------------------------------------------
Other providers:

Symmetric algorithms:

RijndaelManaged (AES)
RC2
DES
TripleDES


Asymmetric algorithms:

RSACryptoServiceProvider
DSACryptoServiceProvider


Hash algorithms:

MD5
RIPEMD160
SHA1
SHA256
SHA384
SHA512


Keyed hash algorithms:

HMACSHA1
MACTripleDESC

1 comments:

Diogo said...

Hi Oscar,

I read your post and i want to know if is possible create a hash with x++ code.

Using the SHA1 for instance.


View My Stats