Openssl-aes-256-cbc encryption in iOS - encryption

I am working on Encryption,Decryption in swift OpenSSl AES-256-CBC. I have checked with many third- party libraries or pods i.e. CryptoSwift and many others. But I am always getting HMAc is Not valid from Php back end team.
Where as in android they have done this:
Following is my android method:
public EncryptedData encrypt(Object data) throws Exception {
String text;
if (data instanceof String) {
text = String.valueOf(data);
} else {
text = (new Gson()).toJson(data);
}
if (!this.doAction) {
return new EncryptedData(text, "");
} else {
this.ivspec = new IvParameterSpec(this.getIV1().getBytes());
this.keyspec = new SecretKeySpec(this.getKey1().getBytes(), "AES");
if (text != null && text.length() != 0) {
byte[] encrypted;
try {
this.cipher.init(Cipher.ENCRYPT_MODE, this.keyspec, this.ivspec);
encrypted = this.cipher.doFinal(this.padString(text).getBytes());
} catch (Exception var5) {
throw new Exception("[encrypt] " + var5.getMessage());
}
String encryptedData = new String(Base64.encode(encrypted, Base64.DEFAULT))
.replace("\n", "");
SecretKeySpec macKey = new SecretKeySpec(getKey1().getBytes(), "HmacSHA256");
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
hmacSha256.init(macKey);
hmacSha256.update((Base64.encodeToString(getIV1().getBytes(), Base64.DEFAULT).trim() + encryptedData.trim()).getBytes());
byte[] calcMac = hmacSha256.doFinal();
return new EncryptedData(encryptedData, bytesToHex(calcMac));
} else {
throw new Exception("Empty string");
}
}
}
Any one know how this will works in iOS.
Any help will be appreciated.
Thanks

Here is a simple HMAC implement in Swift 4:
0xa6a/HMAC
No third-party library is needed. Just create a bridging header and import <CommonCrypto/CommonCrypto.h> in it.
Have a try and happy coding.

Related

vulnerability from security team in forget password controller in asp .net

I have a controller form application and the security team they said there is a vulnerability you can put any user_id fom postman inside the controller like this
ForgotPassword/user_id
how I can remove this vulnerability check the code below:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult ForgotPassword(string emailId)
{
var helper = new Helper.Helper();
List<SqlParameter> args = new List<SqlParameter>();
args.Add(new SqlParameter("#Pin_email_id", emailId));
var req_resp = new Dictionary<string, object>();
try
{
using (DataSet dataset = helper.ExecuteSqlQuery("Web_Forgot_Password", args))
{
if (dataset != null && dataset.Tables.Count > 0 && dataset.Tables[0].Rows.Count > 0)
{
if (dataset.Tables[0].Rows[0]["Status"].ToString() == "Success")
{
req_resp["status"] = true;
req_resp["message"] = dataset.Tables[0].Rows[0]["Description"].ToString();
req_resp["code"] = dataset.Tables[0].Rows[0]["Code"].ToString();
string password = dataset.Tables[0].Rows[0]["user_password"].ToString();
SendForgotMail(emailId, dataset.Tables[0].Rows[0]["user_name"].ToString(), helper.Decrypt(password), dataset.Tables[0].Rows[0]["employee"].ToString());
return Json(req_resp);
}
else
{
req_resp["status"] = false;
req_resp["message"] = dataset.Tables[0].Rows[0]["Description"].ToString();
req_resp["code"] = dataset.Tables[0].Rows[0]["Code"].ToString();
return Json(req_resp);
}
}
else
{
req_resp["status"] = false;
req_resp["message"] = "Request Failed";
req_resp["code"] = "1005";
return Json(req_resp);
}
}
}
catch
{
var response = new
{
status = false,
message = "Request failed",
code = "1005"
};
return Json(response);
}
}
Well normally you store only password hashes in your database, which are not decryptable. Watching helper.Decrypt(password) in your code and sending the original password as a plain text in email is something painful. Normally I would just send a password reset link which can be used only once.
I checked the SqlParemater docs, it is added as a String value the way you use it, so it is not SQL injectable. Without the exact SQL I cannot tell much. I think they meant that it is SQL injectable, but then they should send evidence at least.

