Hello I have been exploring new tool that provides us Visual Studio 2015 that is Xamarin, I have already implemented an application on Android but I am currently translating it into C # for my application is platform, I have no idea how to perform encryption, I found the example below you'll stick but only encrypt and decrypt, also enclose the code that have already implemented in Java, I hope someone can support me because I get many errors.
loggedUser = null;
sharedPreferences = getSharedPreferences(AppConstants.PREFERENCES_FILE_NAME, MODE_PRIVATE);
if (sharedPreferences.getAll().isEmpty()) {
Intent loginActivityIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginActivityIntent);
finishAffinity();
}
String loggedUserUsername = sharedPreferences.getString(AppConstants.LOGIN_CREDENTIAL_USERNAME_KEY, "");
if (loggedUserUsername.isEmpty()) {
Intent loginActivityIntent = new Intent(MainActivity.this, LoginActivity.class);
loginActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginActivityIntent);
finishAffinity();
} else {
File filesDirectory = new File(getFilesDir().getPath());
for (File file: filesDirectory.listFiles()) {
if (file.getName().contains(loggedUserUsername) && file.getName().contains(AppConstants.USER_INFO_FILE_SUFFIX)) {
String deviceId;
String deviceKey;
byte[] secretBytes;
byte[] ivBytes;
FileInputStream fileInputStream = null;
CipherInputStream cipherInputStream = null;
ObjectInputStream objectInputStream = null;
try {
deviceId = sharedPreferences.getString(AppConstants.LOGIN_CREDENTIAL_DEVICE_ID_KEY, "").replace("-", "");
deviceKey = sharedPreferences.getString(AppConstants.LOGIN_CREDENTIAL_DEVICE_KEY_KEY, "").replace("-", "");
secretBytes = deviceKey.substring(0, 16).getBytes();
ivBytes = deviceId.substring(deviceId.length() - 16, deviceId.length()).getBytes();
fileInputStream = openFileInput(file.getName());
final SecretKey secretKey = new SecretKeySpec(secretBytes, "AES");
final IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
cipherInputStream = new CipherInputStream(fileInputStream, cipher);
objectInputStream = new ObjectInputStream(cipherInputStream);
loggedUser = new User((String)objectInputStream.readObject());
} catch (ClassNotFoundException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IOException | JSONException e) {
if (AppConstants.DEBUG) Log.e(TAG, AppConstants.EXCEPTION_CAUGHT_MESSAGE + e.getMessage(), e);
loggedUser = null;
} finally {
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
if (AppConstants.DEBUG) Log.e(TAG, AppConstants.EXCEPTION_CAUGHT_MESSAGE + e.getMessage(), e);
}
} else {
if (AppConstants.DEBUG) Log.e(TAG, "objectOutputStream:null");
}
if (cipherInputStream != null) {
try {
cipherInputStream.close();
} catch (IOException e) {
if (AppConstants.DEBUG) Log.e(TAG, AppConstants.EXCEPTION_CAUGHT_MESSAGE + e.getMessage(), e);
}
} else {
if (AppConstants.DEBUG) Log.e(TAG, "cipherOutputStream:null");
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
if (AppConstants.DEBUG) Log.e(TAG, AppConstants.EXCEPTION_CAUGHT_MESSAGE + e.getMessage(), e);
}
} else {
if (AppConstants.DEBUG) Log.e(TAG, "fileOutputStream:null");
}
}
break;
}
}
}
Here code C#
base.OnCreate(savedInstanceState);
loggedUser = null;
sharedPreferences = GetSharedPreferences(AppConstants.PREFERENCES_FILE_NAME, MODE_PRIVATE);
if (sharedPreferences.All.Count == 0)
{
Intent loginActivityIntent = new Intent(MainActivity.this, LoginActivity.Class);
loginActivityIntent.SetFlags(ActivityFlags.ClearTop);
StartActivity(loginActivityIntent);
FinishAffinity();
}
else
{
Java.IO.File filesDirectory = new Java.IO.File(FilesDir.Path);
foreach (Java.IO.File file in filesDirectory.ListFiles())
{
if (file.Name.Contains(loggedUser) && file.Name.Contains(AppConstants.USER_INFO_FILE_SUFFIX))
{
string deviceId;
string deviceKey;
byte[] secretBytes;
byte[] ivBytes;
FileInputStream fileInputStream = null;
CipherInputStream cipherInputStream = null;
ObjectInputStream objectInputStream = null;
try
{
deviceId = sharedPreferences.GetString(AppConstants.LOGIN_CREDENTIAL_DEVICE_ID_KEY, "").Replace("-","");
deviceId = sharedPreferences.GetString(AppConstants.LOGIN_CREDENTIAL_DEVICE_KEY_KEY, "").Replace("-", "");
secretBytes = System.Text.Encoding.UTF8.GetBytes(deviceId.Substring(0, 16));
ivBytes = System.Text.Encoding.UTF8.GetBytes(deviceId.Substring(deviceId.Length - 16, deviceId.Length));
Stream fileStream = OpenFileInput(file.Name);
SecretKeySpec secretKeySpec = new SecretKeySpec(secretBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(secretBytes);
Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding");
cipher.Init(CipherMode.DecryptMode, secretKeySpec, ivSpec);
cipherInputStream = new CipherInputStream(fileStream,cipher);
objectInputStream = new ObjectInputStream(cipherInputStream); <- In this parte i have a error because not is possible to convert CipherInputStream to Stream
And this is the link with the example
Encryption and Decryption Support in .NET and Android
You could use a 3rd party library like PCL Crypto. It is also available as NuGet package.
Related
How do I decode DER-formatted detached signature using BouncyCastle bc-sharp? For PEM-formatted signature I do it like this:
public static bool VerifyDetachedSignature(byte[] fileRawBytes, string sign)
{
try
{
var signatureFileRawBytes = Convert.FromBase64String(sign);
var cms = new CmsSignedData(new CmsProcessableByteArray(fileRawBytes), signatureFileRawBytes);
var signers = cms.GetSignerInfos();
var certificates = cms.GetCertificates("Collection");
var signerInfos = signers.GetSigners();
foreach (SignerInformation info in signerInfos)
{
var certList = new ArrayList(certificates.GetMatches(info.SignerID));
var cert = (X509Certificate)certList[0];
if (cert == null) throw new NullReferenceException();
var publicKey = cert.GetPublicKey();
info.Verify(publicKey);
}
return true;
}
catch (Exception exception)
{
return false;
}
}
On rare ocasions I need to verify DER-formatted signature. It appears I just need to covert string to byte array, like this:
public static bool VerifyDetachedSignature(byte[] fileRawBytes, string sign)
{
try
{
byte[] signatureFileRawBytes;
try
{
signatureFileRawBytes = Convert.FromBase64String(sign);
}
catch (FormatException)
{
signatureFileRawBytes = Encoding.ASCII.GetBytes(sign);
}
var cms = new CmsSignedData(new CmsProcessableByteArray(fileRawBytes), signatureFileRawBytes);
var signers = cms.GetSignerInfos();
var certificates = cms.GetCertificates("Collection");
var signerInfos = signers.GetSigners();
foreach (SignerInformation info in signerInfos)
{
var certList = new ArrayList(certificates.GetMatches(info.SignerID));
var cert = (X509Certificate)certList[0];
if (cert == null) throw new NullReferenceException();
var publicKey = cert.GetPublicKey();
info.Verify(publicKey);
}
return true;
}
catch (Exception exception)
{
return false;
}
}
In this case I get an exception on that line:
var cms = new CmsSignedData(new CmsProcessableByteArray(fileRawBytes), signatureFileRawBytes);
Org.BouncyCastle.Cms.CmsException
HResult=0x80131500
Message=IOException reading content.
Source=BouncyCastle
StackTrace:
at Org.BouncyCastle.Cms.CmsUtilities.ReadContentInfo(Asn1InputStream aIn)
at Org.BouncyCastle.Cms.CmsUtilities.ReadContentInfo(Stream input)
at Org.BouncyCastle.Cms.CmsSignedData..ctor(CmsProcessable signedContent, Byte[] sigBlock)
at backend.Helpers.CryptoHelper.VerifyDetachedSignature(Byte[] fileRawBytes, String sign) in C:\Projects\[...]\Helpers\CryptoHelper.cs:line 107
This exception was originally thrown at this call stack:
[External Code]
Inner Exception 1:
EndOfStreamException: DEF length 63 object truncated by 2
Any thoughts or suggestions on how to decode DER-signature?
It turned out the problem was not related to BouncyCastle. The problem was that I read binary data to a string variable and lose data. When i passed signature as byte array to VerifyDetachedSignature(byte[] fileRawBytes, byte[] sign) method it worked perfectly like this:
public static bool VerifyDetachedSignature(byte[] fileRawBytes, byte[] sign)
{
try
{
CmsSignedData cms;
try
{
cms = new CmsSignedData(new CmsProcessableByteArray(fileRawBytes), sign);
}
catch (CmsException)
{
var strSign = System.Text.Encoding.ASCII.GetString(sign);
var decodedSignRawBytes = Convert.FromBase64String(strSign);
cms = new CmsSignedData(new CmsProcessableByteArray(fileRawBytes), decodedSignRawBytes);
}
var signers = cms.GetSignerInfos();
var certificates = cms.GetCertificates("Collection");
var signerInfos = signers.GetSigners();
foreach (SignerInformation info in signerInfos)
{
var certList = new ArrayList(certificates.GetMatches(info.SignerID));
var cert = (X509Certificate)certList[0];
if (cert == null) throw new NullReferenceException();
var publicKey = cert.GetPublicKey();
info.Verify(publicKey);
}
return true;
}
catch (Exception)
{
return false;
}
}
Hope this helps someone to not make the same mistake.
I am trying to send/receive byte array of image from server to server.
I think i managed to send it but am unable to receive it.
Here is code for sending:
[HttpPost]
[Route("/ARGallery/AUploadImage/{appid}")]
public IActionResult AUploadImage(IFormFile file, int appid)
{
try
{
// Korisnik prosledjuje fajl kroz browser
// Taj fajl ima svoje ime
// Bezbednosti radi proveravam ime fajla i prilagodjavam ga
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
filename = this.EnsureCorrectFilename(filename);
//===============
// Uzimam app model iz buffera
ApplicationsModel am = Buffer.GetApplication(appid);
// Proveravam da li je uspesno uzet model, ako nije uzimam direktno iz faljova
if (am == null)
am = ApplicationsModel.List().Where(a => a.ID == appid).FirstOrDefault();
// Ako je posle svega neuspesno vracam gresku
if (am == null)
return View("Error", "Error loading application info!");
byte[] imageInBytes = null;
System.Drawing.Image img = System.Drawing.Image.FromStream(file.OpenReadStream());
using (var ms = new MemoryStream())
{
img.Save(ms, img.RawFormat);
imageInBytes = ms.ToArray();
}
using(var client = new WebClient())
{
return Json(client.UploadString("http://" + am.Name + "/ARGallery/AUploadImage/" + file.FileName, System.Text.Encoding.UTF8.GetString(imageInBytes)));
}
}
catch (Exception ex)
{
return Json(ex.ToString());
}
}
and here is receiving code
[HttpPost]
[Route("/ARGallery/AUploadImage/{filename}")]
public IActionResult AUploadImage(string bufferedImage, string filename)
{
try
{
MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(bufferedImage));
System.Drawing.Image myimg = Image.FromStream(ms);
while(System.IO.File.Exists(GetPathAndFilename(filename)))
{
string extension = "";
int br = filename.ToString().IndexOf('.');
string ex = filename.ToString().Substring(br);
if (ex == "jpeg")
extension = filename.Substring(filename.Length - 5, 5);
else
extension = filename.Substring(filename.Length - 4, 4);
// Dodajem na ostatak fajl name-a bez extensiona random karaktere i vracam extension nazad
filename = filename.Substring(0, filename.Length - 4) + AR.Security.HashPW(Program.rnd.Next(1000).ToString()).Substring(0, 2) + extension;
}
//Cuvam original format slike u temp folder
myimg.Save(GetPathAndFilename(filename));
// Cuvam osiromaseni format slike u temp folder
LowerQuality((Bitmap)myimg).Save(GetPathAndFilenameLQ(filename));
// Vracam nazad link do slike na remote serveru (serveru aplikacije)
return Json(filename);
}
catch (Exception ex)
{
return Json(ex.ToString());
}
}
I get "null" exception on line MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(bufferedImage));
EDIT:
Also what i have tried on sending app side is this but still same problem:
[HttpPost]
[Route("/ARGallery/AUploadImage/{appid}")]
public async Task<IActionResult> AUploadImage(IFormFile file, int appid)
{
try
{
// Korisnik prosledjuje fajl kroz browser
// Taj fajl ima svoje ime
// Bezbednosti radi proveravam ime fajla i prilagodjavam ga
string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
filename = this.EnsureCorrectFilename(filename);
//===============
// Uzimam app model iz buffera
ApplicationsModel am = Buffer.GetApplication(appid);
// Proveravam da li je uspesno uzet model, ako nije uzimam direktno iz faljova
if (am == null)
am = ApplicationsModel.List().Where(a => a.ID == appid).FirstOrDefault();
// Ako je posle svega neuspesno vracam gresku
if (am == null)
return View("Error", "Error loading application info!");
byte[] imageInBytes = null;
System.Drawing.Image img = System.Drawing.Image.FromStream(file.OpenReadStream());
using (var ms = new MemoryStream())
{
img.Save(ms, img.RawFormat);
imageInBytes = ms.ToArray();
}
using(var client = new HttpClient())
{
var options = new
{
bufferedImage = System.Text.Encoding.UTF8.GetString(imageInBytes),
filename = file.FileName
};
HttpResponseMessage message = await client.PostAsync("http://" + am.Name + "/ARGallery/AUploadImage", new StringContent(JsonConvert.SerializeObject(options), Encoding.UTF8, "application/json"));
return Json(await message.Content.ReadAsStringAsync());
}
}
catch (Exception ex)
{
return Json(ex.ToString());
}
}
I have a Print function which calls by different forms in my Project. Previously I was using DataSet as on my parameter, Now I switched to Data model. I am not sure how to retrieve information from different data model each time. Here is my old code.
public static void Print(string templeteID, DataSet dsSource,bool bPreview)
{
try
{
TPX.HMI.BusinessLogic.SystemSetting.ReportTemplate bll = new TPX.HMI.BusinessLogic.SystemSetting.ReportTemplate();
DataSet dsTemp = bll.RetrieveReportTemplateByID(templeteID);
if (dsTemp.Tables[0].Rows.Count > 0)
{
FileStream fs = new FileStream(Application.StartupPath + #"\\temp.repx", FileMode.Create);
Byte[] aryFile = dsTemp.Tables[0].Rows[0]["TemplateFile"] as Byte[];
fs.Write(aryFile, 0, aryFile.Length);
fs.Close();
}
string reportPatch = Application.StartupPath + #"\\temp.repx";
//开始打印
if (!System.IO.File.Exists(reportPatch))
{
MessageBox.Show(TPX.LanguageHelper.GetSystemKeyValue(GlobalParameters.Language, "TPX_TF_HMI_Print_TemplateError"));
return;
}
System.IO.FileStream stream = new System.IO.FileStream(reportPatch, System.IO.FileMode.Open);
XtraReport mReport = DevExpress.XtraReports.UI.XtraReport.FromStream(stream, true);
stream.Close();
if (dsSource != null) //传入数据集
{
mReport.DataSource = dsSource;
mReport.DataMember = dsSource.Tables[dsSource.Tables.Count - 1].TableName;
}
mReport.Name = "TPX";
mReport.RequestParameters = false;
mReport.PrintingSystem.ShowPrintStatusDialog = false;
mReport.PrintingSystem.ShowMarginsWarning = false;
if (!string.IsNullOrEmpty(GlobalParameters.DefaultPrinter))
mReport.PrintingSystem.PageSettings.PrinterName = GlobalParameters.DefaultPrinter;
mReport.CreateDocument();
if (bPreview)
mReport.ShowPreviewDialog();
else
mReport.Print();
}
catch (Exception ex)
{
MessageBox.Show((TPX.LanguageHelper.GetSystemKeyValue(GlobalParameters.Language, "TPX_TF_HMI_Print_TemplatePrintEx")) + ex.Message);
}
}
in c#
public static string HashToString(string message, byte[] key)
{
byte[] b=new HMACSHA512(key).ComputeHash(Encoding.UTF8.GetBytes(message));
return Convert.ToBase64String(b);
}
client.DefaultRequestHeaders.Add("X-Hash", hash);
var encryptedContent = DataMotion.Security.Encrypt(key, Convert.FromBase64String(iv), serializedModel);
var request = client.PostAsync(ApiUrlTextBox.Text,encryptedContent,new JsonMediaTypeFormatter());
in java:
protected String hashToString(String serializedModel, byte[] key) {
String result = null;
Mac sha512_HMAC;
try {
sha512_HMAC = Mac.getInstance("HmacSHA512");
SecretKeySpec secretkey = new SecretKeySpec(key, "HmacSHA512");
sha512_HMAC.init(secretkey);
byte[] mac_data = sha512_HMAC.doFinal(serializedModel.getBytes("UTF-8"));
result = Base64.encodeBase64String(mac_data);
}catch(Exception e){
}
}
o/p: ye+AZPqaKrU14pui4U5gBCiAbegNvLVjzVdGK3rwG9QVzqKfIgyWBDTncORkNND3DA8jPba5xmC7B5OUwZEKlQ==
i have written hashtostring method in java based on c# code. is this currect? (output is different because every time process is dynamic in both cases.)
With different C# encoding
public static string SHA512_ComputeHash(string text, string secretKey)
{
var hash = new StringBuilder(); ;
byte[] secretkeyBytes = Encoding.UTF8.GetBytes(secretKey);
byte[] inputBytes = Encoding.UTF8.GetBytes(text);
using (var hmac = new HMACSHA512(secretkeyBytes))
{
byte[] hashValue = hmac.ComputeHash(inputBytes);
foreach (var theByte in hashValue)
{
hash.Append(theByte.ToString("x2"));
}
}
return hash.ToString();
}
Both java and C# code are giving same result(same hash code). You should check again.
Replace following line in java code at end
result = Base64.getEncoder().encodeToString(mac_data);
In c#
public static string HMACSHA512(this string Key, string TextToHash)
{
string HmacHashed = "";
if (string.IsNullOrEmpty(Key))
throw new ArgumentNullException("HMACSHA512: Key", "Parameter cannot be empty.");
if (string.IsNullOrEmpty(TextToHash))
throw new ArgumentNullException("HMACSHA512: TextToHash", "Parameter cannot be empty.");
if (Key.Length % 2 != 0 || Key.Trim().Length < 2)
{
throw new ArgumentNullException("HMACSHA512: Key", "Parameter cannot be odd or less than 2 characters.");
}
try
{
using (var HMACSHA512 = new HMACSHA512(Encoding.ASCII.GetBytes(Key)))
{
HmacHashed = BitConverter.ToString(HMACSHA512.ComputeHash(Encoding.ASCII.GetBytes(TextToHash))).Replace("-", string.Empty);
}
return HmacHashed;
}
catch (Exception ex)
{
throw new Exception("HMACSHA512: " + ex.Message);
}
}
public static void ListFolders()
{
HomeFolderListing = new List<string>();
ReportingServiceSoapClient rs = new ReportingServiceSoapClient();
rs.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
CatalogItem[] HomeFolders = null;
string reportPath = "/";
rs.ListChildren(reportPath, true, out HomeFolders);
foreach (var homeF in HomeFolders)
{
if (homeF.Name.ToString().ToLower().Contains("base"))
{
if (homeF.Path.ToString().ToLower().Contains("/data sources/"))
{
}
else
{
Console.WriteLine("Adding reporting folder: " + homeF.Name.ToString());
HomeFolderListing.Add(homeF.Path.ToString());
}
}
}
}
public static void PublishReport()
{
foreach (string HomeFold in HomeFolderListing)
{
ReportingServiceSoapClient rs = new ReportingServiceSoapClient();
rs.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
BatchHeader bh = new BatchHeader();
string batchID = null;
rs.CreateBatch(out batchID);
bh.BatchID = batchID;
Byte[] definition = null;
Warning[] warnings = null;
try
{
FileStream stream = File.OpenRead(ReportInformation.Report2Deploy);
definition = new Byte[stream.Length];
stream.Read(definition, 0, (int)stream.Length);
stream.Close();
}
catch (Exception ex)
{
}
try
{
string filename = ReportInformation.ReportDeployNameOnly;
Console.WriteLine("Deploying Report: " + filename + " to: " + HomeFold);
rs.CreateReport(bh, filename, HomeFold, true, definition, null, out warnings);
if (warnings != null)
{
foreach (Warning warning in warnings)
{
Console.WriteLine(warning.Message);
}
}
else
Console.WriteLine("Report: {0} created successfully with no warnings", filename);
}
catch (Exception ex)
{
}
}
}
when i execute rs.CreateReport() it comes back as if it was successful with no warning, however, when i view the server it just isn't there. And yes I've looking in all the folders.
Are you sure there is no error? There's an empty catch block. The documenation says to catch a SoapException. Try this in the catch:
catch (SoapException e)
{
//Do something with the error, sample code write to console
Console.WriteLine(e.Detail.InnerXml.ToString());
}
Taken from:
http://msdn.microsoft.com/en-us/library/aa225813(v=sql.80).aspx