How to convert string to image.source in UWP? - c#

Encrypt.cs
BitmapImage bitmapImage = new BitmapImage(new Uri(this.BaseUri,#"D:\Others\Quotes\1.jpg"));
var plainString = bitmapImage;
string key = txtkey.Text; // Key
string encryptedString = await EncryptStringHelper(plainString.ToString(), key); // Encrypt method and get string
txbencrypt.Text = encryptedString;
Decrypt.cs
string encryptedString = txbencrypt.Text; // Encrypt text
string key = txtkey.Text; // Same key
string decryptedString = await DecryptStringHelper(encryptedString, key);
imgoutput.Source = decryptedString;
private Task<string> EncryptStringHelper(string plainString, string key)
{
try
{
var hashKey = GetMD5Hash(key);
var decryptBuffer = CryptographicBuffer.ConvertStringToBinary(plainString, BinaryStringEncoding.Utf8);
var AES = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
var symmetricKey = AES.CreateSymmetricKey((IBuffer)hashKey);
var encryptedBuffer = CryptographicEngine.Encrypt(symmetricKey, decryptBuffer, null);
var encryptedString = CryptographicBuffer.EncodeToBase64String(encryptedBuffer);
return Task.Run(() =>
{
return encryptedString;
});
}
catch (Exception ex)
{
return null;
}
}
public Task<string> DecryptStringHelper(string encryptedString, string key)
{
try
{
var hashKey = GetMD5Hash(key);
IBuffer decryptBuffer = CryptographicBuffer.DecodeFromBase64String(encryptedString);
var AES = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
var symmetricKey = AES.CreateSymmetricKey((IBuffer)hashKey);
var decryptedBuffer = CryptographicEngine.Decrypt(symmetricKey, decryptBuffer, null);
string decryptedString = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedBuffer);
return Task.Run(() =>
{
return decryptedString;
});
}
catch (Exception ex)
{
return null;
}
}
I develop Universal windows application(UWP) then tried encrypt and decrypt to image file, but i convert image to encrypt text then i couldn't convert when i decrypt that text into image. So how do i do that?

You would want to convert your base 64 string to a byte array, and then create the ImageSource from that.
byte[] data = Convert.FromBase64String(base64string);
if (data.caseImage.Count() > 1)
{
MemoryStream ms = new MemoryStream(data.caseImage, 0, data.caseImage.Length);
BitmapImage img = new BitmapImage();
var ras = ms.AsRandomAccessStream();
await img.SetSourceAsync(ras);
imgCase.Source = img;
}
with imgCase being a Xaml image.
in terms of initially creating the base64string you would want to do something like this:
Converting BitMapImage to ImageSource:
BitmapImage bitmapCamera = new BitmapImage();
bitmapCamera.SetSource(streamCamera);
// Convert the camera bitap to a WriteableBitmap object,
// which is often a more useful format.
int width = bitmapCamera.PixelWidth;
int height = bitmapCamera.PixelHeight;
WriteableBitmap wBitmap = new WriteableBitmap(width, height);
using (var stream = await capturedMedia.OpenAsync(FileAccessMode.Read))
{
wBitmap.SetSource(stream);
}
imgPreview.Source = wBitmap;
And or a StorageFile to Base64String:
byte[] fileBytes = null;
var imageFile = *Your storageFile*;
mimetype = imageFile.ContentType;
filetype = imageFile.FileType;
using (IRandomAccessStreamWithContentType stream = await imageFile.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (DataReader reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}
string base64 = Convert.ToBase64String(fileBytes);
Hope this helps.

Related

ASP.NET Web API C# Answer HttpRequest with Image via Json [duplicate]

How do you convert an image from a path on the user's computer to a base64 string in C#?
For example, I have the path to the image (in the format C:/image/1.gif) and would like to have a data URI like data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD.. representing the 1.gif image returned.
Try this
using (Image image = Image.FromFile(Path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
Get the byte array (byte[]) representation of the image, then use Convert.ToBase64String(), st. like this:
byte[] imageArray = System.IO.File.ReadAllBytes(#"image file path");
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
To convert a base64 image back to a System.Drawing.Image:
var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(base64String)));
Since most of us like oneliners:
Convert.ToBase64String(File.ReadAllBytes(imageFilepath));
If you need it as Base64 byte array:
Encoding.ASCII.GetBytes(Convert.ToBase64String(File.ReadAllBytes(imageFilepath)));
This is the class I wrote for this purpose:
public class Base64Image
{
public static Base64Image Parse(string base64Content)
{
if (string.IsNullOrEmpty(base64Content))
{
throw new ArgumentNullException(nameof(base64Content));
}
int indexOfSemiColon = base64Content.IndexOf(";", StringComparison.OrdinalIgnoreCase);
string dataLabel = base64Content.Substring(0, indexOfSemiColon);
string contentType = dataLabel.Split(':').Last();
var startIndex = base64Content.IndexOf("base64,", StringComparison.OrdinalIgnoreCase) + 7;
var fileContents = base64Content.Substring(startIndex);
var bytes = Convert.FromBase64String(fileContents);
return new Base64Image
{
ContentType = contentType,
FileContents = bytes
};
}
public string ContentType { get; set; }
public byte[] FileContents { get; set; }
public override string ToString()
{
return $"data:{ContentType};base64,{Convert.ToBase64String(FileContents)}";
}
}
var base64Img = new Base64Image {
FileContents = File.ReadAllBytes("Path to image"),
ContentType="image/png"
};
string base64EncodedImg = base64Img.ToString();
You can easily pass the path of the image to retrieve the base64 string
public static string ImageToBase64(string _imagePath)
{
string _base64String = null;
using (System.Drawing.Image _image = System.Drawing.Image.FromFile(_imagePath))
{
using (MemoryStream _mStream = new MemoryStream())
{
_image.Save(_mStream, _image.RawFormat);
byte[] _imageBytes = _mStream.ToArray();
_base64String = Convert.ToBase64String(_imageBytes);
return "data:image/jpg;base64," + _base64String;
}
}
}
Hope this will help.
You can use Server.Map path to give relative path and then you can either create image using base64 conversion or you can just add base64 string to image src.
byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/Upload_Image.png"));
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
This code works well with me on DotNet Core 6
using (Image image = Image.FromFile(path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, ImageFormat.Jpeg);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
// In my case I didn't find the part "data:image/png;base64,", so I added.
return $"data:image/png;base64,{base64String}";
}
}
That way it's simpler, where you pass the image and then pass the format.
private static string ImageToBase64(Image image)
{
var imageStream = new MemoryStream();
try
{
image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp);
imageStream.Position = 0;
var imageBytes = imageStream.ToArray();
var ImageBase64 = Convert.ToBase64String(imageBytes);
return ImageBase64;
}
catch (Exception ex)
{
return "Error converting image to base64!";
}
finally
{
imageStream.Dispose;
}
}
Based on top voted answer, updated for C# 8. Following can be used out of the box. Added explicit System.Drawing before Image as one might be using that class from other namespace defaultly.
public static string ImagePathToBase64(string path)
{
using System.Drawing.Image image = System.Drawing.Image.FromFile(path);
using MemoryStream m = new MemoryStream();
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
tring base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
The following piece of code works for me:
string image_path="physical path of your image";
byte[] byes_array = System.IO.File.ReadAllBytes(Server.MapPath(image_path));
string base64String = Convert.ToBase64String(byes_array);
The reverse of this for the googlers arriving here (there is no SO quesion/answer to that)
public static byte[] BytesFromBase64ImageString(string imageData)
{
var trunc = imageData.Split(',')[1];
var padded = trunc.PadRight(trunc.Length + (4 - trunc.Length % 4) % 4, '=');
return Convert.FromBase64String(padded);
}
Something like that
Function imgTo64(ByVal thePath As String) As String
Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(thePath)
Dim m As IO.MemoryStream = New IO.MemoryStream()
img.Save(m, img.RawFormat)
Dim imageBytes As Byte() = m.ToArray
img.Dispose()
Dim str64 = Convert.ToBase64String(imageBytes)
Return str64
End Function

Xamarin: Upload image to server

I need upload image to server using api.
Now I'm using System.Net.Http;
byte[] lFileBytes= DependencyService.Get<IFileHelper>().ReadAllBytes(ImagePath);
ByteArrayContent lFileContent = new ByteArrayContent(lFileBytes,0,lFileBytes.Length);
lFileContent.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse("form-data");
lFileContent.Headers.ContentType=new MediaTypeHeaderValue("image/jpg");
lFileContent.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("name","file"));
lFileContent.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("filename", "9.jpg"));
lFileContent.Headers.ContentLength= lFileBytes.Length;
lContent.Add(lFileContent);
public byte[] ReadAllBytes(string path) {
using (var streamReader = new StreamReader(path))
{
using (var memoryStream = new MemoryStream())
{
streamReader.BaseStream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
}
After sending request i have error Type file is invalid
I'm thinking problem in byte[] ReadAllBytes(string path)
For request i can use Stream or byte[]
Please, help
UPDATE
lRequestResponse = await lHttpClient.PostAsync("URL", lContent);
In case you still need, this works for me:
var cont = new MultipartFormDataContent();
var image = new StreamContent(img.Image.GetStream());
cont.Add(image, "\"file\"", img.FileName);
var uri = App.apiurl + $"FileUpload/" + img.FileName + "/";
using (var client = new HttpClient())
{
var response = await client.PostAsync(uri, cont);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
// return error code
}
}
This help me
MultipartFormDataContent lContent=new MultipartFormDataContent();
byte[] lBytes = DependencyService.Get<IFileHelper>().ReadAllBytes(filename);
ByteArrayContent lFileContent= new ByteArrayContent(lBytes);
lFileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = filename,
Name = "imgFile"
};
lFileContent.Headers.ContentType = new MediaTypeHeaderValue("image/png");
lContent.Add(lFileContent);
HttpResponseMessage lRequestResponse=await lHttpClient.PostAsync(await url, lContent);
IFileHelper implement on IOS
namespace Client.iOS
{
public class FileHelper : IFileHelper
{
private string GetLocalFilePath(string filename)
{
string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string libFolder = Path.Combine(docFolder, "..", "images", "Databases");
if (!Directory.Exists(libFolder))
{
Directory.CreateDirectory(libFolder);
}
return Path.Combine(libFolder, filename);
}
public byte[] ReadAllBytes(string filename)
{
string path=GetLocalFilePath(filename);
return (FileStream(path) as MemoryStream).ToArray();
}
private Stream FileStream(string path)
{
StreamReader lStreamReader = new StreamReader(path);
MemoryStream lMemoryStream = new MemoryStream();
lMemoryStream.Position = 0;
lStreamReader.BaseStream.CopyTo(lMemoryStream);
return lMemoryStream;
}
}
}

