Telerik RadPersistenceManager Unable to read storage content - c#

I've used RadPersistenceManager with asp.net and follow the following guide :
http://demos.telerik.com/aspnet-ajax/persistence-framework/examples/custom-storage-provider/defaultcs.aspx.
But when I implement this in my project the following exception appears:
Title: xxxx.aspx, xxxxx Method Name:
Unable to read storage content. Could not find file
'C:\inetpub\wwwroot\XXXX\App_Data\TelerikAspNetRadControlsPersistedState'.
Exception: at
Telerik.Web.UI.PersistenceFramework.AppDataStorageProvider.LoadStateFromStorage(String
key) at Telerik.Web.UI.RadPersistenceManager.LoadState() at GraphicalUserInterface.JobBasket.LoadGridJobBasket()

That's the default storage provider key. If the control is looking for it, then your custom provider is not in effect at all.
Make sure you have everything from the demo, primarily:
the lines that set the custom storage provider:
protected void Page_Init(object sender, EventArgs e)
{
RadPersistenceManager1.StorageProviderKey = CookieName;
RadPersistenceManager1.StorageProvider = new CookieStorageProvider(CookieName);
}
and the custom storage provider itself:
using System;
using System.Linq;
using System.Web;
using Telerik.Web.UI.PersistenceFramework;
using System.IO;
using System.IO.Compression;
using System.Text;
public class CookieStorageProvider : IStateStorageProvider
{
private static readonly Encoding AsciiEncoding = System.Text.Encoding.ASCII;
private static readonly int MaxCookieSize = 4000;
private static readonly int LengthDataByteCount = sizeof(Int32);
private string StorageKey { get; set; }
#region IStateStorageProvider
public CookieStorageProvider(string key)
{
StorageKey = key;
}
public void SaveStateToStorage(string key, string serializedState)
{
HttpCookie cookie = new HttpCookie(StorageKey);
string settingsData = CompressString(serializedState);
if (settingsData.Length > MaxCookieSize)
{
throw new ArgumentOutOfRangeException("Current settings exceed 4k in compressed form! Operation canceled!");
}
cookie.Value = settingsData;
HttpContext.Current.Response.Cookies.Add(cookie);
}
public string LoadStateFromStorage(string key)
{
return DecompressString(HttpContext.Current.Request.Cookies[StorageKey].Value.ToString());
}
#endregion
private string CompressString(string inputString)
{
byte[] outputBytes = null;
byte[] inputBytes = AsciiEncoding.GetBytes(inputString);
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress))
{
zipStream.Write(inputBytes, 0, inputBytes.Length);
}
outputBytes = ms.ToArray();
}
return Convert.ToBase64String(AddDataCount(outputBytes, inputBytes.Length));
}
private string DecompressString(string inputString)
{
string outputString = String.Empty;
byte[] inputBytes = Convert.FromBase64String(inputString);
Int32 lengthDataArray = BitConverter.ToInt32(inputBytes, inputBytes.Length - LengthDataByteCount);
byte[] outputBytes = new byte[lengthDataArray];
using (MemoryStream ms = new MemoryStream(RemoveDataCount(inputBytes)))
{
using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress))
{
zipStream.Read(outputBytes, 0, outputBytes.Length);
}
outputString = AsciiEncoding.GetString(outputBytes);
}
return outputString;
}
private byte[] AddDataCount(byte[] inputArray, Int32 length)
{
byte[] lengthDataArray = BitConverter.GetBytes(length);
Array.Resize<byte>(ref inputArray, inputArray.Length + LengthDataByteCount);
Array.Copy(lengthDataArray, 0, inputArray, inputArray.Length - LengthDataByteCount, LengthDataByteCount);
return inputArray;
}
private byte[] RemoveDataCount(byte[] inputArray)
{
Array.Resize<byte>(ref inputArray, inputArray.Length - LengthDataByteCount);
return inputArray;
}
}

The different between the demo and my example that I need to load the persistence configurations on page load instead of load button. so it seems some times the CookieStorageProvider not initiated in Page_Init, so I added it in page_load instead.

Related

BouncyCastle: "mac check in GCM failed"

