Bouncy Castle AES Encryption - providing input in blocks - encryption

I'm using Bouncy Castle library to encrypt some data in my Windows Store App. My EncryptHelper class:
public static class EncryptHelper
{
private const string KEY = "chiaveAES";
private const int SIZE = 16;
private enum CipherMode
{
Encrypt,
Decrypt
}
private static PaddedBufferedBlockCipher InitCipher(CipherMode mode)
{
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesLightEngine()), new ZeroBytePadding());
var key = new byte[32];
var keyArray = KEY.ToCharArray();
Buffer.BlockCopy(keyArray, 0, key, 0, Math.Min(keyArray.Length, key.Length));
cipher.Init(mode == CipherMode.Encrypt, new KeyParameter(key));
return cipher;
}
public static async Task Encrypt(Stream sourceStream, Stream destinationStream, bool autoSeekStart = true, bool autoSeekEnd = true)
{
//await Process(InitCipher(CipherMode.Encrypt), sourceStream, destinationStream, autoSeekStart, autoSeekEnd);
await ProcessBlocks(InitCipher(CipherMode.Encrypt), sourceStream, destinationStream, autoSeekStart, autoSeekEnd);
}
public static async Task Decrypt(Stream sourceStream, Stream destinationStream, bool autoSeekStart = true, bool autoSeekEnd = true)
{
//await Process(InitCipher(CipherMode.Decrypt), sourceStream, destinationStream, autoSeekStart, autoSeekEnd);
await ProcessBlocks(InitCipher(CipherMode.Decrypt), sourceStream, destinationStream, autoSeekStart, autoSeekEnd);
}
private static async Task Process(PaddedBufferedBlockCipher cipher, Stream sourceStream, Stream destinationStream, bool autoSeekStart, bool autoSeekEnd)
{
if (autoSeekStart)
{
sourceStream.ToBegin();
destinationStream.ToBegin();
}
var size = Convert.ToInt16(sourceStream.Length);
byte[] inBuffer = new byte[size];
byte[] outBuffer = new byte[cipher.GetOutputSize(size)];
int inCount = 0;
int outCount = 0;
try
{
inCount = await sourceStream.ReadAsync(inBuffer, 0, inBuffer.Length);
outCount = cipher.ProcessBytes(inBuffer, 0, inCount, outBuffer, 0);
outCount += cipher.DoFinal(outBuffer, outCount);
await destinationStream.WriteAsync();
await destinationStream.FlushAsync();
}
catch { }
if (autoSeekEnd)
{
sourceStream.ToBegin();
destinationStream.ToBegin();
}
}
private static async Task ProcessBlocks(PaddedBufferedBlockCipher cipher, Stream sourceStream, Stream destinationStream, bool autoSeekStart, bool autoSeekEnd)
{
if (autoSeekStart)
{
sourceStream.ToBegin();
destinationStream.ToBegin();
}
byte[] inBuffer = new byte[SIZE];
byte[] outBuffer = new byte[cipher.GetOutputSize(SIZE)];
int inCount = 0;
int outCount = 0;
try
{
while ((inCount = await sourceStream.ReadAsync(inBuffer, 0, inBuffer.Length)) > 0)
{
outCount += cipher.ProcessBytes(inBuffer, 0, inCount, outBuffer, 0);
await destinationStream.WriteAsync(outBuffer, 0, outBuffer.Length);
}
outBuffer = ?
outCount += cipher.DoFinal(outBuffer, outCount);
await destinationStream.WriteAsync(outBuffer, 0, outCount);
await destinationStream.FlushAsync();
}
catch { }
if (autoSeekEnd)
{
sourceStream.ToBegin();
destinationStream.ToBegin();
}
}
}
My Process() method works fine, but when on the instruction
inCount = await sourceStream.ReadAsync(inBuffer, 0, inBuffer.Length);
I'm afraid it may occurr an OutOfMemoryException if the stream has too much data. So, I was trying to build the ProcessBlocks() method, which should read from the stream progressively, one block per time, without overcharging the RAM. I have some doubts on how to behave with outBuffer: it should be overwritten in every cycle in which cipher.ProcessBytes() gets executed, but of which size should it be just before the cipher.DoFinal() invocation?
Thank you
UPDATE 30/07/2015
I modified the Main in the answer to handle a zip file and the outcoming zip file is no more a valid ZIP, could someone explain me why?
public static void Main(string[] args)
{
var plainPath = #"C:\Users\Federico\Desktop\0abed72d-defc-4c9a-a8ae-3fec43f01224.zip";
var decryptPath = #"C:\Users\Federico\Desktop\0abed72d-defc-4c9a-a8ae-3fec43f01224 - decrypted.zip";
var plainStream = new FileStream(plainPath, FileMode.Open, FileAccess.Read);
var cipherStream = new MemoryStream();
EncryptHelper.Encrypt(plainStream, cipherStream);
cipherStream.Seek(0, SeekOrigin.Begin);
FileStream fs = new FileStream(decryptPath, FileMode.Create);
EncryptHelper.Decrypt(cipherStream, fs);
fs.Flush();
fs.Close();
}

