how to convert android.util.Base64.encodeToString to C# - c#

import android.util.Base64;
public static String Base64(String str) {
byte[] data = new byte[0];
data = str.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, 0);
return base64;
}
it is a android method to convert base64
public string Base64(string str)
{
byte[] data = new byte[0];
data = System.Text.Encoding.UTF8.GetBytes(str);
string base64 = Convert.ToBase64String(data);
return base64;
}
it is c# method
but both output are different
what can i do for same output??

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

c# base64 encoding. Invalid length error on decrpytion

I'm trying to decrypt a string which is also base64 encoded, but I am receiving an when I try to decrypt the string.
The error I am receiving is:
{System.FormatException: Invalid length for a Base-64 char array or string.
at this line in the decrypt function below:
MemoryStream ms = new MemoryStream(Convert.FromBase64String(inString));
Encrpyt/Decrypt functions:
//ENCRYPT
public static bool stringEncrypt(string inString,ref string outstring)
{
try
{
if(String.IsNullOrEmpty(inString)){return false;}
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms,provider.CreateEncryptor(PWbytes,PWbytes),CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cs);
sw.Write(inString);
sw.Flush();
cs.FlushFinalBlock();
sw.Flush();
outstring = Convert.ToBase64String(ms.GetBuffer(),0,(int)ms.Length);
return true;
}
catch(Exception ex)
{
clsCommonBase.AppendToExceptionFile("Encrypt : " + ex.Message);
return false;
}
}
//DECRPYT
public static bool stringDecrypt(string inString,ref string outstring)
{
try
{
if(String.IsNullOrEmpty(inString)){return false;};
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(Convert.FromBase64String(inString));
CryptoStream cs = new CryptoStream(ms, provider.CreateDecryptor(PWbytes,PWbytes),CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
outstring = sr.ReadToEnd();
return true;
}
catch(Exception ex)
{
clsCommonBase.AppendToExceptionFile("Decrypt : " + ex.Message);
return false;
}
}
Solved using the simple solution in the following link
How do I encode and decode a base64 string?
Also added some code in the encoding function to ensure the plain text string will be converted to a valid length base64 string.
Code:
public static string Base64Encode(string plainText)
{
//check plain text string and pad if needed
int mod4 = plainText.Length % 4;
if (mod4 > 0)
{
plainText += new string('=', 4 - mod4);
}
//convert to base64 and return
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64EncodedData)
{
//decode base64 and return as string
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

SHA384 PHP code translate to C#

I have some issues translating this PHP code into C#:
$hash = hash('sha384', $string_to_hash, true);
$base64Hash = strtr(base64_encode($hash), '+/', '-_');
Could you please help me?
Thanks!
Edit: I am updating this post with the whole PHP code to translate to C# because I can't get the same hashed Token with both Languages
$host = "100.200.100.200";
$url= "http://".$host.":1935/";
$stream = "vod/_definst_/test.smil";
$start = time();
$end = strtotime("+30 minutes");
$secret = "abcde";
$tokenName = "wowzatoken";
$hash = hash('sha384', $stream."?".$secret."&{$tokenName}endtime=".$end."&{$tokenName}starttime=".$start, true);
$base64Hash = strtr(base64_encode($hash), '+/', '-_');
$params = array("{$tokenName}starttime=".$start, "{$tokenName}endtime=".$end, "{$tokenName}hash=".$base64Hash);
$playbackURL = $url.$stream."/playlist.m3u8?";
foreach($params as $entry){
$playbackURL.= $entry."&";
}
$playbackURL = preg_replace("/(\&)$/","", $playbackURL);
echo $playbackURL;
I am not good at PHP, So I am not sure about strtr function. But I have tried to resolve your issue and give the some code below. try it.
class Program
{
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
public static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static void Main(string[] args)
{
string code = "SecretCode";
byte[] data = new byte[code.Length];
byte[] result;
data = GetBytes(code);
SHA384 shaM = new SHA384Managed();
result = shaM.ComputeHash(data);
string encodedString = GetString(result);
string ans = Base64Encode(encodedString);
ans = ans.Replace('+','-').Replace('/','_');
Console.Write(ans);
Console.Read();
}
}

base64 encode HttpPostedFileBase

I want to base64 encode an image that is being received as HttpPostedFileBase to send it in a json object and I don't know how it can be done...and please tell me how can I decode it back to HttpPostedFileBase
I tried this and it worked
string theFileName = Path.GetFileName(YourFile.FileName);
byte[] thePictureAsBytes = new byte[YourFile.ContentLength];
using (BinaryReader theReader = new BinaryReader(YourFile.InputStream))
{
thePictureAsBytes = theReader.ReadBytes(YourFile.ContentLength);
}
string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes);
Follow the below steps to convert the HttpPostedFileBase to Base64String type
public ActionResult ParseCv(HttpPostedFileBase cvFile)
{
byte[] fileInBytes = new byte[cvFile.ContentLength];
using (BinaryReader theReader = new BinaryReader(cvFile.InputStream))
{
fileInBytes = theReader.ReadBytes(cvFile.ContentLength);
}
string fileAsString= Convert.ToBase64String(fileInBytes);
return Content(fileAsString);
}
You can do this:
byte[] binaryData;
binaryData = new Byte[product.BrochureFile.InputStream.Length];
long bytesRead = product.BrochureFile.InputStream.Read(binaryData, 0, (int)product.BrochureFile.InputStream.Length);
product.BrochureFile.InputStream.Close();
string base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);

