Cross Platform Encoding of Encrypted Strings in PHP and OSX - php

Im encrypting a string in PHP using the following code
<?php
$key256 = "323";
$iv128 = "2424";
$text = "ABC";
$blocksize = 16;
$len = strlen($text);
$pad = $blocksize - ($len % $blocksize);
$text .= str_repeat("0", $pad);
$cipher = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key256, $text, MCRYPT_MODE_CBC, $iv128);
echo $cipher;
?>
In SWIFT I use POST Request and get the data from the server and print out the fetched data to the console like this
var request = URLRequest(url: URL(string: "http://www.example.com/test.php")!)
request.httpMethod = "POST"
let akey:String = txt_key.stringValue;
let email:String = txt_email.stringValue
let VAL:String="test"
var data="blah"
let postString = data
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print(responseString)
}
task.resume()
This keeps printing nil even when the Web Browser shows the encrypted string.
What I'm I doing wrong?
Update
I have set the app transport security and stuff in the info.plist and the printing works correctly if I don't use encryption in php

Related

swift 3 http request

I am trying to sent input from the user to a php script to have it ultimately passed to an SQL server, Most of the code runs but having problem with submitting the data.
#IBAction func submit(_ sender: AnyObject) {
let requestURL = URL(string: "*****")
let request = NSMutableURLRequest(url:requestURL!)
request.httpMethod = "POST"
let song=txt1.text!
let artist=txt2.text!
let album=txt3.text!
let year=txt4.text!
let genre=txt5.text!
let songPost = "song=" + (song as String)
let artistPost = "&artist=" + (artist as String)
let albumPost = "&album=" + (album as String)
let yearPost = "&year=" + (year as String)
let genrePost = "&genre=" + (genre as String)
request.httpBody = songPost.data(using: String.Encoding.utf8);
request.httpBody = artistPost.data(using: String.Encoding.utf8);
request.httpBody = albumPost.data(using: String.Encoding.utf8);
request.httpBody = yearPost.data(using: String.Encoding.utf8);
request.httpBody = genrePost.data(using: String.Encoding.utf8);
--->>let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
print(response)
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
Having an issue with the urlsession.shared.datatask line of code. Compiler error says "ambigious reference to member'dataTask(with:completionhandler:)"
What can get this code to work and how can I verify that this information was passed on the app?
The reason you get that error message is because you are passing NSMutableURLRequest where URLRequest is needed.
Changing this line:
let request = NSMutableURLRequest(url:requestURL!)
to this:
var request = URLRequest(url:requestURL!)
should fix it.
But I recommend a little more fixes to make your request successfully sent to the server:
let requestURL = URL(string: "*****")
//You should use `URLRequest` in Swift 3, mutability is represented by `var`
var request = URLRequest(url:requestURL!)
request.httpMethod = "POST"
//UITextField.text can be nil, you should treat nil cases
//(Generally avoid using forced unwrapping `!` as far as you can.)
let song = txt1.text ?? ""
let artist = txt2.text ?? ""
let album = txt3.text ?? ""
let year = txt4.text ?? ""
let genre = txt5.text ?? ""
//`song`,... are all Strings, you have no need to add `as String`
let songPost = "song=" + song
let artistPost = "&artist=" + artist
let albumPost = "&album=" + album
let yearPost = "&year=" + year
let genrePost = "&genre=" + genre
//You need to make a single data containing all params
//(Creating a concatenated String and getting `data` later would be another way.)
var data = Data()
data.append(songPost.data(using: String.Encoding.utf8)!)
data.append(artistPost.data(using: String.Encoding.utf8)!)
data.append(albumPost.data(using: String.Encoding.utf8)!)
data.append(yearPost.data(using: String.Encoding.utf8)!)
data.append(genrePost.data(using: String.Encoding.utf8)!)
request.httpBody = data
let task = URLSession.shared.dataTask(with: request) { data, response, error in
...

Swift: Data not fetching correctly from PHP

I am creating an app, where I am fetching the data from a php. To download the data from the php, I have a func that downloads the data, submits to the model, and then retrieves it whenever needed. Now the issue is, when my data is fetched from the data base, it is not snyc appropriately and getting the same info every where. For example, Name shows the mob phone; street address also shows the same.
here is my code
func download(){
let request = NSMutableURLRequest(url: URL(string: "http://www.some-site.com")!)
request.httpMethod = "POST"
let postString = "id=\(businessID)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: (request as URLRequest), completionHandler: { data, response, error in
let responseString = String(data: data!, encoding: String.Encoding.utf8)
let r = self.convertStringToDictionary(responseString!)
for element in r! {
print("element = \(element)")
let stname = String(describing: element.first!)
let sn = stname.replacingOccurrences(of: "\"STREET_NAME\", ", with: "")
let name = String(describing: element.first!)
let n = name.replacingOccurrences(of: "\"FILE_LOCATION\", ", with: "")
let reverse = element.reversed()
let fileloc = String(describing: reverse.first!)
let f = fileloc.replacingOccurrences(of: "\"BUSINESS_NAME\", ", with: "")
self.model = ProfilePage(fileloc: f, streetname: sn, name: n)
print("Address = \(stname)")
print("Name = \(name)")
print("File Location = \(f)")
DispatchQueue.main.async {
self.setUI()
}
}
if error != nil {
print("error=\(error)")
}
})
task.resume()
}
}
but yes in my output console, i can see all the infor appropriate, its just when i run this, it shows all the info as one
Screenshots
Let me Know is this work for you,
let r = self.convertStringToDictionary(responseString!) // Make sure Your string is successfully converted as NSDictionary else use below
// let r = self.convertStringToDictionary(responseString!) as NSDictionary // if r is dictionary, then convert to NSDictionary
let stname = r["STREET_NAME"] as! String
let name = r["FILE_LOCATION"] as! String
let f = r["BUSINESS_NAME"] as! String
print("Address",stname)
print("Name",name)
print("File Location",f)
DispatchQueue.main.async {
self.setUI()
}
If you confuse, then refer below example
let mydict = ["Hip-Hop Tamizha": 21,"Hip-Hop Tamizha":"Takkaru Takkaru","Michael Jackson":"Beat It","Taylor Swift":"Back to December","Katy Perry":"Fire Works","Selina Gomez":"Love You Like A Love Song Baby","Avril Lavigne":"Slipped Away","Eminem":"The Music Box","Akhil":"Khaab","Hip-Hop Tamizha": 21,"Akhil": 61] as NSDictionary
let hop = mydict["Hip-Hop Tamizha"] as AnyObject
let swift = mydict["Taylor Swift"] as! String
print("The Number:",hop)
print("Taylor Swift song:",swift)