cipher.DoFinal() will produce as many as 2 * Cipher.GetBlockSize() bytes. The actual number of bytes produced is returned by the method.
Here is an example that is loosely based on your example.
using System;
using System.IO;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Engines;
using System.Text;
namespace PaddedBufferedBlockCipherExample
{
public class EncryptHelper
{
private const string KEY = "chiaveAES";
private const int BufferSize = 1024;
private PaddedBufferedBlockCipher cipher;
public enum CipherMode
{
Encrypt,
Decrypt
}
public EncryptHelper (CipherMode mode)
{
cipher = new PaddedBufferedBlockCipher (new CbcBlockCipher (new AesLightEngine ()), new Pkcs7Padding ());
var key = new byte[32];
var keyArray = KEY.ToCharArray ();
Buffer.BlockCopy (keyArray, 0, key, 0, Math.Min (keyArray.Length, key.Length));
cipher.Init (mode == CipherMode.Encrypt, new KeyParameter (key));
}
public static void Encrypt (Stream sourceStream, Stream destinationStream)
{
var helper = new EncryptHelper (CipherMode.Encrypt);
helper.ProcessBlocks (sourceStream, destinationStream);
}
public static void Decrypt (Stream sourceStream, Stream destinationStream)
{
var helper = new EncryptHelper (CipherMode.Decrypt);
helper.ProcessBlocks (sourceStream, destinationStream);
}
private void ProcessBlocks (Stream sourceStream, Stream destinationStream)
{
// inBuffer is sized for efficient I/O
var inBuffer = new byte[BufferSize];
// outBuffer should be large enough to not require further resizing
var outBuffer = new byte[cipher.GetBlockSize() + cipher.GetOutputSize (inBuffer.Length)];
int inCount = 0;
int outCount = 0;
// Process data using the cipher.ProcessBytes method, until we reach EOF
while ((inCount = sourceStream.Read (inBuffer, 0, inBuffer.Length)) > 0) {
outCount = cipher.ProcessBytes (inBuffer, 0, inCount, outBuffer, 0);
destinationStream.Write (outBuffer, 0, outCount);
}
// Now "flush" the cipher instance by calling the DoFinal method. This
// will finish the en/de-cryption by ciphering any buffered data and processing any
// encryption padding.
outCount = cipher.DoFinal (outBuffer, 0);
destinationStream.Write (outBuffer, 0, outCount);
}
public static void Main (string[] args)
{
var plainPath = "/Users/robert/src/csharp_toys/toy1/Program.cs";
var plainStream = new FileStream (plainPath, FileMode.Open, FileAccess.Read);
var cipherStream = new MemoryStream ();
EncryptHelper.Encrypt (plainStream, cipherStream);
cipherStream.Seek (0, SeekOrigin.Begin);
var decryptedStream = new MemoryStream ();
EncryptHelper.Decrypt (cipherStream, decryptedStream);
var decryptedString = Encoding.ASCII.GetString (decryptedStream.ToArray ());
Console.Write (decryptedString);
}
}
}