Retrieving Image from Chooser Intent in Android 10

I'm trying to update my app to work with androids new scoped storage rules in Android 10 and up, but am having the hardest time with it. I know I need to rebuild my app with new versions of java, but I just want to get it to work while I study and learn enough to do so. In a nutshell, I really need help. I have read so many different ways to make scoped storage work, and everybody seems to be doing it differently.
Just for clarification, what I am trying to do with the uri is both display in an imageview, then upload to database.
This code is working to take a picture and select images and videos in android 9, but in android 10, it only works when camera component captures a picture or a video. When a user selects an image or video from file, it returns a null pointer exception. Because I am pretty sure the error is in how I am dealing with the different chooser intents, I have shown the on result code first.
I have been unable to find a clear example of how to retrieve a usable image or video uri in android 10. If anybody can help, I would really appreciate it. I know I have much to learn.
if ((new java.io.File(_filePath)).exists()){
} else {
_filePath = vidfile.getAbsolutePath();
if ((new java.io.File(_filePath)).exists()){
} else {
ArrayList<String> _filePath_1 = new ArrayList<>();
if (_data != null) {
if (_data.getClipData() != null) {
for (int _index = 0; _index < _data.getClipData().getItemCount(); _index++) {
ClipData.Item _item = _data.getClipData().getItemAt(_index);
_filePath_1.add(FileUtil.convertUriToFilePath(getApplicationContext(),
_item.getUri()));
}
}
else {
_filePath_1.add(FileUtil.convertUriToFilePath(getApplicationContext(),
_data.getData()));
}
}
_filePath = _filePath_1.get((int)0);
}
}
Just in case I am wrong, here is the code for the click event to launch the chooser...
SimpleDateFormat date1 = new SimpleDateFormat("yyyyMMdd_HHmmss");
String fileName1 = date1.format(new Date()) + ".jpg";
picfile = new
File(getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DCIM).getAbsolutePath() +
File.separator + fileName1);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri _uri_camr1 = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
_uri_camr1 = FileProvider.getUriForFile(getApplicationContext(),
getApplicationContext().getPackageName() + ".provider", picfile);
}
else {
_uri_camr1 = Uri.fromFile(picfile);
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, _uri_camr1);
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
SimpleDateFormat date2 = new SimpleDateFormat("yyyyMMdd_HHmmss");
String fileName2 = date2.format(new Date()) + ".mp4";
vidfile = new
File(getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DCIM).getAbsolutePath() +
File.separator + fileName2);
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
Uri _uri_camr2 = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
_uri_camr2 = FileProvider.getUriForFile(getApplicationContext(),
getApplicationContext().getPackageName() + ".provider", vidfile);
}
else {
_uri_camr2 = Uri.fromFile(vidfile);
}
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, _uri_camr2);
takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
contentSelectionIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent[] intentArray = new Intent[]{ takePictureIntent, takeVideoIntent};
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Choose an action");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, REQ_CD_CAMR);
try this code. it copies the selected file to scoped storage and gives you the final path of scoped storage from where you can access it. try it out & let me know if you face any problem.
android.net.Uri sharedFileUri = android.net.Uri.fromFile(new java.io.File(_filepath));
java.io.FileInputStream input = null;
java.io.FileOutputStream output = null;
try {
String filePath = new java.io.File(getCacheDir(), "tmp").getAbsolutePath();
android.os.ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(sharedFileUri, "rw");
if (pfd != null) {
java.io.FileDescriptor fd = pfd.getFileDescriptor();
input = new java.io.FileInputStream (fd);
output = new java.io.FileOutputStream (filePath);
int read;
byte[] bytes = new byte[4096];
while ((read = input.read(bytes)) != -1) {
output.write(bytes, 0, read);
}
java.io.File sharedFile = new java.io.File(filePath);
String finalPath = sharedFile.getPath(); // this will provide you path to scoped storage. use this final path to access the selected file from scoped storage.
}
}catch(Exception ex) {
android.widget.Toast.makeText(this, ex.toString(), android.widget.Toast.LENGTH_SHORT).show();
} finally {
try {
input.close();
output.close();
} catch (Exception ignored) {
}
}