Incomplete Base64 when sending to server

I am trying to send an image to server, but the image should be in Base64 format. I am using this function to send it:
func upload_signature_staff(ticket: NSString){
let defaults = NSUserDefaults.standardUserDefaults()
let stringOne = defaults.stringForKey(defaultsKeys.staff_id)
let stringtwo = defaults.stringForKey(defaultsKeys.mst_customer)
let sig = defaults.stringForKey("staff_signature")
let request = NSMutableURLRequest(URL: NSURL(string: "http://xxxxxxxxxxxxx/upload.php")!)
request.HTTPMethod = "POST"
let postString = "action=add_signature&mst_customer=\((stringtwo!))&ticket=\((ticket))&signature=\((sig!))&current_user=\((stringOne!))&item_type=10"
print(postString)
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
//self.performSegueWithIdentifier("goto_main2", sender: self)
}
The sig variable holds the Base64 string, it is being printed in my console so I can verify that the string is correct. I am also printing the postString and upon inspection it is also correct that the signature is matching the Base64 String. But when I open phpmyadmin, I see the field of my image with incomplete Base64 string, maybe 1/4 is just there.
Here's my php code, in case you want to see it:
<?php
require_once("../c.php");
$action = trim($_POST['action']);
if($action == "add_signature"){
$mst_customer = trim($_POST['mst_customer']);
$ticket = trim($_POST['ticket']);
$signature = trim($_POST['signature']);
$current_user = trim($_POST['current_user']);
$item_type = trim($_POST['item_type']);
$inputtime = time();
$sql = "INSERT INTO ticket_items SET mst_customer = '$mst_customer', ticket = '$ticket', ticket_item_type = '$item_type', details = '$signature', addedby = '$current_user', lastupdate = '$inputtime' ";
mysql_query($sql) or die(mysql_error());
}
?>
I think this was solved in the comments but here's a recap:
Inserting base64 strings that were too long (variable length?) in a varchar(255) field resulted in missing data. As far as I can tell, increasing the size of the field solved the immediate problem. I use the term "immediate" because, as #YvesLeBorg pointed out in the comments, this is bound to fail at some point without input size restrictions on the backend.
Additionally, I couldn't ignore the fact that the PHP/SQL code was wide open to injections.
Passing $mst_customer = trim($_POST['mst_customer']); on to "INSERT INTO ticket_items SET mst_customer = '$mst_customer' and then executing via mysql_query($sql) or die(mysql_error()); is dangerous!
Anybody could write anything in the $_POST parameter and SQL would happily accept it. Prepared statements, PDO, input sanitization etc. are there for a reason.
Finally, there was an issue concerning vanishing + signs in the base64 data. This was the result of missing url encoding of the post data.
I think that sums it up.