UPDATE 30/07/2015
I found out it was just a padding problem, I used ZeroBytePadding and it messed up everything.

Related

Decompress stream from HttpClient using SharpZipLib in Xamarin.Forms

I am trying decompress stream from HttpClient using SharpZipLib in Xamarin.Forms. This code perfectly works on iOS, but on Android CanDecompressEntry() always returns false. What i'm missing? Maybe Android need some permissions?
var zipStream = await httpClient.GetStreamAsync(url);
using (ZipInputStream s = new ZipInputStream(zipStream))
{
ZipEntry theEntry;
//const int size = 2048;
byte[] data = new byte[2048];
Debug.WriteLine(s.CanDecompressEntry);
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.IsFile)
{
string str = "";
while (true)
{
int size = s.Read(data, 0, data.Length);
if (size > 0)
{
str += new UTF8Encoding().GetString(data, 0, size);
}
else
{
files.Add(theEntry.Name.Substring(0,theEntry.Name.Length-5), str);
break;
}
}
}
}
}
return files;
Ok. I just set ConfigureAwait to false, and it works.
var zipStream = await httpClient.GetStreamAsync(url).ConfigureAwait(false);

Making screen capture in xamarin.forms

Is there a package that does screen capture in xamarin.forms ?
I need also to capture google maps screen shots
Check out this blog post by Daniel Hindrikes.
I'm going to assume that you use a PCL for your shared code.
You will need to create an interface in your PCL. He calls it IScreenshotManager. The declaration looks like this:
public interface IScreenshotManager
{
Task<byte[]> CaptureAsync();
}
Now all platforms will have their own implementation for it.
For iOS;
public class ScreenshotManager : IScreenshotManager
{
public async System.Threading.Tasks.Task<byte[]> CaptureAsync()
{
var view = UIApplication.SharedApplication.KeyWindow.RootViewController.View;
UIGraphics.BeginImageContext(view.Frame.Size);
view.DrawViewHierarchy(view.Frame, true);
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
using(var imageData = image.AsPNG())
{
var bytes = new byte[imageData.Length];
System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, bytes, 0, Convert.ToInt32(imageData.Length));
return bytes;
}
}
}
For Android:
public class ScreenshotManager : IScreenshotManager
{
public static Activity Activity { get; set; }
public async System.Threading.Tasks.Task<byte[]> CaptureAsync()
{
if(Activity == null)
{
throw new Exception("You have to set ScreenshotManager.Activity in your Android project");
}
var view = Activity.Window.DecorView;
view.DrawingCacheEnabled = true;
Bitmap bitmap = view.GetDrawingCache(true);
byte[] bitmapData;
using (var stream = new MemoryStream())
{
bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
return bitmapData;
}
}
And for Windows Phone:
public class ScreenshotManager : IScreenshotManager
{
public async Task<byte[]> CaptureAsync()
{
var rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;
var screenImage = new WriteableBitmap((int)rootFrame.ActualWidth, (int)rootFrame.ActualHeight);
screenImage.Render(rootFrame, new MatrixTransform());
screenImage.Invalidate();
using (var stream = new MemoryStream())
{
screenImage.SaveJpeg(stream, screenImage.PixelWidth, screenImage.PixelHeight, 0, 100);
var bytes = stream.ToArray();
return bytes;
}
}
}
Don't forget to register your platform specific implementations with the attribute which registers it with the Dependency Service, like this:
[assembly: Xamarin.Forms.Dependency (typeof (ScreenshotManager))]
It goes above the namespace declaration.
Now from your shared code you would be able to get the byte[] of a screenshot with a call like this:
var screenshotBytes = DependencyService.Get<IScreenshotManager>().CaptureAsync();
You probably want to check if DependencyService.Get<IScreenshotManager>() isn't null before using it.
After that you can turn your byte[] into an image and do whatever you like with it!
Implementation for UWP
public async Task<byte[]> CaptureAsync()
{
//create and capture Window
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(Window.Current.Content);
var pixelpuffer = await renderTargetBitmap.GetPixelsAsync();
var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
IRandomAccessStream stream = new InMemoryRandomAccessStream();
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, logicalDpi, logicalDpi, pixelpuffer.ToArray());
await encoder.FlushAsync();
byte[] resultingBuffer = new byte[stream.Size];
await stream.ReadAsync(resultingBuffer.AsBuffer(), (uint)resultingBuffer.Length, InputStreamOptions.None);
return resultingBuffer;
}

