Skip to content

Commit

Permalink
3. Data Streams : Cryptography Basics #118
Browse files Browse the repository at this point in the history
- added EncryptDataTest
- UT 👍
  • Loading branch information
mpostol committed Aug 15, 2018
1 parent 925b5b3 commit 35a7e6e
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//____________________________________________________________________________

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
Expand All @@ -21,8 +22,8 @@ public void CalculateSHA256Test()
{
const string _pasword = "Fe4ZFH2VgpOOwBdM9dkI";
(string HexString, string Base64) = _pasword.CalculateSHA256();
Assert.AreEqual<string>("D9CBFBB0AD87D8CE0CC0D2FF1BCFF67C6933D2B4B4CC4C6FA60CE29F73322CD8", HexString);
Assert.AreEqual<int>(256/4, HexString.Length);
Assert.AreEqual<string>("D9-CB-FB-B0-AD-87-D8-CE-0C-C0-D2-FF-1B-CF-F6-7C-69-33-D2-B4-B4-CC-4C-6F-A6-0C-E2-9F-73-32-2C-D8", HexString);
Assert.AreEqual<int>(256 / 4 + 31, HexString.Length);
Assert.AreEqual<string>("2cv7sK2H2M4MwNL/G8/2fGkz0rS0zExvpgzin3MyLNg=", Base64);
Assert.AreEqual<int>(44, Base64.Length);
}
Expand All @@ -31,15 +32,33 @@ public void CalculateSHA256LongTest()
{
const string _pasword = "UAXflAoVz8wcR1VkxUgTO8HAMBYK83yQvcHI9nqsQUiI4mx6jLlCAFGPrHj99XHi3uOoUfqe7wF7JkX2wBwwPADpn9f8s2Q0CfaA";
(string HexString, string Base64) = _pasword.CalculateSHA256();
Assert.AreEqual<string>("B77B064339A0D98C722F54A7B055539BD63BAFC07EBD2B9342EA247EAA86FB18", HexString);
Assert.AreEqual<int>(256 / 4, HexString.Length);
Assert.AreEqual<string>("B7-7B-06-43-39-A0-D9-8C-72-2F-54-A7-B0-55-53-9B-D6-3B-AF-C0-7E-BD-2B-93-42-EA-24-7E-AA-86-FB-18", HexString);
Assert.AreEqual<int>(256 / 4 + 31, HexString.Length);
Assert.AreEqual<string>("t3sGQzmg2YxyL1SnsFVTm9Y7r8B+vSuTQuokfqqG+xg=", Base64);
Assert.AreEqual<int>(44, Base64.Length);
}
[TestMethod]
public void XmlSignatureTestMethod1()
[DeploymentItem("Instrumentation")]
public void EncryptDataTest()
{
const string _inFileName = @"catalog.example.xml";
FileInfo _inFileInfo = new FileInfo(_inFileName);
Assert.IsTrue(_inFileInfo.Exists);
const string _outFileName = "encrypteDXmlFile.xml";
if (File.Exists(_outFileName))
File.Delete(_outFileName);
ProgressMonitor _logger = new ProgressMonitor();
TripleDESCryptoServiceProvider _tripleDesProvider = new TripleDESCryptoServiceProvider();
CryptographyHelpers.EncryptData(_inFileName, _outFileName, _tripleDesProvider.Key, _tripleDesProvider.IV, _logger);
Assert.AreEqual<int>(7, _logger.ReportedCycles);
FileInfo _outFileInfo = new FileInfo(_outFileName);
Assert.AreEqual<long>(_outFileInfo.Length, _inFileInfo.Length+1);
Assert.AreEqual<long>(_outFileInfo.Length, _logger.ReportedValue+1);
}
[TestMethod]
public void CreateRSACryptoServiceKeysTest()
{
(RSAParameters parameters, string publicKey, string privatePublicKeys) = CreateRSACryptoServiceKeys();
(RSAParameters parameters, string publicKey, string privatePublicKeys) = CryptographyHelpers.CreateRSACryptoServiceKeys();
Assert.IsNotNull(parameters);
Assert.AreNotEqual<string>(publicKey, privatePublicKeys);
Debug.WriteLine(publicKey);
Expand All @@ -59,9 +78,9 @@ public void XmlSignatureTest()
XmlDocument _documentToSign = new XmlDocument();
_documentToSign.Load(_xmlFile);
const string _signedFileName = "SignedXmlFile.xml";
string _rsaKeys = null;
if (File.Exists(_signedFileName))
File.Delete(_signedFileName);
string _rsaKeys = null;
using (StreamReader _reader = new StreamReader(_publiPrivateKeys, System.Text.Encoding.UTF8))
_rsaKeys = _reader.ReadToEnd();
CryptographyHelpers.SignSaveXml(_documentToSign, _rsaKeys, _signedFileName);
Expand All @@ -74,16 +93,17 @@ public void XmlSignatureTest()
Assert.IsNotNull(_signedXmlDocument2);
Assert.AreEqual<string>(_signedXmlDocument1.ToString(), _signedXmlDocument2.ToString());
}
private (RSAParameters parameters, string publicKey, string privatePublicKeys) CreateRSACryptoServiceKeys()
private class ProgressMonitor : IProgress<long>
{
using (RSACryptoServiceProvider _rsa = new RSACryptoServiceProvider(2048))
internal long ReportedValue = 0;
internal int ReportedCycles = 0;
public void Report(long value)
{
RSAParameters _parameters = _rsa.ExportParameters(true);
string _public = _rsa.ToXmlString(false);
string _both = _rsa.ToXmlString(true);
return (_parameters, _public, _both);
ReportedCycles++;
ReportedValue = value;
}
}

}
}