Throws exception: Org.BouncyCastle.Crypto.InvalidCipherTextException: "mac check in GCM failed"
I am taring to decode metamask vault an sure that everithing with it must be OK
I can't find what's wrong
using System.Security.Cryptography;
using Org.BouncyCastle.Crypto.Parameters;
using System.Text;
using Jose;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
namespace net6metachecker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void startbtn_Click(object sender, EventArgs e)
{
Decrypt1();
}
public void Decrypt1()
{
byte[] salt = Convert.FromBase64String("RXoBv+8Yu/nQhmj+nXMp8Rf57VLT8aYu5rvP5LEcq7Y=");
byte[] data = Convert.FromBase64String("cVZeRBJI7yzsN6lM9LS6tNSVYTU7IFy+UMAVsZjHa+/nGvXirE99pILb4+VdYANkEg05kbeoYgLwacqUNfZc+9llePvcLkVmzFtye4pYbVSkHtaGCKfFMb0gQxJb2xJz7Br4MHNzGEY7aZAkrWpx1KhIghA3uZBE5sjZ+vjw/aFg3w51xGBMgzwLdMcr8+Fru5Kyb5p1dVXSsMt7AFIQFg1BsOcbEiDNf/jkigxuJpILVYUY3qrUJmYh500frohZnxoh8fSPSWcyLbl08TKGE4DQuBeJ7cMcmmHnpvJ166BK1roOni4CMRIn84BBUr5DEW36+22i52vfPCvzgNUierIBoh3wUTZI/trHozXSLYg8t86XwLIzwNq4H08Ctss/Daivta/7mgE5KC7gesRoda6OLJ5XldxeibdtOprq1v+teeNVaZRRYTKs+cCUkrwxZVrjqzmnVMBxDegR3/gjchZRszm4hOWDfVR8JRhjpCKQmrLkOno=");
byte[] iv = Convert.FromBase64String("beg6WtZTF82na0IKb5Juhw==");
byte[] password = Encoding.UTF8.GetBytes("11111111");
byte[] key = PBKDF2.DeriveKey(password, salt, 10000, 256, HMAC.Create("HMACSHA256"));
GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesFastEngine());
AeadParameters parameters = new AeadParameters(new KeyParameter(key), 128, iv, null);
gcmBlockCipher.Init(false, parameters);
byte[] plainBytes = new byte[gcmBlockCipher.GetOutputSize(data.Length)];
int retLen = gcmBlockCipher.ProcessBytes(data, 0, data.Length, plainBytes, 0);
byte[] cc = gcmBlockCipher.GetMac();
int xx = gcmBlockCipher.DoFinal(plainBytes, retLen); // Exception is here
string x = Encoding.UTF8.GetString(plainBytes).TrimEnd("\r\n\0".ToCharArray());
MessageBox.Show(x);
}
}
}

RSA.Cryptography "Incorrect Parameter" thrown C#