How can I SHA512 a string in C#?

I am trying to write a function to take a string and sha512 it like so?
public string SHA512(string input)
{
string hash;
~magic~
return hash;
}
What should the magic be?
Your code is correct, but you should dispose of the SHA512Managed instance:
using (SHA512 shaM = new SHA512Managed())
{
hash = shaM.ComputeHash(data);
}
512 bits are 64 bytes.
To convert a string to a byte array, you need to specify an encoding. UTF8 is okay if you want to create a hash code:
var data = Encoding.UTF8.GetBytes("text");
using (...
This is from one of my projects:
public static string SHA512(string input)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(input);
using (var hash = System.Security.Cryptography.SHA512.Create())
{
var hashedInputBytes = hash.ComputeHash(bytes);
// Convert to text
// StringBuilder Capacity is 128, because 512 bits / 8 bits in byte * 2 symbols for byte
var hashedInputStringBuilder = new System.Text.StringBuilder(128);
foreach (var b in hashedInputBytes)
hashedInputStringBuilder.Append(b.ToString("X2"));
return hashedInputStringBuilder.ToString();
}
}
Please, note:
SHA512 object is disposed ('using' section), so we do not have any resource leaks.
StringBuilder is used for efficient hex string building.
512/8 = 64, so 64 is indeed the correct size. Perhaps you want to convert it to hexadecimal after the SHA512 algorithm.
See also: How do you convert Byte Array to Hexadecimal String, and vice versa?
You might try these lines:
public static string GenSHA512(string s, bool l = false)
{
string r = "";
try
{
byte[] d = Encoding.UTF8.GetBytes(s);
using (SHA512 a = new SHA512Managed())
{
byte[] h = a.ComputeHash(d);
r = BitConverter.ToString(h).Replace("-", "");
}
r = (l ? r.ToLowerInvariant() : r);
}
catch
{
}
return r;
}
It is disposed at the end
It's safe
Supports lower case
Instead of WinCrypt-API using System.Security.Cryptography, you can also use BouncyCastle:
public static byte[] SHA512(string text)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(text);
Org.BouncyCastle.Crypto.Digests.Sha512Digest digester = new Org.BouncyCastle.Crypto.Digests.Sha512Digest();
byte[] retValue = new byte[digester.GetDigestSize()];
digester.BlockUpdate(bytes, 0, bytes.Length);
digester.DoFinal(retValue, 0);
return retValue;
}
If you need the HMAC-version (to add authentication to the hash)
public static byte[] HmacSha512(string text, string key)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
var hmac = new Org.BouncyCastle.Crypto.Macs.HMac(new Org.BouncyCastle.Crypto.Digests.Sha512Digest());
hmac.Init(new Org.BouncyCastle.Crypto.Parameters.KeyParameter(System.Text.Encoding.UTF8.GetBytes(key)));
byte[] result = new byte[hmac.GetMacSize()];
hmac.BlockUpdate(bytes, 0, bytes.Length);
hmac.DoFinal(result, 0);
return result;
}
Keeping it simple:
using (SHA512 sha512 = new SHA512Managed())
{
password = Encoding.UTF8.GetString(sha512.ComputeHash(Encoding.UTF8.GetBytes(password)));
}
I'm not sure why you are expecting 128.
8 bits in a byte. 64 bytes. 8 * 64 = 512 bit hash.
From the MSDN Documentation:
The hash size for the SHA512Managed algorithm is 512 bits.
You could use the System.Security.Cryptography.SHA512 class
MSDN on SHA512
Here is an example, straigt from the MSDN
byte[] data = new byte[DATA_SIZE];
byte[] result;
SHA512 shaM = new SHA512Managed();
result = shaM.ComputeHash(data);
UnicodeEncoding UE = new UnicodeEncoding();
byte[] message = UE.GetBytes(password);
SHA512Managed hashString = new SHA512Managed();
string hexNumber = "";
byte[] hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hexNumber += String.Format("{0:x2}", x);
}
string hashData = hexNumber;
I used the following
public static string ToSha512(this string inputString)
{
if (string.IsNullOrWhiteSpace(inputString)) return string.Empty;
using (SHA512 shaM = new SHA512Managed())
{
return Convert.ToBase64String(shaM.ComputeHash(Encoding.UTF8.GetBytes(inputString)));
}
}
Made it into an extension method in my ExtensionUtility.cs class
public static string SHA512(this string plainText)
{
using (SHA512 shaM = new SHA512Managed())
{
var buffer = Encoding.UTF8.GetBytes(plainText);
var hashedInputBytes = shaM.ComputeHash(buffer);
return BitConverter.ToString(hashedInputBytes).Replace("-", "");
}
}

Categories

Resources