Crystal report method not found

I made a feedback project. I made it on ASP.NET MVC 5 it also has crystal reports. reports were working fine, but suddenly they stopped to work. I don't what happened with them. but since last week I tried hard to find solution but unfortunately could not get the right one who solved the solution. I downloaded different run times but all went vain. this is the bottom line of error.
"Method not found: 'CrystalDecisions.ReportAppServer.DataDefModel.PropertyBag CrystalDecisions.ReportAppServer.ReportDefModel.ISCRExportOptions.get_ExportOptionsEx()'"
this is the code:
public CrystalReportFeedback UserFeedbackDateWise(FeedbackReport be){
if (Session["CurrentUser"] != null && Convert.ToInt32(Session["User_Id"]) != 0)
{
string reportPath = Path.Combine(Server.MapPath("~/Reports"), "UserFeedbackReport.rpt");
if (ModelState.IsValid)
{
be.FromDate = Convert.ToDateTime(TempData["UserFromDate"]);
be.ToDate = Convert.ToDateTime(TempData["UserToDate"]);
be.User_Id = Convert.ToInt32(Session["User_Id"]);
}
return new CrystalReportFeedback(reportPath, be);
}
else
{
return null;
//new CrystalReportFeedback(reportPath, be);
}
}
Init of the report :
public CrystalReportFeedback(string reportPath, FeedbackReport be)//, object dataSet)
{
//int[] array;
string strConnect = Convert.ToString(System.Configuration.ConfigurationManager.ConnectionStrings["TSC"]);
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(strConnect);
string _username = builder.UserID;
string _pass = builder.Password;
string _server = builder.DataSource;
string _database = builder.InitialCatalog;
ReportDocument reportDocument = new ReportDocument();
//
reportDocument.Load(reportPath);
reportDocument.SetDatabaseLogon(_username, _pass, _server, _database);
if (be.Region_Id != 0)
{
reportDocument.SetParameterValue("#Region_Id", be.Region_Id);
}
if (be.User_Id != 0)
{
reportDocument.SetParameterValue("#User_Id", be.User_Id);
}
reportDocument.SetParameterValue("#FromDate", be.FromDate);
reportDocument.SetParameterValue("#ToDate", be.ToDate);
//reportDocument.ExportToDisk(ExportFormatType.PortableDocFormat, "C:\report.pdf");
_contentBytes = StreamToBytes(reportDocument.ExportToStream(ExportFormatType.PortableDocFormat));
}
Export method :
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.ApplicationInstance.Response;
response.Clear();
response.Buffer = false;
response.ClearContent();
response.ClearHeaders();
response.Cache.SetCacheability(HttpCacheability.Public);
response.ContentType = "application/pdf";
using (var stream = new MemoryStream(_contentBytes))
{
stream.WriteTo(response.OutputStream);
stream.Flush();
}
}
private static byte[] StreamToBytes(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
Hope that I will get my solution at earliest.
this is modified code:
[HttpGet]
public FileResult UserFeedbackDateWise(FeedbackReport be)
{
if (Session["CurrentUser"] != null && Convert.ToInt32(Session["User_Id"]) != 0)
{
string reportPath = Path.Combine(Server.MapPath("~/Reports"), "UserFeedbackReport.rpt");
if (ModelState.IsValid)
{
be.FromDate = Convert.ToDateTime(TempData["UserFromDate"]);
be.ToDate = Convert.ToDateTime(TempData["UserToDate"]);
be.User_Id = Convert.ToInt32(Session["User_Id"]);
}
string strConnect = Convert.ToString(System.Configuration.ConfigurationManager.ConnectionStrings["TSC"]);
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(strConnect);
string _username = builder.UserID;
string _pass = builder.Password;
string _server = builder.DataSource;
string _database = builder.InitialCatalog;
ReportDocument reportDocument = new ReportDocument();
//
reportDocument.Load(reportPath);
reportDocument.SetDatabaseLogon(_username, _pass, _server, _database);
if (be.Region_Id != 0)
{
reportDocument.SetParameterValue("#Region_Id", be.Region_Id);
}
if (be.User_Id != 0)
{
reportDocument.SetParameterValue("#User_Id", be.User_Id);
}
reportDocument.SetParameterValue("#FromDate", be.FromDate);
reportDocument.SetParameterValue("#ToDate", be.ToDate);
Stream stream = reportDocument.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
//Here i have my stream with my pdf report, i just create a new FileStreamResult and return it to my client like that :
FileStreamResult myfile = new FileStreamResult(stream, "application/pdf");
return myfile;
//new CrystalReportFeedback(reportPath, be);
}
else
{
return null;
//new CrystalReportFeedback(reportPath, be);
}
}
This isn't a coding issue, it's a runtime issue. The version of the crystal runtime or the bitness of your application.
One thing to try first is to upgrade both your development version and ensure you're running the same version in production. See https://apps.support.sap.com/sap/support/knowledge/public/en/2148492 for more details
It says:
Compile your application either to 'X86 mode' or 'X64 mode'
Install the particular versions of runtimes on deployment machine.
i.e. If the application is compiled as 32 bit, then install the 32bit runtimes.
I'll try my best to help you exporting your report, but your post is not very clear. For your next post try to be very specific and provide as much information as you can.
I currently made a MVC project and export a crystalreport report from my controller to my client.
I think that your ExecuteResult method can work, but working with the httpcontext is useless, Crystalreport and .NET provide some useful methods to do the same.
So i'll show you how i create and export my report so you can copy / paste and modify your code.
Here is my controller method, called from a button :
[HttpGet]
public FileResult InitReport()
{
//I create my report here
FileImportReport rptH = new FileImportReport();
// Some configuration on the report, datasource, databaselogon .. etc
...
//
//Then I export my report to a pdf stream like that :
Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
//Here i have my stream with my pdf report, i just create a new FileStreamResult and return it to my client like that :
FileStreamResult myfile = new FileStreamResult(stream, "application/pdf");
return myfile;
}
My method is called from a button but it can work like you want, or the file can be saved in any known path.
You can test to reproduce my code, in your CrystalReportFeedback method use my code with your reportDocument object, you don't need to use your StreamToBytes method.
Regards,
EDIT : Useful links with your error :
Crystal Reports exception in Visual Studio 2013
https://www.arcanadev.com/support/kb/K00000499.aspx

Check Httpconnection is open or not in blackberry

Before making HttpConnection from blackberry application i want to check if it is open or not?. Because without checking that when i tried to make a connection i got class net.rim.device.api.io.ConnectionClosedException.
EDIT: Posted the code from the OP's answer.
Below is my code for the http connection.
public String makePostRequest(String[] paramName, String[] paramValue) {
StringBuffer postData = new StringBuffer();
HttpConnection connection = null;
InputStream inputStream = null;
OutputStream out = null;
try {
connection = (HttpConnection) Connector.open(this.url);
connection.setRequestMethod(HttpConnection.POST);
for (int i = 0; i < paramName.length; i++) {
postData.append(paramName[i]);
postData.append("=");
postData.append(paramValue[i]);
postData.append("&");
}
String encodedData = postData.toString();
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", (new Integer(
encodedData.length())).toString());
connection.setRequestProperty("Cookie", Constants.COOKIE_TOKEN);
byte[] postDataByte = postData.toString().getBytes("UTF-8");
out = connection.openOutputStream();
out.write(postDataByte);
DebugScreen.Log("Output stream..."+out);
DebugScreen.Log("Output stream..."+connection.getResponseCode());
// get the response from the input stream..
inputStream = connection.openInputStream();
DebugScreen.Log("Input stream..."+inputStream);
byte[] data = IOUtilities.streamToBytes(inputStream);
response = new String(data);
} catch ( Exception e) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
WaitingScreen.removePopUP();
Status.show(Constants.CONNETION_ERROR);
}
});
DebugScreen.Log("Exception inside the make connection..makePostRequest."
+ e.getMessage());
DebugScreen.Log("Exception inside the make connection..makePostRequest."
+ e.getClass());
}finally {
try {
if(inputStream != null){
inputStream.close();
inputStream = null;
}
if(out != null){
out.close();
out = null;
}
if(connection != null){
connection.close();
connection = null;
}
} catch ( Exception ex) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
WaitingScreen.removePopUP();
}
});
DebugScreen.Log("Exception from the connection2 class.."
+ ex.getMessage());
DebugScreen.Log("Exception from the connection2 class.."
+ ex.getClass());
}
}
return response;
}
Before making httpconnection from blackberry application i want to check if it is open or not.
That doesn't make sense. You want to make sure it is open before you open it. You can't. You have to try to open it, and handle the exception if it fails. That's what the exception is for.
The best way to test whether any resource is available is to try to use it. You can't predict that. You have to try it.
Because without checking that when i tried to make a connection i got class net.rim.device.api.io.ConnectionClosedException.
So it wasn't available. So now you know. That's the correct behaviour. You're already doing the right thing. There is no question here to answer.

