Converting text using Base64 in Linux and Windows - windows

I need to encrypt text/files in base 64 so I can send them in an email (I can't do attachments). I can use openSSL and GPG in Linux to encrypt and decrypt but don't know how to do the same in Windows XP. Does anyone know a program that can do this for me in windows?

EDITED AGAIN
In this link you can find how to encode/decode files.
I attach sample code:
private string FileToBase64(string srcFilename)
{
if (!string.IsNullOrEmpty(srcFilename))
{
FileStream fs = new FileStream(srcFilename,
FileMode.Open,
FileAccess.Read);
byte[] filebytes = new byte[fs.Length];
fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
string encodedData = Convert.ToBase64String(filebytes,
Base64FormattingOptions.InsertLineBreaks);
return encodedData;
}
}
private void Base64ToFile(string src, string dstFilename)
{
if (!string.IsNullOrEmpty(dstFilename))
{
byte[] filebytes = Convert.FromBase64String(src);
FileStream fs = new FileStream(dstFilename,
FileMode.CreateNew,
FileAccess.Write,
FileShare.None);
fs.Write(filebytes, 0, filebytes.Length);
fs.Close();
}
}

Related

Xamrin UWP Release causes weird NullReferenceException (System.Security.Cryptography.PasswordDeriveBytes)

public static class CryptoHelper {
// This size of the IV (in bytes) must = (keysize / 8). Default keysize is 256, so the IV must be
// 32 bytes long. Using a 16 character string here gives us 32 bytes when converted to a byte array.
private const string initVector = "pemgail9uzpgzl88";
// This constant is used to determine the keysize of the encryption algorithm
private static int keysize = 256;
private static int getKeySize()
{
return 256;
}
//Encrypt
//public static byte[] EncryptString( string plainText, string passPhrase ) {
public static byte[] EncryptString(string toEncrypt, string salt)
{
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(toEncrypt);
byte[] keyBytes = new byte[126];
try
{
PasswordDeriveBytes password = new PasswordDeriveBytes(Encoding.UTF8.GetBytes(salt), null);
Debug.WriteLine(CryptoHelper.getKeySize());
Debug.WriteLine(password.ToString());
keyBytes = password.GetBytes(256 / 8);
} catch (Exception e)
{
Debug.WriteLine(e.StackTrace);
}
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return cipherTextBytes;
}
........
The call to "password.GetBytes(256 / 8);" results in a non catchable NullReferenceException
This happens only when the UWP App is in Release mode; UWP Debug as well as Andorid and IOS are fine.
Also I get a weird Debug Message:
"this._hash" war "null".
or
"this._hash" was "null". (translated)
Here you can see it in action
VS2019 Screenshot
To repuduce this issue the inputs for the function are:
toEncrypt "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwiZXhwIjoxNjE3MDAyMTEyfQ.C0CaGgfibM4z55MoANI2CiohUyew09r3_D_TpcQ6n1c8LmQd8BusSyF1SMEIQ3cO5uxE9Tnau0ZAT6D3kN3NcQ"
salt
"9x83m74tzrx9387x4mz98374zt90x8m273z948734z59"
Cause I cant see the detailed cause of this problem there it is basilcy not possible to get a workaround for this.
I was trying to make the same code work. The solution I found was to replace:
PasswordDeriveBytes password = new PasswordDeriveBytes(Encoding.UTF8.GetBytes(salt), null);
with:
Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(passPhrase, Encoding.UTF8.GetBytes("12345678"));
and also add this:
symmetricKey.Padding = PaddingMode.Zeros;

download files from ftp to local drive

In FTP Sub Folder contains some csv files want to download into local drive folder within one csv file.
In FTP each csv file contains only one record.So,Now i want get all 5 records into localdrive folder in one csv file.Here is code works only for one csv file.
private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath)
{
//FileStream responseStream =null;
int Length = 2048;
Byte[] buffer = new Byte[Length];
// int bytesRead = responseStream.Read(buffer, 0, Length);
int bytesRead = 0;
FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, false);
request.Method = WebRequestMethods.Ftp.DownloadFile;
Stream reader = request.GetResponse().GetResponseStream();
FileStream fileStream = new FileStream(localDestinationFilePath, FileMode.Create);
while (true )
{
bytesRead = reader.Read(buffer,0,buffer.Length);
if (bytesRead == 0)
break;
fileStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
}
private FtpWebRequest CreateFtpWebRequest(string ftpDirectoryPath, string userName, string password, bool keepAlive)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ftpDirectoryPath));
//Set proxy to null. Under current configuration if this option is not set then the proxy that is used will get an html response from the web content gateway (firewall monitoring system)
request.Proxy = null;
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = keepAlive;
request.Credentials = new NetworkCredential(userName, password);
return request;
}
private void button1_Click(object sender, EventArgs e)
{
DownloadFile("Username1", "Password1", "ftp://172.32.1.252:5010/Test/CBRE/building.csv", "C://Workspace/ex.csv");
}
I dont understand exactly what you are trying to do, but you can try this wat too:
WebClient Client = new WebClient ();
Client.DownloadFile(http://www.domain.com/files/yourfile.ext, " yourfile.ext");
WebClientClass

how to save a variable include image into isolate storage in windowsphone

i've been doing a essay about windowsphone. i created a address variable include a uri to add a image into address. There is a error when i use Isolate storage to save data. I don't know why.
Please help me!
Thank you so much.
class Address
{
private string name;
private Uri icon;
.....
}
......
public void save()
{
XmlWriterSettings xmlwritersetting = new XmlWriterSettings();
xmlwritersetting.Indent = true;
using (IsolatedStorageFile myisolatedstiragefile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myisolatedstiragefile.FileExists(filename))
{
myisolatedstiragefile.DeleteFile(filename);
}
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filename, System.IO.FileMode.OpenOrCreate, myisolatedstiragefile))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Adress>));
using (XmlWriter writer = XmlWriter.Create(stream, xmlwritersetting))
{
serializer.Serialize(writer, listadress);
}
}
}
}
It's a little difficult for me to understand your question, but I'll try. You really should indicate what error you specifically get in the debugger and where it occurs.
But just by looking, it seems that you might be trying to use the XmlSerializer to write binary image data to iso-storage and that probably won't work. You can find many examples of using iso-storage for various purposes including writing image files here:
http://www.windowsphonegeek.com/tips/All-about-WP7-Isolated-Storage---Read-and-Save-Images
For example, it shows that you can save a JPG image to isolated storage by doing this:
// Create a filename for JPEG file in isolated storage.
String tempJPEG = "logo.jpg";
// Create virtual store and file stream. Check for duplicate tempJPEG files.
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) {
if (myIsolatedStorage.FileExists(tempJPEG)) {
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
StreamResourceInfo sri = null;
Uri uri = new Uri(tempJPEG, UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85); fileStream.Close();
}

How to save and read a byte[] into a IsolatedStorageFile

i know how to save a string into the IsolatedStorageFile but what about a byte[] ?
for a string i do:
string enc = "myString";
using (var iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = iso.OpenFile("fileName", FileMode.Create))
{
var writer = new StreamWriter(stream);
writer.Write(enc);
writer.Close();
}
}
EDIT: okay i know now how to write, but how to read out the byte[] again?
Use BinaryWriter instead of StreamWriter.
To write a byte array, instead of enclosing your stream in a StreamWriter, use directly stream.Write. Or use a BinaryWriter.
For instance:
stream.Write(byteArray, 0, byteArray.Length);