Unable to run second WebClient request after timed out and aborting request

I have a desktop app which is downloading 1 or more small files (jpg with less than 400KB in size and no more than 20 at a time) simultaneously using a CustomWebClient object and calling OpenReadAsync(). The download process is working just fine if there is no problem in the process. I want to limit the response to a certain time (15 sec) so I have introduced a timeOut handling which is Aborting the request. Even the timeout is working and after that my “OpenReadCompletedEventHandler” method is receiving System.Net.WebException: The request was aborted: The request was canceled (which is the right behaviour).
Now, my problem is that I want to allow the user to try re-loading the picture(s). So the next webClient request(s) are failing with the same WebException. Below is my code.
Here is my Custom WebClient class (used in order to have more than 2 async connections at a time):
internal class ExtendedWebClient : WebClient
{
private Timer _timer;
public int ConnectionLimit { get; set; }
public int ConnectionTimeout { get; set; }
public ExtendedWebClient()
{
this.ConnectionLimit = 2;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address) as HttpWebRequest;
if (request != null){_timer = new Timer(TimeoutRequest, request, ConnectionTimeout, Timeout.Infinite);
request.ServicePoint.ConnectionLimit = this.ConnectionLimit;
request.ServicePoint.MaxIdleTime = 5000;
request.ServicePoint.ConnectionLeaseTimeout = 5000;
}
return request;
}
private void TimeoutRequest(object state)
{
_timer.Dispose();
_timer = null;
((WebRequest)state).Abort();
}
protected override void Dispose(bool disposing)
{
if (_timer != null)
{
_timer.Dispose();
_timer = null;
}
base.Dispose(disposing);
}
}
Here is the code to download the files using my custom WebClient class:
internal struct PageWaitHandleState
{
public int WaitHandleIndexInPage;
public bool ImageIsLoaded;
public string ErrMessage;
}
public Image[] downloadedImages;
private PageWaitHandleState[] waitHandlesInPage;
private OpenReadCompletedEventHandler[] downloadComplete;
private EventWaitHandle[] pagesEWH = null;
private EventWaitHandle[] downloadImageEvent;
private int availableImages = 1; // Set here to simplify, but as I stated in my description, it may be more than 1.
int downloadTimeOut = 15000;
int maxSimultaneousDownloads = 20;
private void DownloadImages(int pageIndex = 0, string[] imageUrl)
{
if (pagesEWH[pageIndex] != null)
{
ReloadImages(pageIndex, imageUrl); // Executed in the second request
return;
else
{
pagesEWH[pageIndex] = new EventWaitHandle[availableImages];
downloadedImages = new Image[availableImages];
downloadComplete = new OpenReadCompletedEventHandler[availableImages];
downloadImageEvent = new EventWaitHandle[availableImages];
waitHandlesInPage = new PageWaitHandleState[availableImages];
// Set the downloadComplete deletages
for (int i = 0; i < availableImages; i++)
{
downloadComplete[i] = ProcessImage;
}
}
for (int imgCounter = 0; i < availableImages; i++)
{
waitHandlesInPage[imgCounter] = new PageWaitHandleState() { ImageIsLoaded = false, WaitHandleIndexInPage = imgCounter, ErrMessage = null };
downloadImageEvent[imgCounter] = GrabImageAsync(imageUrl[imgCounter], downloadComplete[imgCounter], imgCounter, downloadTimeOut, maxSimultaneousDownloads);
pagesEWH[imgCounter] = downloadImageEvent[imgCounter];
}
offenderIndex++;
}
}
private static EventWaitHandle GrabImageAsync(string url, OpenReadCompletedEventHandler openReadCompletedEventHandler, int imgCounter, int downloadTimeOut, int maxSimultaneousDownloads)
{
var myClient = new ExtendedWebClient();
myClient.ConnectionLimit = maxSimultaneousDownloads;
myClient.ConnectionTimeout = downloadTimeOut;
myClient.OpenReadCompleted += openReadCompletedEventHandler;
var iewh = new ImageEventWaitHandle() { ewh = new EventWaitHandle(false, EventResetMode.ManualReset), ImageIndex = imgCounter };
myClient.OpenReadAsync(new Uri(url), iewh);
return iewh.ewh;
}
internal void ProcessImage(object sender, OpenReadCompletedEventArgs e)
{
ImageEventWaitHandle iewh = (ImageEventWaitHandle)e.UserState;
bool disposeObject = false;
try
{
if (e.Cancelled)
{
this.waitHandlesInPage[iewh.ImageIndex].ImageIsLoaded = false;
this.waitHandlesInPage[iewh.ImageIndex].ErrMessage = "WebClient request was cancelled";
}
else if (e.Error != null)
{
this.waitHandlesInPage[iewh.ImageIndex].ImageIsLoaded = false;
this.waitHandlesInPage[iewh.ImageIndex].ErrMessage = e.Error.Message;
iewh.ewh.Set();
this.downloadImageEvent[iewh.ImageIndex].Close();
}
else
{
using (Stream inputStream = e.Result)
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = new byte[4096];
int bytesRead;
int totalReadBytes = 0;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length); // Exception fired here with the second request
ms.Write(buffer, 0, bytesRead);
totalReadBytes += bytesRead;
} while (inputStream.CanRead && bytesRead > 0);
this.downloadedImages[iewh.ImageIndex] = Image.FromStream(ms);
this.waitHandlesInPage[iewh.ImageIndex].ImageIsLoaded = true;
this.waitHandlesInPage[iewh.ImageIndex].ErrMessage = null;
}
disposeObject = true;
}
}
catch (Exception exc)
{
this.downloadedImages[iewh.ImageIndex] = null;
}
finally
{
// Signal the wait handle
if (disposeObject)
{
iewh.ewh.Set();
((WebClient)sender).Dispose();
}
}
}
private void ReloadImages(int pageIndex, string[] imageUrl)
{
for (int imgCounter = 0; imgCounter < availableImages; imgCounter++)
{
this.downloadComplete[imgCounter] = this.ProcessImage;
this.waitHandlesInPage[imgCounter] = new PageWaitHandleState() { ImageIsLoaded = false, WaitHandleIndexInPage = imgCounter, ErrMessage = null };
this.downloadImageEvent[imgCounter] = GrabImageAsync(ImageUrl[imgCounter],this.downloadComplete[imgCounter], imgCounter, downloadTimeOut, maxSimultaneousDownloads);
this.pagesEWH[imgCounter] = this.downloadImageEvent[imgCounter];
}
}
Finally, when I want to access the images I check if they are ready by using:
private bool ImagesInPageReady(int pageIndex, int recordsInCurrentPage)
{
if (_PagesEWH[pageIndex] != null)
{
int completedDownloadsCount = 0;
bool waitHandleSet;
// Wait for the default images first (imgCounter = 0). When moving page or asking for more pictures, then wait for the others.
for (int ewhIndexInPage = 0; ewhIndexInPage < recordsInCurrentPage; ewhIndexInPage++)
{
if (this.pagesEWH[ewhIndexInPage].WaitOne(this.downloadTimeOut))
{
if (this.WaitHandlesInPage[ewhIndexInPage].ImageIsLoaded)
{
completedDownloadsCount++;
}
}
else
{
this.pagesEWH[ewhIndexInPage].Set();
}
}
return (completedDownloadsCount > 0);
}
return false;
}
#usr, thanks for pointing me in the right direction. HttpClient was the solution. So I basically encapsulated my HttpClient object in a new class, together with the ProcessImage() method and exposing and event fired by the same method.