Blackberry HttpConnection failure on device

I'm after some BlackBerry suggestions again. I'm developing a REST based app using the standard BB code that appends to the URI connection string (I'll post if you like but don't want to take up space here as I suspect that those of you that know about this know exactly what I mean).
The code works fine in the emulator in MDS mode and is good on the phone too with straight WiFi.
Now, the problem is when I come to use 3G on an actual phone. At that point it fails. Is this some kind of transcoding problem?
I'm using a raw HttpConnection.
An HTTP POST works (with body info) but the GET (which uses a cookie for auth purposes as a header requestproperty) fails.
The failure is only with header (GET) based info on non WiFi connections on the mobile device.
Any suggestions would be most appreciated.
public static String httpGet(Hashtable params, String uriIn) {
String result = null;
LoginDetails loginDetails = LoginDetails.getInstance();
HttpConnection _connection;
String uri = uriIn + "?api_key=" + loginDetails.getApi_key();
Enumeration e = params.keys();
// iterate through Hashtable keys Enumeration
while (e.hasMoreElements()) {
String key = (String) (e.nextElement());
String value = (String) params.get(key);
uri += "&" + key + "=" + value;
}
uri = uri + HelperMethods.getConnectionString();
try {
_connection = (HttpConnection) Connector.open(uri);
_connection.setRequestMethod(HttpConnection.GET);
_connection.setRequestProperty("Content-Type",
"text/plain; charset=UTF-8");
_connection.setRequestProperty("x-rim-authentication-passthrough",
"true");
_connection.setRequestProperty("Cookie", loginDetails.getCookie());
_connection.setRequestProperty("Content-Type", "application/json");
String charset = "UTF-8";
_connection.setRequestProperty("Accept-Charset", charset);
_connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
OutputStream _outputStream = _connection.openOutputStream();
int rc = _connection.getResponseCode();
InputStream _inputStream = _connection.openInputStream();
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
int ch;
while ((ch = _inputStream.read()) != -1) {
bytestream.write(ch);
}
result = new String(bytestream.toByteArray());
bytestream.close();
{
if (_outputStream != null)
try {
_outputStream.close();
} catch (Exception e1) {
}
if (_connection != null)
try {
_connection.close();
} catch (Exception e2) {
}
}
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
return result;
}
And this uses:
public synchronized static String getConnectionString() {
String connectionString = null;
// Simulator behaviour is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceside=true";
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid hassling the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
connectionString = "none";
}
// In theory, all bases are covered by now so this shouldn't be reachable.But hey, just in case ...
else {
connectionString = ";deviceside=true";
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*/
private synchronized static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
Fixed - see above.
It turns out that there were spaces in the uri's.
Quite why this worked over WiFi & not 3G etc. is still puzzling.

Resources