Bing Maps CustomMapTileDataSource wont load pixelData

I am writing a UWP application using the MapControl I have implemented my own MapTileSource like so:
var nativeTileLayer = new MapTileSource();
nativeTileLayer.DataSource = new UWPSyncTileLayer();
nativeTileLayer.TilePixelSize = outerItem.TileSize;
nativeTileLayer.AllowOverstretch = true;
// NativeMap.Style = MapStyle.None;
outerItem.NativeObject = nativeTileLayer;
NativeMap.TileSources.Clear();
NativeMap.TileSources.Add(nativeTileLayer);
return nativeTileLayer;
Where UWPSyncTileLayer is my own implementation of CustomMapTileDataSource
internal class UWPSyncTileLayer : CustomMapTileDataSource
{
public UWPSyncTileLayer(int tileSize = 256)
{
this.BitmapRequested += UWPSyncTileLayer_BitmapRequested;
}
private void UWPSyncTileLayer_BitmapRequested(CustomMapTileDataSource sender, MapTileBitmapRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
var data = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAASQUlEQVR42u3dfZBeVX3A8W921+263W7jNk1pmomZqJmYiTHS8GKIaUSLNFIa0SJSYZRBy5Si0lZbHOgMwx8MoxQp06LT0oigtKLgtIIKyjvyJuHFQCCEgCRACHlZlnWTbLKb/nHOSoBN2Ow+z73n3Pv9zJxJhpnwPM+5v/O755x77jmTkPLSGct0YDZwUPzvPwUetXqkamkD5gGnACuAh4CXgD2vKXdaVeOrXCk1HcB84M+BY4FZQNcb/JvpVpuUr5bYpf8y8MAod/g3KuutQinPhr8AuBrYNo6GbwKQMh1+LgauBXZNoOGbAKTM7vhLgOuA7Q1o+CPlSatWStuceMcfamDDHykPWb1SmtqBzwHPN6Hhj5SbrWYpve7+4cA9TWz4I+Uqq/vAuQ5AzbzrnwecBnQX8HmbrXITg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MbCuork4hnNa8hTwX+VyNj/r0GlNiTyCXSasLY6PvKKm+WgiPzP4WuCs2rNTrbSfwzyXWmRLXQjjd9fkEg3cLcC3hCUZHgvU2H7gIeCrRZPA4sAyX92oM5sVxdAqBuxr4MmHPwxyCdwph26xbgV2J3PUvAQ4yrHUgOmIgP1HCGPVFwtOJo8h3Br4tJtILYh0WnQy2Az8DFnnX10TvaGfT/PcIdsa75mcJLy9VSTdh3cW3af7OzbsIO/gchZvBqIF6gNMIs+47G3Sn3xYb/ZfihFp7xeuwJdbjCbGHs75BdbkzjvEviL0OG/4oXAfQuKHBIuDD8S4z5wACboDw/Plu4E7CTjPralyX3cACwlqMQ2Ljnc4bT3L2E06IfjTO1ayMZcDwNAEUqTMG7FzCJN1oG0cOE46SepqwTdlWDmxRTl20xPrrJEzYTYsJonOvRt8X63JTrMMBPCJ+zP4fl44XyBRTFr4AAAAASUVORK5CYII=".Split(",".ToCharArray(), 2)[1]);
MemoryStream stream = new MemoryStream();
stream.Write(data, 0, data.Length);
stream.Position = 0;
var decoder = Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream.AsRandomAccessStream()).AsTask().Result;
var pixelProvider = decoder.GetPixelDataAsync().AsTask().Result;// Windows.Graphics.Imaging.BitmapPixelFormat.Rgba8, Windows.Graphics.Imaging.BitmapAlphaMode.Ignore, new Windows.Graphics.Imaging.BitmapTransform(), Windows.Graphics.Imaging.ExifOrientationMode.RespectExifOrientation, Windows.Graphics.Imaging.ColorManagementMode.ColorManageToSRgb).AsTask().Result;
var pixelData = pixelProvider.DetachPixelData();
InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
IOutputStream outputStream = randomAccessStream.GetOutputStreamAt(0);
DataWriter writer = new DataWriter(outputStream);
writer.WriteBytes(pixelData);
var i = writer.StoreAsync().AsTask().Result;
var d = writer.FlushAsync().AsTask().Result;
args.Request.PixelData = RandomAccessStreamReference.CreateFromStream(randomAccessStream);
deferral.Complete();
}
}
But the image is always blank.
Does anyone know what I'm doing wrong?
I can't tell from your data stream, but it looks like you might be passing a compressed PNG stream to the PixelData property. You'll need to decode a PNG to RGB values and set PixelData to the decoded RGBA buffer. See the example code here:https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.maps.maptilebitmaprequest.pixeldata.aspx