Windows Store App HttpClient progress

I need to provide the download progress inside the app for an arbitrary file.
I thought I could use HttpClient.GetInputStreamAsync progress but it is not fine grained. The progress notification is delivered very rare. The code below:
var httpClient = new HttpClient();
var path = new Uri(#"http://<path>");
using (var inputStream = (await httpClient.GetInputStreamAsync(path).AsTask(new MyProgress())).AsStreamForRead())
{
var outputFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("output.mov", CreationCollisionOption.ReplaceExisting);
using (var outputStream = (await outputFile.OpenAsync(FileAccessMode.ReadWrite)).AsStreamForWrite())
{
await inputStream.CopyToAsync(outputStream);
await outputStream.FlushAsync();
}
}
Debug.WriteLine("done");
private class MyProgress : IProgress<HttpProgress>
{
public void Report(HttpProgress value)
{
Debug.WriteLine("HTTP {0} progress {1}/{2}", value.Stage, value.BytesReceived, value.TotalBytesToReceive);
}
}
outputs:
HTTP ResolvingName progress 0/
HTTP ConnectingToServer progress 0/
HTTP SendingHeaders progress 0/
HTTP WaitingForResponse progress 0/
HTTP ReceivingHeaders progress 0/
HTTP ReceivingContent progress 0/109192147
done
So at some point of time the total bytes to receive is known but no progress reported during file download.
I ended up with solution like below:
var httpClient = new HttpClient();
var path = new Uri(#"http://<path>");
var progressHelper = new ProgressHelper();
using (var inputStream = (await httpClient.GetInputStreamAsync(path).AsTask(progressHelper)).AsStreamForRead())
{
var outputFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("output.mov", CreationCollisionOption.ReplaceExisting);
using (var outputStream = (await outputFile.OpenAsync(FileAccessMode.ReadWrite)).AsStreamForWrite())
{
var buffer = new byte[1024 * 1024];
int read;
while ((read = await inputStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
progressHelper.BytesReceived += (ulong)read;
await outputStream.WriteAsync(buffer, 0, read);
}
await outputStream.FlushAsync();
}
}
Debug.WriteLine("done");
private class ProgressHelper : IProgress<HttpProgress>
{
private ulong _bytesReceived = 0;
private ulong? _totalBytesToReceive = null;
public void Report(HttpProgress value)
{
Debug.WriteLine("HTTP {0} progress {1}/{2}", value.Stage, value.BytesReceived, value.TotalBytesToReceive);
TotalBytesToReceive = value.TotalBytesToReceive;
}
public ulong? TotalBytesToReceive
{
get
{
return _totalBytesToReceive;
}
set
{
if (_totalBytesToReceive == value)
return;
_totalBytesToReceive = value;
UpdateProgress();
}
}
public ulong BytesReceived
{
get
{
return _bytesReceived;
}
set
{
if (_bytesReceived == value)
return;
_bytesReceived = value;
UpdateProgress();
}
}
public int? Progress
{
get
{
if (_totalBytesToReceive.HasValue)
{
return (int)Math.Round((100.0 * _bytesReceived) / _totalBytesToReceive.Value);
}
return null;
}
}
private void UpdateProgress()
{
Debug.WriteLine("Progress: {0}", Progress);
}
}
Since the HttpClient.GetInputStreamAsync doesn't support progress during file download, you can use other methods of HttpClient such as GetAsync andGetBufferAsync.The following code is updating of your code to use HttpClient.GetAsync.
var httpClient = new HttpClient();
var path = new Uri("https://sec.ch9.ms/slides/developerGuideToWindows10/02-XAMLcontrols.pptx");
HttpResponseMessage response = await httpClient.GetAsync(path).AsTask(new MyProgress());
using (Stream responseStream = (await response.Content.ReadAsInputStreamAsync()).AsStreamForRead())
{
var outputFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("output.pptx", CreationCollisionOption.ReplaceExisting);
using (var outputStream = (await outputFile.OpenAsync(FileAccessMode.ReadWrite)).AsStreamForWrite())
{
await responseStream.CopyToAsync(outputStream);
await outputStream.FlushAsync();
}
}
Debug.WriteLine("done");
And the outputs

RSA Data decryption error.The data to be decrypted exceeds the maximum for this modulus of 64 bytes

while encrypting and descripting the string with rsa provider I am getting this error.
RSA Data decryption error.The data to be decrypted exceeds the maximum for this modulus of 64 bytes.
Can any one have idea how to slove this error?
internal sealed class RSAProvider
{
#region key store class
[Serializable]
private struct rsaKey
{
public rsaKey(RSAParameters rsaKeyInfo)
{
D = rsaKeyInfo.D;
DP = rsaKeyInfo.DP;
DQ = rsaKeyInfo.DQ;
Exponent = rsaKeyInfo.Exponent;
InverseQ = rsaKeyInfo.InverseQ;
Modulus = rsaKeyInfo.Modulus;
P = rsaKeyInfo.P;
Q = rsaKeyInfo.Q;
}
public RSAParameters CreateRSAKey()
{
RSAParameters rsaKeyInfo = new RSAParameters();
rsaKeyInfo.D = D;
rsaKeyInfo.DP = DP;
rsaKeyInfo.DQ = DQ;
rsaKeyInfo.Exponent = Exponent;
rsaKeyInfo.InverseQ = InverseQ;
rsaKeyInfo.Modulus = Modulus;
rsaKeyInfo.P = P;
rsaKeyInfo.Q = Q;
return rsaKeyInfo;
}
public byte[] D;
public byte[] DP;
public byte[] DQ;
public byte[] Exponent;
public byte[] InverseQ;
public byte[] Modulus;
public byte[] P;
public byte[] Q;
}
#endregion
private static RSAParameters rsaKeyParameters;
static RSAProvider()
{
string rsaKeyString = System.Configuration.ConfigurationSettings.AppSettings["RSAKey"];
if(rsaKeyString != null)
{
rsaKeyParameters = GetKeyByString(rsaKeyString);
}
}
private RSAProvider()
{
}
private static RSAParameters RSAKeyInfo
{
get
{
return rsaKeyParameters;
}
}
private static bool DoOAEPPadding
{
get
{
return false;
}
}
public static string GenerateKey(int keySize)
{
//Create a new instance of RSACryptoServiceProvider to generate
//public and private key data.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(keySize);
RSAParameters rsaKeyInfo = RSA.ExportParameters(true);
return GetKeyString(rsaKeyInfo);
}
#region Encrypt
public static byte[] Encrypt(byte[] dataToEncrypt, string rsaKeyString)
{
RSAParameters rsaKeyInfo = GetKeyByString(rsaKeyString);
return Encrypt(dataToEncrypt, rsaKeyInfo);
}
public static byte[] Encrypt(byte[] dataToEncrypt, RSAParameters rsaKeyInfo)
{
try
{
//Create a new instance of RSACryptoServiceProvider.
// Common.Identity.ImpersonateValidUser("prana", "eetplpvt", "Avdhoota1985");
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//Import the RSA Key information. This only needs
//toinclude the public key information.
RSA.ImportParameters(rsaKeyInfo);
//Encrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
//return RSA.Encrypt(dataToEncrypt, DoOAEPPadding);
byte[] data = RSA.Encrypt(dataToEncrypt, DoOAEPPadding);
RSA.Clear();
//Common.Identity.UndoImpersonation();
return data;
}
//Catch and display a CryptographicException
//to the console.
catch(CryptographicException e)
{
// Updated By Divya Bhalodia on 27th June 2008 for Localization task
//throw new Exception("Data encryption error.", e);
Common.EnumLocalization.EnumLocalization loc = new Common.EnumLocalization.EnumLocalization(ASP.BL.ApplicationUsers.ApplicationUserController.CurrentUserCulture.Code, ASP.BL.Applications.ApplicationController.CurrentApplicationInfo.ItemId);
throw new Exception(loc.LocalizeString("RSA Data encryption error.") + e.Message, e);
// end Updated - Divya
}
}
public static byte[] Encrypt(byte[] dataToEncrypt)
{
return Encrypt(dataToEncrypt, RSAKeyInfo);
}
#endregion
#region Decrypt
public static byte[] Decrypt(byte[] dataToDecrypt, string rsaKeyString, bool doOAEPPadding)
{
RSAParameters rsaKeyInfo = GetKeyByString(rsaKeyString);
return Decrypt(dataToDecrypt, rsaKeyInfo, doOAEPPadding);
}
public static byte[] Decrypt(byte[] dataToDecrypt, RSAParameters rsaKeyInfo, bool doOAEPPadding)
{
try
{
//Create a new instance of RSACryptoServiceProvider.
Common.Identity.ImpersonateValidUser();
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(rsaKeyInfo);
//Decrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
//return RSA.Decrypt(dataToDecrypt, doOAEPPadding);
byte[] data = RSA.Decrypt(dataToDecrypt, doOAEPPadding);
RSA.Clear();
Common.Identity.UndoImpersonation();
return data;
}
//Catch and display a CryptographicException
//to the console.
catch(CryptographicException e)
{
// Updated By Divya Bhalodia on 27th June 2008 for Localization task
//throw new Exception("Data decryption error.", e);
Common.EnumLocalization.EnumLocalization loc = new Common.EnumLocalization.EnumLocalization(ASP.BL.ApplicationUsers.ApplicationUserController.CurrentUserCulture.Code, ASP.BL.Applications.ApplicationController.CurrentApplicationInfo.ItemId);
throw new Exception(loc.LocalizeString("RSA Data decryption error.") + e.Message, e);
// end Updated - Divya
}
}
public static byte[] Decrypt(byte[] dataToDecrypt)
{
return Decrypt(dataToDecrypt, RSAKeyInfo, DoOAEPPadding);
}
#endregion
#region Additional functions
private static string GetKeyString(RSAParameters rsaKeyInfo)
{
byte[] tmp;
rsaKey k = new rsaKey(rsaKeyInfo);
BinaryFormatter formater = new BinaryFormatter();
using(MemoryStream stream = new MemoryStream())
{
formater.Serialize(stream, k);
tmp = stream.ToArray();
}
Code(tmp);
return Convert.ToBase64String(tmp);
}
private static RSAParameters GetKeyByString(string rsaKeyString)
{
rsaKey k;
byte[] tmp = Convert.FromBase64String(rsaKeyString);
Code(tmp);
BinaryFormatter formater = new BinaryFormatter();
using(MemoryStream stream = new MemoryStream(tmp))
{
k = (rsaKey)formater.Deserialize(stream);
}
return k.CreateRSAKey();
}
private static void Code(byte[] tmp)
{
byte mask1 = 0x55;
byte mask3 = 0xB9;
byte mask4 = 0xCF;
for(int i = 0; i
I've encoutered similar problems but you can do two things to help yourself overcome them.
You need to ensure that hte data you are encrypting is shorter than the key that you are using. so if your key is 1024 bits then make sure that you are only bassing in say 1000 bits. To do this you need to get chunk your byte array into smaller chunks, encrypt each chunk and then store the encrypeted value in an array or a string. So instead of encrypting 1 string you encrypt say 5 strings.
When storing this information as a string make sure that all numbers are the same length, so if the formatter returns 15 you store the string with 015 so that you just divide by 3 later to get the byte to then put into the array.
To decrypt your data you need to simply read the length of the string and determine how many chunks to decrypt. Decrupt these one by one and then you can recreate the object with the decrupted byte array.
if you would like actual code please contact me personally and I'll be able to help you better with some script that can do this for you.

Resources