I'm trying to set up a messing server for me and my friends and I ran into issues with RSA Decryption.
The correct keys are used
If I enable OAEP padding I get a error that simply states "OAEPpadding"
I'm losing my mind on this bug, I'm posting the script below.
Encryption works fine, its just decryption that's problematic
Please Help
using System;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Xml.Serialization;
namespace Server_WIN_
{
class Program
{
public static XmlSerializer xs = new XmlSerializer(typeof(RSAParameters));
public static TcpListener server = new TcpListener(IPAddress.Parse("192.168.1.93"), 78);
public static TcpClient client = null;
public static NetworkStream canwetalk = null;
public static RSACryptoServiceProvider csp = new RSACryptoServiceProvider(4096);
public static RSAParameters publickey;
public static RSAParameters privatekey;
static Program()
{
server.Start();
csp.PersistKeyInCsp = false;
publickey = csp.ExportParameters(false);
privatekey = csp.ExportParameters(true);
client = server.AcceptTcpClient();
canwetalk = client.GetStream();
}
public static void Main(string[] args)
{
string strHostName = "";
strHostName = Dns.GetHostName();
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
Random ran = new Random();
HashAlgorithm sha = SHA256.Create();
string msg = "";
byte[] buffer = new byte[4096];
msg = "test";
msg = Encrypt(msg);
msg = Decrypt(msg);
Console.WriteLine(msg);
}
public static string PublicKeyString()
{
byte[] bytes = new byte[4096];
var sw = new StringWriter();
var xs = new XmlSerializer(typeof(RSAParameters));
xs.Serialize(sw, publickey);
return sw.ToString();
}
public static string PrivateKeyString()
{
byte[] bytes = new byte[4096];
var sw = new StringWriter();
var xs = new XmlSerializer(typeof(RSAParameters));
xs.Serialize(sw, privatekey);
return sw.ToString();
}
public static string Encrypt(string msg)
{
csp.ImportParameters(publickey);
byte[] data = System.Text.Encoding.ASCII.GetBytes(msg);
byte[] cipher = csp.Encrypt(data, false);
return System.Text.Encoding.ASCII.GetString(cipher);
}
public static string Decrypt(string msg)
{
try
{
csp.ImportParameters(privatekey);
byte[] decrypted = csp.Decrypt(System.Text.Encoding.ASCII.GetBytes(msg), false);
return System.Text.Encoding.Unicode.GetString(decrypted);
}
catch(CryptographicException e)
{
string p = e.ToString();
Console.WriteLine(p);
}
return "";
}
public static void ExportPublicKey()
{
string msg = PublicKeyString();
byte[] buffer = new byte[4096];
byte[] msg1 = System.Text.Encoding.ASCII.GetBytes(msg);
canwetalk.Write(msg1, 0, msg1.Length);
}
public static void ToStream(string msg, bool Encryption)
{
if (Encryption)
{
msg = Encrypt(msg);
byte[] msgbytes = System.Text.Encoding.ASCII.GetBytes(msg);
canwetalk.Write(msgbytes, 0, msgbytes.Length);
}
else
{
byte[] msgbytes = System.Text.Encoding.ASCII.GetBytes(msg);
canwetalk.Write(msgbytes, 0, msgbytes.Length);
}
}
public static string ReadStream()
{
byte[] buffer = new byte[4096];
int i = canwetalk.Read(buffer,0,buffer.Length);
return System.Text.Encoding.ASCII.GetString(buffer,0,i);
}
}
You can find this stackoverflow question helpful, but it's quite out of date Error occurred while decoding OAEP padding
Don't use the same provider. Do this instead:
var publicKey = RSA.Create();
publicKey.ImportParameters(PUB_PARAMS);
var privateKey = RSA.Create();
privateKey.ImportParameters(PRIV_PARAMS);

Decoding Z64 (ZB64) string

I'm working on breaking down ZPL label definitions generated by NiceLabel label making software. For the most part I don't have to worry about decoding the Z64 because it is just encoded graphics and I don't need to change the underlying data.
However I have a line of text that is used as a graphic by the label for some reason probably due to Font's or something.
Anyways, the Z64 or ZB64 string is created by compressing the original data using LZ77 and encoding that as Base64 and then appending a CRC at the end.
TEST STRING FULL EXAMPLE:
:Z64:eJztkDFOxDAQRb81hRsULmBtruECyRwpZYpFGLmg5AhwFKMUuYal9CtL26QwHsbe3RMguv3lz9P85wD3/CWaiZ+56OjqWA44cwKIAyfeXXL1sQ7YWqd54czltTge+VOdOQsXFp8TrLUw9KEW3+6pLU4Zk3mC0ataonSEzU8JMywGCiFcue+c8YLGvYcLF5a+68WFhbvtRs5jdmVkWolj96vgXe/it7eucT+0+gxV5N5RrdTveQpevhnxO+BEfRe0xIzc/EbUzkn3lhLSIH6DdFeu+c39Hb7c7vksfrJryB8vu6A4cxE/NjpK1/6LkJZ3+nL1gaLt3D33/Ed+AehfkrY=:6C38
TEST STRING TARGET EXAMPLE:
eJztkDFOxDAQRb81hRsULmBtruECyRwpZYpFGLmg5AhwFKMUuYal9CtL26QwHsbe3RMguv3lz9P85wD3/CWaiZ+56OjqWA44cwKIAyfeXXL1sQ7YWqd54czltTge+VOdOQsXFp8TrLUw9KEW3+6pLU4Zk3mC0ataonSEzU8JMywGCiFcue+c8YLGvYcLF5a+68WFhbvtRs5jdmVkWolj96vgXe/it7eucT+0+gxV5N5RrdTveQpevhnxO+BEfRe0xIzc/EbUzkn3lhLSIH6DdFeu+c39Hb7c7vksfrJryB8vu6A4cxE/NjpK1/6LkJZ3+nL1gaLt3D33/Ed+AehfkrY=
My Code to Decode / Decompress:
static string DecompressZb64(string compressedString)
{
var b64 = SmartWarehouse.Shared.Utils.Parser.ConvertFromBase64(compressedString);
var encoding = new ASCIIEncoding();
var inBytes = Encoding.ASCII.GetBytes(b64);
var outBytes = new byte[inBytes.Length];
try
{
using (var memoryStream = new MemoryStream())
using (var decompressionStream = new DeflateStream(memoryStream, CompressionMode.Decompress))
{
decompressionStream.Read(outBytes, 0, inBytes.Length);
}
return encoding.GetString(outBytes);
}
catch (Exception e)
{
// TODO: DOcument exception
Console.WriteLine(e.Message);
}
return string.Empty;
}
Current Exception:
Block length does not match with its complement.
Stacktrace:
at System.IO.Compression.Inflater.DecodeUncompressedBlock(Boolean& end_of_block)
at System.IO.Compression.Inflater.Decode()
at System.IO.Compression.Inflater.Inflate(Byte[] bytes, Int32 offset, Int32 length)
at System.IO.Compression.DeflateStream.Read(Byte[] array, Int32 offset, Int32 count)
at SmartWarehouse.Tools.Program.DecompressZb64(String compressedString) in C:\Users\[user_dir]\Source\Repos\Handheld.[user].[fork]\SmartWarehouse.Tools\Program.cs:line 511
UPDATE:
I was looking into this and I found this SO post it is essentially the same issue. So i did some more research and i found this article on a blog from 2007. Which discusses a workaround by skipping the first 2 bytes in the input array due to those bytes not actually being included in the RFC specification.
CODE CHANGE:
static string DecompressZb64(string compressedString)
{
var b64 = Convert.FromBase64String(compressedString);
var encoding = new ASCIIEncoding();
var outBytes = new byte[b64.Length - 2];
try
{
using (var memoryStream = new MemoryStream(b64))
{
memoryStream.ReadByte();
memoryStream.ReadByte();
using (var decompressionStream = new DeflateStream(memoryStream, CompressionMode.Decompress))
{
decompressionStream.Read(outBytes, 0, b64.Length - 2);
}
}
return encoding.GetString(outBytes);
}
catch (Exception e)
{
// TODO: DOcument exception
Console.WriteLine(e.Message);
}
return string.Empty;
}
This code change doesn't actually produce an exception anymore however it doesn't decompress properly and returns this result:
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
That data looks fine to me, I got this image out of it:
It's a monochrome bitmap, one bit per pixel.
Your code didn't read until the end of the stream, there are actually 1280 bytes of image data, which can then be decoded to the image above.
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace ZB64Decode
{
public class Program
{
static void Main(string[] args)
{
//this is C#
var sb = new StringBuilder();
sb.AppendLine("^XA");
sb.AppendLine("^UT1,1");
sb.AppendLine("^Uh0,300,64,4000,2,0,F");
sb.AppendLine("^Uh1,300,64,4000,2,0,F");
sb.AppendLine("^UC1,0,1,0,0");
sb.AppendLine("^LH0,0");
sb.AppendLine("^LT0");
sb.AppendLine("^XZ");
sb.AppendLine("^XA");
sb.AppendLine("^PW3543");
sb.AppendLine("^LL512");
sb.AppendLine("^FO532,66^GFA,885,9272,76,:Z64:eJztWkFywyAMDMOBI0/gKTyNPC1P6RN6zKFTNxiCY0AgJE0nh+zJTc0GrdYES1wu/wWzHfiVIuLR2YZpB4FJpZH38UcouP6oRHddogqPEd/9f0WyLzyTGqpsVuLUj5tvoxv8tv3gqSa3WCSZxrjIoMgUzpAGoxnW2wZMdIFHG9tOEhQtekVyze7VSzYMQ/3DVIMTRt/sFtcUA0epZ2o28GCUfi3CCOjbDWHVhMaElRyOB1nss3+C7no7rAqf4DsTM+vr+A7VUYw4rTixeqAmqdUf2bKjESrz96LGwlQWNxRvPVHNw1N+2p9wJ30UWfkIfbKT5YQY1X/5gxVinMqtXCui53vjWVmMCEcmHS/EGOT1ecnKYoQudlXra3ONIphZ3Oh14H7rCzrKdDxXrijYLV3w5Socmr50HcixCUhfNBeQvkxIQPoiVOA92AkqPdISacwsImnMSklyiVgiu8FyF6+EnUbEXjk8SS4Rq+YUviuXyCOUH6IP14er5npX37/rmiO5rkqu90K/Q5Jcux0Ud0OekCwvuZ+Q3OdI7r9EDJZJJPerkvtoiUQWY0m+d0i+Dwk4/5BJ8P2R++p+enk3XIf5I3uSdYDX93gKTnUEywvypLdmBVlVgwInk1U1iFUcqibCKVo1AjHqhc1Qanm1W2qsq5FouFZqS677diyw2r7LcL0Vnjax7rTgHsEQQC+CUsDvl+8vpMYCOGTQogEwaALBLZo+hk2gpRbYpM1llnLpx4V6fMsQ0TQM6KaAmQqisC1ijWiyahwZ7jZUVxfZIcb0m1F96x12dnzALRx9GHf8x6cFWmzwkQAPH2EA4AE26PMh0lmTagLkMye+HDG5P4+HUCbVsHGZIqqzMLPb/wCr2VTW:718B");
sb.AppendLine("^PQ1,0,1,Y^XZ");
var zpl = sb.ToString();
//extract the Z64-String
var z64Data = "";
var bytesPerRow = 0;
foreach (var item in zpl.Split('^'))
{
if (item.StartsWith("GFA"))
{
var sp= item.Split(':');
z64Data = item.Substring(sp[0].Length);
bytesPerRow = Convert.ToInt32(sp[0].Split(',')[3]);
break;
}
}
//convert String to Bitmap
Bitmap decodedBitmap = null;
if (z64Data.StartsWith(":Z64"))
{
var imageData = DecompressZb64(z64Data.Substring(5));
int width = bytesPerRow * 8;
int height = imageData.Length / bytesPerRow;
decodedBitmap = ArrayToBitmap(imageData, width, height, PixelFormat.Format1bppIndexed);
}
Debug.WriteLine(decodedBitmap.Width + ":" + decodedBitmap.Height);
}
public static Bitmap ArrayToBitmap(byte[] bytes, int width, int height, PixelFormat pixelFormat)
{
var image = new Bitmap(width, height, pixelFormat);
var imageData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
ImageLockMode.ReadWrite, pixelFormat);
try
{
Marshal.Copy(bytes, 0, imageData.Scan0, bytes.Length);
}
finally
{
image.UnlockBits(imageData);
}
return image;
}
public static byte[] DecompressZb64(string compressedString)
{
var b64 = Convert.FromBase64String(compressedString.Split(':')[0]).Skip(2).ToArray();
return Decompress(b64);
}
public static byte[] Decompress(byte[] data)
{
byte[] decompressedArray = null;
try
{
using (MemoryStream decompressedStream = new MemoryStream())
{
using (MemoryStream compressStream = new MemoryStream(data))
{
using (DeflateStream deflateStream = new DeflateStream(compressStream, CompressionMode.Decompress))
{
deflateStream.CopyTo(decompressedStream);
}
}
decompressedArray = decompressedStream.ToArray();
}
}
catch (Exception ex)
{
// do something !
}
return decompressedArray;
}
}
}