Xamarin forms signature pad Get image

Im using the following code to get the signature from the signature pad, But any value doesn't come.
try {
var signature = padView.GetImage (Acr.XamForms.SignaturePad.ImageFormatType.Png);
using (BinaryReader br = new BinaryReader (signature)) {
var result = br.ReadBytes ((int)signature.Length);
}
} catch (Exception ex) {
// Helper_ErrorHandling.SendErrorToServer (ex);
}
Am I ding it wrong, Also how do i convert this to a base64 string
?
I'm not too familiar with the Xamarin Forms Signature Pad, but if you're looking for a way to convert a Stream to as base64 string, try this:
[...]
string base64String;
using (var memoryStream = new MemoryStream())
{
signature.CopyTo( memoryStream );
var byteArray = memoryStream.ToArray();
base64String = Convert.ToBase64String( byteArray );
}
EDIT: you can most of the time skip the copy, if you check if signature is already a MemoryStream...
[...]
string base64String;
var signatureMemoryStream = signature as MemoryStream;
if (signatureMemoryStream == null)
{
signatureMemoryStream = new MemoryStream();
signature.CopyTo( signatureMemoryStream );
}
var byteArray = signatureMemoryStream.ToArray();
base64String = Convert.ToBase64String( byteArray );
Using the most current PCL compliant Xamarin package :
acr-xamarin-forms
This method works like a charm!
private string ConvertSignatureToBase64()
{
try
{
byte[] data;
if(Device.OS == TargetPlatform.iOS)
{
var img = SignaturePad.GetImage(Acr.XamForms.SignaturePad.ImageFormatType.Jpg);
var signatureMemoryStream = new MemoryStream();
img.CopyTo(signatureMemoryStream);
data = signatureMemoryStream.ToArray();
}
else
{
var img = SignaturePad.GetImage(Acr.XamForms.SignaturePad.ImageFormatType.Jpg);
var signatureMemoryStream = (MemoryStream)img;
data = signatureMemoryStream.ToArray();
}
return Convert.ToBase64String(data);
}
catch(Exception ex)
{
return ex.ToString();
}
}