swift php array to swift json

I am trying to work with a swift code to pass vars to php and a response back to swift. this all goes smooth with the following code. This is just a simple peice of code to get things going. It gives me the correct connection and results, how ever i have to pass loads of data which should be in an array i guess. But when i try to send through more data in a array i don't see anything. In php i would explode the results to get them one by one but how do i get loads of values to variables so i can use them again?
below is my code
<?php
require('conn.php');
header('Content-type: application/json');
if($_POST) {
$database =trim ($_POST['database']);
$engine = trim($_POST['engine']);
$name = "William";
$results = Array("name" => $name
);
echo json_encode($results);
}/*end if POST*/
?>
this is the swift code
let data:NSString = ("bfdprofile" as NSString)
let engine:NSString = "account" as NSString
self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String
let url = NSURL(string:"xxxxx.php")
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
// set Content-Type in HTTP header
let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
// set data
var dataString = "data=\(data)&engine=\(engine)"
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
// set content length
//NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request)
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)
if let results = NSJSONSerialization.JSONObjectWithData(reply!, options: nil, error: &error) as? [String: String]{
if let name = results["name"]{
labelTestOutput.text = name as? String
}
}
Thanks for the help
You can do it asynchronously with Alamofire library as simple as that:
typealias JSONdic = [String: AnyObject]
let param = ["data": "somedata", "engine": "someEngine"]
Alamofire.request(.POST, URLString: "xxxxx.php", parameters: param).responseJSON() {
(_,_,json,_) in
if let json = json as? JSONdic, name = json["name"] as? String {
// do something with name
}
}

PHP JSON decoded in Swift iOS returns empty value

I am trying to send JSON from PHP to iOS Swift.
But when I decode json in Swift, the value is "",
although the key comes out well.
I learned the variables in PHP have to be UTF-8 encoded, but same problem occurs even after the encoding.
Can anyone help me how to solve this issue?
You can just copy & paste both PHP and Swift code.
If I run this code in a web browser, I get
{"upDirection":"\u00ec\u00a2\u0085\u00ed\u0095\u00a9\u00ec\u009a\u00b4\u00eb\u008f\u0099\u00ec\u009e\u00a5"}
This is the code:
<?php
//if(isset($_POST["stationId"]) && isset($_POST["dateTime"])) {
include('simple_html_dom.php');
/* for testing */
$station_id = "923";
$date_time = "201507091750";
$url = "http://m.map.naver.com/pubtrans/inquireSubwayDepartureInfo.nhn?stationID=".$station_id."&inquiryDateTime=".$date_time."00&count=5&caller=mobile_naver_map&output=json";
$html = file_get_contents($url);
//Json to array
$json = json_decode($html, true);
$result = $json["result"];
/**
upDirection
**/
$upDirection = $result["upDirection"];
$upDirection = utf8_encode($upDirection);
// Return as json
$return_json = [
"upDirection" => $upDirection
];
header('Content-Type: application/json; charset=utf-8');
echo json_encode($return_json);
//}
?>
And here is the code in swift
func fetchTimeSchedule() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
// Send the station ID to PHP
var url: NSURL = NSURL(string: self.timeScheduleUrl)!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
// Prepare post data
// station id
let stationId = self.currentViewingStation.id
// datetime
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay | .CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let year = components.year
let month = components.month < 10 ? "0\(components.month)" : "\(components.month)"
let day = components.day < 10 ? "0\(components.day)" : "\(components.day)"
let hour = components.hour < 10 ? "0\(components.hour)" : "\(components.hour)"
let minutes = components.minute < 10 ? "0\(components.minute)" : "\(components.minute)"
let dateTime = "\(year)\(month)\(day)\(hour)\(minutes)"
var bodyData = "stationId=\(stationId)&dateTime=\(dateTime)"
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
println("bodyData:\(bodyData)")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error = \(error)")
return
}
if let HTTPresponse = response as? NSHTTPURLResponse {
println("received:\(HTTPresponse.statusCode)")
if HTTPresponse.statusCode == 200 { // Successfully got response
var err: NSError?
if let json : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) {
// decode json
println(json) // <- Here ******************
}
}
}
}
task.resume()
})
}
This is what the line
println(json) // <- Here ******************
prints out:
Optional({
upDirection = "";
})
i solved this problem with this code:
let url = NSURL(string:yourUrl)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
// set Content-Type in HTTP header
let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
// set data
var dataString = "user=mike"
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)
let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
println("API Response: \(results)")
With this php
header('Content-Type: application/json; charset=utf-8');
$a1 = $_POST['user'];
$returnValue = array("a1"=>$a1);
echo json_encode($returnValue);

Categories