.net core PGP Encryption Decryption

Running into error on the void Encryption().
public void Encryption()
{
#region PGP Encryption
PgpEncryptionKeys encryptionKeys = new PgpEncryptionKeys(#"C:\Keys\PGPPublicKey.asc", #"C:\Keys\PGPPrivateKey.asc", "password");
PgpEncrypt encrypter = new PgpEncrypt(encryptionKeys);
using (Stream outputStream = File.Create("C:\\Keys\\EncryptData.txt"))
{
encrypter.EncryptAndSign(outputStream, new FileInfo(#"D:\Keys\PlainText.txt"));
}
Console.WriteLine("Encryption Done !");
#endregion
}
I used https://code.msdn.microsoft.com/vstudio/Pretty-Good-Privacy-using-4f473c67
as a reference.
I am confused about the parameters in the PgpEncryptionKeys.
Does anyone have a working example or help? This is my first time encrypting so I am little lost.
I'm using by this way:
I think can help you!
Helper:
public static void EncryptPgpFile(string inputFile, string outputFile, string publicKeyFile, bool armor, bool withIntegrityCheck)
{
using (Stream publicKeyStream = File.OpenRead(publicKeyFile))
{
PgpPublicKey pubKey = ReadPublicKey(publicKeyStream);
using (MemoryStream outputBytes = new MemoryStream())
{
PgpCompressedDataGenerator dataCompressor = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
PgpUtilities.WriteFileToLiteralData(dataCompressor.Open(outputBytes), PgpLiteralData.Binary, new FileInfo(inputFile));
dataCompressor.Close();
PgpEncryptedDataGenerator dataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());
dataGenerator.AddMethod(pubKey);
byte[] dataBytes = outputBytes.ToArray();
using (Stream outputStream = File.Create(outputFile))
{
if (armor)
{
using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(outputStream))
using (Stream outputStream = dataGenerator.Open(armoredStream, dataBytes.Length))
outputStream.Write(dataBytes, 0, dataBytes.Length);
}
else
{
using (Stream outputStream = dataGenerator.Open(armoredStream, dataBytes.Length))
outputStream.Write(dataBytes, 0, dataBytes.Length);
}
}
}
}
}
private static PgpPublicKey ReadPublicKey(Stream inputStream)
{
inputStream = PgpUtilities.GetDecoderStream(inputStream);
PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(inputStream);
foreach (PgpPublicKeyRing keyRing in pgpPub.GetKeyRings())
{
foreach (PgpPublicKey key in keyRing.GetPublicKeys())
{
if (key.IsEncryptionKey)
return key;
}
}
throw new ArgumentException("Can't find encryption key in key ring.");
}
Usage:
EncryptPgpFile(inputFile, outputFile, publicKeyPath, true, true);

Encrypted Serialization of Objects in C#

I am storing my DataTable in a file using the function given below which i had taken from a website. The code works well.
The problem is:
I want to apply some sort of encryption here. How can i achieve that?
public void SerializeObject<T>(T serializableObject, string fileName)
{
if (serializableObject == null) { return; }
try
{
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, serializableObject);
stream.Position = 0;
xmlDocument.Load(stream);
xmlDocument.Save(fileName);
stream.Close();
}
}
catch (Exception ex)
{
//Log exception here
}
}
Any help is highly appreciated.
Thanks
Encrypt/Decrypt your streamed XML file with the given below class:
You can use another encryption strategy it is depending on your requirements.
public static class EncryptionManagement
{
private static SymmetricAlgorithm encryption;
private const string password = "admin";
private const string Mkey = "MY SECRET KEY";
private static void Init()
{
encryption = new RijndaelManaged();
var key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(Mkey));
encryption.Key = key.GetBytes(encryption.KeySize / 8);
encryption.IV = key.GetBytes(encryption.BlockSize / 8);
encryption.Padding = PaddingMode.PKCS7;
}
public static void Encrypt(Stream inStream, Stream OutStream)
{
Init();
var encryptor = encryption.CreateEncryptor();
inStream.Position = 0;
var encryptStream = new CryptoStream(OutStream, encryptor, CryptoStreamMode.Write);
inStream.CopyTo(encryptStream);
encryptStream.FlushFinalBlock();
}
public static void Decrypt(Stream inStream, Stream OutStream)
{
Init();
var encryptor = encryption.CreateDecryptor();
inStream.Position = 0;
var encryptStream = new CryptoStream(inStream, encryptor, CryptoStreamMode.Read);
encryptStream.CopyTo(OutStream);
OutStream.Position = 0;
}
}

Categories