OpenPGP encryption with BouncyCastle

I have been trying to put together an in-memory public-key encryption infrastructure using OpenPGP via Bouncy Castle. One of our vendors uses OpenPGP public key encryption to encrypt all their feeds, and requires us to do the same, so I'm stuck with the technology and the implementation. So now I'm coding an OpenPGP encryption/ decryption toolkit for automating these feeds.
The examples at bouncycastle.org inexplicably default to writing encrypted data to and collecting keys from a file system; this is not what I want to do, so I've been trying to get everything stream-based.
I have gotten to the point where I can actually get my code to compile and run, but my encrypted payload is empty. I think I'm missing something silly, but after several days of trying this and that, I have lost the ability to objectively examine this.
My utility class contains these methods:
public static PgpPublicKey ImportPublicKey(
this Stream publicIn)
{
var pubRings =
new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicIn)).GetKeyRings().OfType<PgpPublicKeyRing>();
var pubKeys = pubRings.SelectMany(x => x.GetPublicKeys().OfType<PgpPublicKey>());
var pubKey = pubKeys.FirstOrDefault();
return pubKey;
}
public static Stream Streamify(this string theString, Encoding encoding = null)
{
encoding = encoding ?? Encoding.UTF8;
var stream = new MemoryStream(encoding.GetBytes(theString));
return stream;
}
public static string Stringify(this Stream theStream,
Encoding encoding = null)
{
encoding = encoding ?? Encoding.UTF8;
using (var reader = new StreamReader(theStream, encoding))
{
return reader.ReadToEnd();
}
}
public static byte[] ReadFully(this Stream stream)
{
if (!stream.CanRead) throw new ArgumentException("This is not a readable stream.");
var buffer = new byte[32768];
using (var ms = new MemoryStream())
{
while (true)
{
var read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public static void PgpEncrypt(
this Stream toEncrypt,
Stream outStream,
PgpPublicKey encryptionKey,
bool armor = true,
bool verify = true,
CompressionAlgorithmTag compressionAlgorithm = CompressionAlgorithmTag.Zip)
{
if (armor) outStream = new ArmoredOutputStream(outStream);
var compressor = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
outStream = compressor.Open(outStream);
var data = toEncrypt.ReadFully();
var encryptor = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, verify, new SecureRandom());
encryptor.AddMethod(encryptionKey);
outStream = encryptor.Open(outStream, data.Length);
outStream.Write(data, 0, data.Length);
}
My test method looks like this:
private static void EncryptMessage()
{
var pubKey = #"<public key text>";
var clearText = "This is an encrypted message. There are many like it but this one is cryptic.";
using (var stream = pubKey.Streamify())
{
var key = stream.ImportPublicKey();
using (var clearStream = clearText.Streamify())
using (var cryptoStream = new MemoryStream())
{
clearStream.PgpEncrypt(cryptoStream,key);
cryptoStream.Position = 0;
Console.WriteLine(cryptoStream.Stringify());
Console.WriteLine("Press any key to continue.");
}
}
Console.ReadKey();
}
The result I get looks like this:
-----BEGIN PGP MESSAGE-----
Version: BCPG C# v1.7.4114.6378
Press any key to continue.
Can someone tell me what I am doing wrong?
OK, I managed to get this working. There were several problems with this implementation. One problem was that certain things had to be done in order. Here is what seems to need to happen:
The raw data needs to be put into a PgpLiteralData object
The literal data needs to be encrypted.
The encrypted data needs to be compressed.
The compressed data (optionally) needs to be armored.
The underlying streams need to be closed in order of usage.
There should be a more elegant way to do this, but the streams used by the BouncyCastle library are all frustratingly one-way, and at several points, I needed to convert the stream to a byte array to get another part to work. I include the code I used and independently verified; if someone has a verifyably better way of doing this, I would be quite interested.
public static class OpenPgpUtility
{
public static void ExportKeyPair(
Stream secretOut,
Stream publicOut,
AsymmetricKeyParameter publicKey,
AsymmetricKeyParameter privateKey,
string identity,
char[] passPhrase,
bool armor)
{
if (armor)
{
secretOut = new ArmoredOutputStream(secretOut);
}
var secretKey = new PgpSecretKey(
PgpSignature.DefaultCertification,
PublicKeyAlgorithmTag.RsaGeneral,
publicKey,
privateKey,
DateTime.UtcNow,
identity,
SymmetricKeyAlgorithmTag.Cast5,
passPhrase,
null,
null,
new SecureRandom()
);
secretKey.Encode(secretOut);
if (armor)
{
secretOut.Close();
publicOut = new ArmoredOutputStream(publicOut);
}
var key = secretKey.PublicKey;
key.Encode(publicOut);
if (armor)
{
publicOut.Close();
}
}
public static PgpPublicKey ImportPublicKey(
this Stream publicIn)
{
var pubRings =
new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicIn)).GetKeyRings().OfType<PgpPublicKeyRing>();
var pubKeys = pubRings.SelectMany(x => x.GetPublicKeys().OfType<PgpPublicKey>());
var pubKey = pubKeys.FirstOrDefault();
return pubKey;
}
public static PgpSecretKey ImportSecretKey(
this Stream secretIn)
{
var secRings =
new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(secretIn)).GetKeyRings().OfType<PgpSecretKeyRing>();
var secKeys = secRings.SelectMany(x => x.GetSecretKeys().OfType<PgpSecretKey>());
var secKey = secKeys.FirstOrDefault();
return secKey;
}
public static Stream Streamify(this string theString, Encoding encoding = null)
{
encoding = encoding ?? Encoding.UTF8;
var stream = new MemoryStream(encoding.GetBytes(theString));
return stream;
}
public static string Stringify(this Stream theStream,
Encoding encoding = null)
{
encoding = encoding ?? Encoding.UTF8;
using (var reader = new StreamReader(theStream, encoding))
{
return reader.ReadToEnd();
}
}
public static byte[] ReadFully(this Stream stream, int position = 0)
{
if (!stream.CanRead) throw new ArgumentException("This is not a readable stream.");
if (stream.CanSeek) stream.Position = 0;
var buffer = new byte[32768];
using (var ms = new MemoryStream())
{
while (true)
{
var read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public static void PgpEncrypt(
this Stream toEncrypt,
Stream outStream,
PgpPublicKey encryptionKey,
bool armor = true,
bool verify = false,
CompressionAlgorithmTag compressionAlgorithm = CompressionAlgorithmTag.Zip)
{
var encryptor = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, verify, new SecureRandom());
var literalizer = new PgpLiteralDataGenerator();
var compressor = new PgpCompressedDataGenerator(compressionAlgorithm);
encryptor.AddMethod(encryptionKey);
//it would be nice if these streams were read/write, and supported seeking. Since they are not,
//we need to shunt the data to a read/write stream so that we can control the flow of data as
//we go.
using (var stream = new MemoryStream()) // this is the read/write stream
using (var armoredStream = armor ? new ArmoredOutputStream(stream) : stream as Stream)
using (var compressedStream = compressor.Open(armoredStream))
{
//data is encrypted first, then compressed, but because of the one-way nature of these streams,
//other "interim" streams are required. The raw data is encapsulated in a "Literal" PGP object.
var rawData = toEncrypt.ReadFully();
var buffer = new byte[1024];
using (var literalOut = new MemoryStream())
using (var literalStream = literalizer.Open(literalOut, 'b', "STREAM", DateTime.UtcNow, buffer))
{
literalStream.Write(rawData, 0, rawData.Length);
literalStream.Close();
var literalData = literalOut.ReadFully();
//The literal data object is then encrypted, which flows into the compressing stream and
//(optionally) into the ASCII armoring stream.
using (var encryptedStream = encryptor.Open(compressedStream, literalData.Length))
{
encryptedStream.Write(literalData, 0, literalData.Length);
encryptedStream.Close();
compressedStream.Close();
armoredStream.Close();
//the stream processes are now complete, and our read/write stream is now populated with
//encrypted data. Convert the stream to a byte array and write to the out stream.
stream.Position = 0;
var data = stream.ReadFully();
outStream.Write(data, 0, data.Length);
}
}
}
}
}
My test method looked like this:
private static void EncryptMessage()
{
var pubKey = #"<public key text here>";
var clearText = #"<message text here>";
using (var stream = pubKey.Streamify())
{
var key = stream.ImportPublicKey();
using (var clearStream = clearText.Streamify())
using (var cryptoStream = new MemoryStream())
{
clearStream.PgpEncrypt(cryptoStream, key);
cryptoStream.Position = 0;
var cryptoString = cryptoStream.Stringify();
Console.WriteLine(cryptoString);
Console.WriteLine("Press any key to continue.");
}
}
Console.ReadKey();
}
Since someone asked, my decryption algorithm looked like this:
public static Stream PgpDecrypt(
this Stream encryptedData,
string armoredPrivateKey,
string privateKeyPassword,
Encoding armorEncoding = null)
{
armorEncoding = armorEncoding ?? Encoding.UTF8;
var stream = PgpUtilities.GetDecoderStream(encryptedData);
var layeredStreams = new List<Stream> { stream }; //this is to clean up/ dispose of any layered streams.
var dataObjectFactory = new PgpObjectFactory(stream);
var dataObject = dataObjectFactory.NextPgpObject();
Dictionary<long, PgpSecretKey> secretKeys;
using (var privateKeyStream = armoredPrivateKey.Streamify(armorEncoding))
{
var secRings =
new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)).GetKeyRings()
.OfType<PgpSecretKeyRing>();
var pgpSecretKeyRings = secRings as PgpSecretKeyRing[] ?? secRings.ToArray();
if (!pgpSecretKeyRings.Any()) throw new ArgumentException("No secret keys found.");
secretKeys = pgpSecretKeyRings.SelectMany(x => x.GetSecretKeys().OfType<PgpSecretKey>())
.ToDictionary(key => key.KeyId, value => value);
}
while (!(dataObject is PgpLiteralData) && dataObject != null)
{
try
{
var compressedData = dataObject as PgpCompressedData;
var listedData = dataObject as PgpEncryptedDataList;
//strip away the compression stream
if (compressedData != null)
{
stream = compressedData.GetDataStream();
layeredStreams.Add(stream);
dataObjectFactory = new PgpObjectFactory(stream);
}
//strip the PgpEncryptedDataList
if (listedData != null)
{
var encryptedDataList = listedData.GetEncryptedDataObjects()
.OfType<PgpPublicKeyEncryptedData>().First();
var decryptionKey = secretKeys[encryptedDataList.KeyId]
.ExtractPrivateKey(privateKeyPassword.ToCharArray());
stream = encryptedDataList.GetDataStream(decryptionKey);
layeredStreams.Add(stream);
dataObjectFactory = new PgpObjectFactory(stream);
}
dataObject = dataObjectFactory.NextPgpObject();
}
catch (Exception ex)
{
//Log exception here.
throw new PgpException("Failed to strip encapsulating streams.", ex);
}
}
foreach (var layeredStream in layeredStreams)
{
layeredStream.Close();
layeredStream.Dispose();
}
if (dataObject == null) return null;
var literalData = (PgpLiteralData)dataObject;
var ms = new MemoryStream();
using (var clearData = literalData.GetInputStream())
{
Streams.PipeAll(clearData, ms);
}
ms.Position = 0;
return ms;
}

Categories

Resources