Original file line number Diff line number Diff line change
Expand Up @@ -17,43 +17,56 @@ namespace TP.DataStreams.Cryptography

public static class CryptographyHelpers
{
public static (string Hex, string Base64) CalculateSHA256 (this string inputStream)
public static (string Hex, string Base64) CalculateSHA256(this string inputStream)
{
byte[] _inputStreamBytes = Encoding.UTF8.GetBytes(inputStream);
using (SHA256 mySHA256 = SHA256Managed.Create())
{
byte[] hashValue = mySHA256.ComputeHash(_inputStreamBytes);
return (hashValue.ToHexString(), Convert.ToBase64String(hashValue, Base64FormattingOptions.InsertLineBreaks));
return (BitConverter.ToString(hashValue, 0), Convert.ToBase64String(hashValue, Base64FormattingOptions.InsertLineBreaks));
}
}
public static void EncryptData(string inFileName, string outFileName, byte[] dESKey, byte[] dESIV, IProgress<long> progress)
{
//Create the file streams to handle the input and output files.
using (FileStream _inFileStream = new FileStream(inFileName, FileMode.Open, FileAccess.Read))
{
using (FileStream _outFileStream = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write))
FileStream _outFileStream = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);
_outFileStream.SetLength(0);
//Create variables to help with read and write.
byte[] _buffer = new byte[100]; //This is intermediate storage for the encryption.
long _bytesWritten = 0; //This is the total number of bytes written.
long _inFileStreamLength = _inFileStream.Length; //This is the total length of the input file.
int _length; //This is the number of bytes to be written at a time.
TripleDESCryptoServiceProvider _tripleProvider = new TripleDESCryptoServiceProvider();
using (CryptoStream _outCryptoStream = new CryptoStream(_outFileStream, _tripleProvider.CreateEncryptor(dESKey, dESIV), CryptoStreamMode.Write))
{
_outFileStream.SetLength(0);
//Create variables to help with read and write.
byte[] _buffer = new byte[100]; //This is intermediate storage for the encryption.
long _bytesWritten = 0; //This is the total number of bytes written.
long _inFileStreamLength = _inFileStream.Length; //This is the total length of the input file.
int _length; //This is the number of bytes to be written at a time.
TripleDESCryptoServiceProvider _tripleProvider = new TripleDESCryptoServiceProvider();
using (CryptoStream _outCryptoStream = new CryptoStream(_outFileStream, _tripleProvider.CreateEncryptor(dESKey, dESIV), CryptoStreamMode.Write))
//Read from the input file, then encrypt and write to the output file.
while (_bytesWritten < _inFileStreamLength)
{
//Read from the input file, then encrypt and write to the output file.
while (_bytesWritten < _inFileStreamLength)
{
_length = _inFileStream.Read(_buffer, 0, 100);
_outCryptoStream.Write(_buffer, 0, _length);
_bytesWritten = _bytesWritten + _length;
progress.Report(_bytesWritten);
}
_length = _inFileStream.Read(_buffer, 0, 100);
_outCryptoStream.Write(_buffer, 0, _length);
_bytesWritten = _bytesWritten + _length;
progress.Report(_bytesWritten);
}
}
}
}
/// <summary>
/// Creates the RSA crypto service keys.
/// </summary>
/// <returns>Returns <see cref="ValueTuple"/> containing key RSA values </returns>
public static (RSAParameters parameters, string publicKey, string privatePublicKeys) CreateRSACryptoServiceKeys()
{
using (RSACryptoServiceProvider _rsa = new RSACryptoServiceProvider(2048))
{
RSAParameters _parameters = _rsa.ExportParameters(true);
string _public = _rsa.ToXmlString(false);
string _both = _rsa.ToXmlString(true);
return (_parameters, _public, _both);
}
}

/// <summary>
/// Sign and save an XML document.
/// </summary>
Expand Down

0 comments on commit 35a7e6e

Please sign in to comment.