How to save data in xml file in windows phone 7

Hello Everyone,
I am working on an application in which i need to save some data in IsolatedStorage .
while my application is running i am able to see data from file. Once i close my application and restarting my application its not showing my data.
public static IsolatedStorageFile isstore = IsolatedStorageFile.GetUserStoreForApplication();
public static IsolatedStorageFileStream xyzStrorageFileStream = new IsolatedStorageFileStream("/category.xml", System.IO.FileMode.OpenOrCreate, isstore);
public static XDocument xmldoc = XDocument.Load("category.xml");
favouriteDoc.Save(rssFavouriteFileStream);
rssFavouriteFileStream.Flush();
Any one having any idea? How to do this?
In order to save structured data you need to use XML Writer or XML Serializer.
For example to save data:
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("People2.xml", FileMode.Create, myIsolatedStorage))
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
{
writer.WriteStartElement("p", "person", "urn:person");
writer.WriteStartElement("FirstName", "");
writer.WriteString("Kate");
writer.WriteEndElement();
writer.WriteStartElement("LastName", "");
writer.WriteString("Brown");
writer.WriteEndElement();
writer.WriteStartElement("Age", "");
writer.WriteString("25");
writer.WriteEndElement();
// Ends the document
writer.WriteEndDocument();
// Write the XML to the file.
writer.Flush();
}
}
}
To read it back:
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("People2.xml", FileMode.Open);
using (StreamReader reader = new StreamReader(isoFileStream))
{
this.tbx.Text = reader.ReadToEnd();
}
}
}
catch
{ }
Answer is taken from this article, so all the credits go to WindowsPhoneGeek. Also, see other examples in the aforementioned article header.

Resources