-
Notifications
You must be signed in to change notification settings - Fork 37
/
CryptographyHelpers.cs
210 lines (192 loc) · 9.49 KB
/
CryptographyHelpers.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
//____________________________________________________________________________________________________________________________________
//
// Copyright (C) 2023, Mariusz Postol LODZ POLAND.
//
// To be in touch join the community by pressing the `Watch` button and get started commenting using the discussion panel at
//
// https://github.com/mpostol/TP/discussions/182
//
// by introducing yourself and telling us what you do with this community.
//_____________________________________________________________________________________________________________________________________
using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Xml;
namespace TP.DataStreams.Cryptography
{
public static class CryptographyHelpers
{
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 (BitConverter.ToString(hashValue), 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))
{
const int _bufferLength = 100;
byte[] _buffer = new byte[_bufferLength]; //This is intermediate storage for the encryption.
long _bytesWritten = 0; //This is the total number of bytes written.
TripleDESCryptoServiceProvider _tripleProvider = new TripleDESCryptoServiceProvider();
FileStream _outFileStream = new FileStream(outFileName, FileMode.Create, FileAccess.Write);
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 (true)
{
int _length = _inFileStream.Read(_buffer, 0, _bufferLength);
if (_length == 0)
{
_outCryptoStream.FlushFinalBlock();
break;
}
_outCryptoStream.Write(_buffer, 0, _length);
_bytesWritten = _bytesWritten + _length;
progress.Report(_bytesWritten);
}
}
}
}
public static void DecryptData(string inCryptoFileName, string outFileName, byte[] dESKey, byte[] dESIV, IProgress<long> progress)
{
//Create the file streams to handle the input and output files.
using (FileStream _outFileStream = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write))
{
_outFileStream.SetLength(0);
const int _bufferLength = 100;
byte[] _buffer = new byte[_bufferLength]; //This is intermediate storage for the decrypted content.
long _bytesWritten = 0;
TripleDESCryptoServiceProvider _tripleProvider = new TripleDESCryptoServiceProvider();
FileStream _inFileStream = new FileStream(inCryptoFileName, FileMode.Open, FileAccess.Read);
using (CryptoStream _inCryptoStream = new CryptoStream(_inFileStream, _tripleProvider.CreateDecryptor(dESKey, dESIV), CryptoStreamMode.Read))
{
while (true)
{
int _length = _inCryptoStream.Read(_buffer, 0, _bufferLength);
if (_length == 0)
break;
_outFileStream.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>
/// <param name="document">Document to be signed</param>
/// <param name="rsa">The keys ro be used by the <see cref="RSACryptoServiceProvider"/> RSA algorithm implementation.</param>
/// <remarks>
/// This document cannot be verified unless the verifying code has the public key with which it was signed.
/// </remarks>
public static void SignSaveXml(this XmlDocument document, string rSAKeys, string fileName)
{
#region Check arguments
if (document == null)
throw new ArgumentException($"The {nameof(document)} parameter cannot be null");
if (string.IsNullOrEmpty(rSAKeys))
throw new ArgumentException($"The {nameof(rSAKeys)} parameter cannot be null");
if (string.IsNullOrEmpty(fileName))
throw new ArgumentException($"The {nameof(fileName)} parameter cannot be null");
#endregion Check arguments
using (RSACryptoServiceProvider _rSAProvider = new RSACryptoServiceProvider())
{
_rSAProvider.FromXmlString(rSAKeys);
KeyInfo _keyInfo = new KeyInfo();// Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
_keyInfo.AddClause(new RSAKeyValue(_rSAProvider));
SignedXml _signedXml = new SignedXml(document)
{
SigningKey = _rSAProvider, // Add the key to the SignedXml document.
KeyInfo = _keyInfo
};
Reference _reference = new Reference // Create a reference to be signed.
{
Uri = "" //An entire XML document is to be signed using an enveloped signature.
};
XmlDsigEnvelopedSignatureTransform _envelope = new XmlDsigEnvelopedSignatureTransform(); // Add an enveloped transformation to the reference.
_reference.AddTransform(_envelope);
_signedXml.AddReference(_reference); // Add the reference to the SignedXml object.
_signedXml.ComputeSignature(); // Compute the signature.
XmlElement _xmlDigitalSignature = _signedXml.GetXml(); // Get the XML representation of the signature and save it to an XmlElement object.
document.DocumentElement.AppendChild(document.ImportNode(_xmlDigitalSignature, true));// Append the element to the XML document.
}
document.Save(fileName);
}
/// <summary>
/// Load and verify the signature of an XML file against an asymmetric RSA algorithm and return the document.
/// </summary>
/// <param name="rsaKeys">The RSA keys as the xml document.</param>
/// <param name="fileName">Name of the file.</param>
/// <returns>An instance of the <see cref="XmlDocument"/> capturing the xml file.</returns>
/// <exception cref="ArgumentException">
/// rsaKeys
/// or
/// fileName
/// </exception>
/// <exception cref="System.Security.Cryptography.CryptographicException"></exception>
/// <remarks>There must be only one signature.</remarks>
public static XmlDocument LoadVerifyXml(string rsaKeys, string fileName)
{
#region Check arguments
if (string.IsNullOrEmpty(rsaKeys))
throw new ArgumentException($"The {nameof(rsaKeys)} parameter cannot be null");
if (string.IsNullOrEmpty(fileName))
throw new ArgumentException($"The {nameof(fileName)} parameter cannot be null");
#endregion Check arguments
(XmlDocument _document, SignedXml _signedXml) = LoadSignedXmlFile(fileName);
using (RSACryptoServiceProvider _provider = new RSACryptoServiceProvider())
{
_provider.FromXmlString(rsaKeys);
if (!_signedXml.CheckSignature(_provider))// Check the signature using custom RSA keys.
throw new CryptographicException($"Wrong signature of the document.");
}
return _document;
}
public static XmlDocument LoadVerifyXml(string fileName)
{
#region Check arguments
if (string.IsNullOrEmpty(fileName))
throw new ArgumentException($"The {nameof(fileName)} parameter cannot be null");
#endregion Check arguments
(XmlDocument _document, SignedXml _signedXml) = LoadSignedXmlFile(fileName);
if (!_signedXml.CheckSignature())// Check the signature and return the result.
throw new System.Security.Cryptography.CryptographicException($"Wrong signature of the document.");
return _document;
}
private static (XmlDocument document, SignedXml signedXml) LoadSignedXmlFile(string fileName)
{
XmlDocument _document = new XmlDocument();
_document.Load(fileName);
SignedXml _signedXml = new SignedXml(_document);
XmlNodeList _nodeList = _document.GetElementsByTagName("Signature");// Find the "Signature" node and create a new XmlNodeList object.
if (_nodeList.Count != 1) // There must be only one signature. Return false if 0 or more than one signatures was found.
throw new CryptographicException($"Expected exactly one signature but the file contaons {_nodeList.Count}.");
_signedXml.LoadXml((XmlElement)_nodeList[0]);// Load the first <signature> node.
_document.DocumentElement.RemoveChild(_nodeList[0]);
return (_document, _signedXml);
}
}
}