push notification iphone error (moon aspn) - c#

I'm using the moon aspn library for sending push notifications in asp.net and c#. I'm encountering the following error: Call to SSPI Failed; in the inner exception i have: Unknown error while processing the certificate; error code: -2147467259.
here is my code:
private void SendQueueToapple(IEnumerable<NotificationPayload> queue)
{
int i = 1000;
foreach (var item in queue)
{
if (!_conected)
{
Connect(_host, NotificationPort, _certificates);
var response = new byte[6];
--> --> --> _apnsStream.BeginRead(response, 0, 6, ReadResponse, new MyAsyncInfo(response, _apnsStream));<-- <-- <--
} try {
if (item.DeviceToken.Length == 64) //check lenght of device token, if its shorter or longer stop generating Payload.
{
item.PayloadId = i;
byte[] payload = GeneratePayload(item);
_apnsStream.Write(payload);
Logger.Info("Notification successfully sent to APNS server for Device Toekn : " + item.DeviceToken);
Thread.Sleep(1000); //Wait to get the response from apple.
}
else
Logger.Error("Invalid device token length, possible simulator entry: " + item.DeviceToken);
}
catch (Exception ex)
{
Logger.Error("An error occurred on sending payload for device token {0} - {1}", item.DeviceToken, ex.Message);
_conected = false;
}
i++;
}
}

This might be a certificate related problem. You have to create .cer and .p12 files. Pay close attention to these files. You first generate the .cer and I'm not going into detail here. There's enough material available. The problem comes when generating the .p12 file.
In your mac, go to the Keychain Access. Select "My Certificates" from the left pane. There you will see a list of certificates. Select the certificate you generated for push notifications. Right click and export. Make sure you DO NOT expand the certificate perform this step on the private key. That's where thing starts to go wrong.

Related

WindowService fails to write in a txt file when I run it from PCs different from mine (where I developed it)

I made a very simple WindowsService that waits data from an UDP port trough WiFi and once received them, it writes them in a txt file (as many examples/tutorials that you can find on the web). I anticipate I usually develop WIndowsForm. The Service choise arises from the need to have a background process that always works, without showing anything to the user... the latter will check the file with the data saved only when needed.
Through the AppConfig.xml file a set the log path and file name and when I run it through VisualStudio no problems appear, as well when I install it (through prompt cmd) on my PC (where I developed it). Everything seems to work properly!
When I tried to install and run it on others PC (included the one where it's supposed to work), the WindowsService has been correctly installed and looked like to work but actually doesn't write on the file (first strange behaviour).
I think is something related to permission.
The account set in the installer is the LocalSystem.
I tried to compile again my project but with the log path hard coded and equals to the directory where the WindowsService.exe is placed but it works only when I run it from VS. When I run it from Services it has the same behaviour seen before: it starts without any error but it doesn't write to the file (second strange behaviour). Obv it doesn't work also to the other PC.
In both cases (write or not) the output in the Process Monitor is the same.Fail to write and OK
Finally, everytime I modify my code and I run it through VS, my Avast antivirus initially blocks the debug because it has to check the .exe file first. Then, the process starts correctly. It's like this only the first time after a change in the code (and so a change in the .exe). This doesn't happen, for example, when I develop and execute WindowsForm...
I'm blocked here from weeks, I hope so much in your help!
Many thanks in advance fot your time.
SB
Code below.
I search for a string in the text file (workbench station).
If this string is already present, I update its associated counter value.
If this string is not present, I added a new line with the new workbench and its counter value.
// Save data received in text file
using (StreamReader sr = new StreamReader(Path.Combine(docPath, fileName)))
{
lineToFind = bancoDiLavoro.Insert(bancoDiLavoro.Length, receiveBytes[0].ToString());
Console.Write("Line to find in text file: ");
Console.WriteLine(lineToFind);
allLines = File.ReadAllLines(Path.Combine(docPath, fileName));
lineNumber = 0;
while (allLines.Length != 0)
{
line = sr.ReadLine();
lineNumber = lineNumber + 1;
try
{
if (line != null)
{
if (line.Contains(lineToFind))
{
sr.Close();
lineFound = true;
allLines[lineNumber - 1] = lineToFind.Insert(lineToFind.Length, "\tConteggio: " + count.ToString() + "\t");
File.WriteAllLines(Path.Combine(docPath, fileName), allLines);
break;
}
}
else
{
Console.WriteLine("Empty line found.");
lineFound = false;
break;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
lineFound = false;
}
}
if (lineFound == false)
{
// Workbench not found: a new workstation has been added
sr.Close();
File.AppendAllText(Path.Combine(docPath, fileName), lineToFind);
File.AppendAllText(Path.Combine(docPath, fileName), "\tConteggio: ");
File.AppendAllText(Path.Combine(docPath, fileName), count.ToString() + "\n");
Thread.Sleep(100);
}
}
[UPDATE]
I've been able to add the EventLog to my service and on the PCs where the service doesn't work, seem that the data are not received on UDP port (even if the port is correctly "opened"). I have to work on this now...
The service remains blocked here:
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
try
{
//Creates a UdpClient for reading incoming data.
UdpClient receivingUdpClient = new UdpClient(UDPport);
//Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
eventLog1.WriteEntry("UDP port opened.");
while (waitForPacket == true)
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
Console.Write("Workbench: ");
Console.Write(receiveBytes[0]);
Console.Write(", count: ");
Console.WriteLine(receiveBytes[1]);
Console.WriteLine("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
eventLog1.WriteEntry("data received.");
// Continues with the data writing...

How to send iOS - APN Notification With P12 Certificate - C# Samples

I am new to IOS APN - Notification generating service , Please help on How we can send APN from C# Windows Service - .Net Framework 4.5 / 4.7?
Tired with Moon-APN , Pushsharp , DotAPN but no result. If any one have sample code with step by step process please share .
Thanks in Advance :-)
#Sumesh you can use the .NET open source library PushSharp to push messages to Apple's APNS service.
step1: Download PushSharp open source project compilation https://github.com/Redth/PushSharp!
step2: After successful compilation, APNS push needs to use Newtonsoft.Json.dll, PushSharp.Apple.dll, PushSharp.Core.dll three assembly library files
step3: Then the ios client needs to provide the .p12 certificate file and the encryption password of the certificate file
step4: After preparing these, create a new console program to reference the above library file, copy the certificate to the root directory, change the attributes, and output to the copy directory as always copy
console program code as follow:
class Program
{
static ApnsConfiguration config;
static ApnsServiceBroker apnsBroker;
static void Main(string[] args)
{
config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, "certificate.p12", "certificate's password");
apnsBroker = new ApnsServiceBroker(config);
//post catch error
apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
//handle failed APN msg
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
Console.WriteLine("Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}" + notification.DeviceToken);
}
else
{
//internal catch error
Console.WriteLine("Apple Notification Failed for some unknown reason : {ex.InnerException}" + notification.DeviceToken);
}
// flag handle
return true;
});
};
//successed
apnsBroker.OnNotificationSucceeded += (notification) =>
{
Console.WriteLine("Apple Notification Sent ! "+notification.DeviceToken);
};
//engined start
apnsBroker.Start();
}
/// <summary>
/// apn message
/// </summary>
public static void SendMsg()
{
List<string> MY_DEVICE_TOKENS = new List<string>() {
"1f6f37acad29348c6a5957529c9fa61ad69766ec9c7367948745899cbccdfd51",
"1f6f37acad29348c6a5957529c9fa61ad69766ec9c7367948745899cbccdfd51"
};
foreach (var deviceToken in MY_DEVICE_TOKENS)
{
// queue triger a notification message to iOS client
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken, // this one deviceToken from iOS client,it have to
Payload = JObject.Parse("{\"aps\":{\"sound\":\"default\",\"badge\":\"1\",\"alert\":\"This is a test of a mass advertising message push message\"}}")
});
}
//engined stop
apnsBroker.Stop();
Console.Read();
}
}
I hope I can help you

C# RSA decrypt parameter is incorrect

I am trying to decrypt communication from web sockets secured with SSL certificate. The certificate is installed on the machine and the private key is present. I have this decrypt function
public static string DecryptTry(X509Certificate2 x509, string stringTodecrypt)
{
try
{
if (x509 == null || string.IsNullOrEmpty(stringTodecrypt))
throw new Exception("A x509 certificate and string for decryption must be provided");
if (!x509.HasPrivateKey)
throw new Exception("x509 certificate does not contain a private key for decryption");
if(x509 == null)
{
Console.WriteLine("certificate is null");
return "";
}
Console.WriteLine("decoding text with private key " + x509.HasPrivateKey);//true
using (RSA csp = (RSA)x509.PrivateKey)
{
byte[] bytestoDecrypt = Encoding.UTF8.GetBytes(stringTodecrypt).Take(256).ToArray();
Console.WriteLine("key size: " + x509.PrivateKey.KeySize + " received data length: " + stringTodecrypt.Length + " bytes length: " + bytestoDecrypt.Length);
Console.WriteLine(Encoding.UTF8.GetString(bytestoDecrypt));
byte[] bytesDecrypted = csp.Decrypt(bytestoDecrypt, RSAEncryptionPadding.OaepSHA256); //ERROR HERE
return Encoding.UTF8.GetString(bytesDecrypted);
}
}
catch(Exception e)
{
Console.WriteLine("Error while decrypting text: " + e.Message + e.HResult + e.StackTrace);
return "";
}
}
But the csp.Decrypt is throwing an error
parameter is incorrect
I have tried all padding parameters - none of the seemed to make a difference.
Does anybody know where the problem might be? Am I missing something?
**
EDIT 25.12.2020
**
To add some more background info: The website where the WebSocket client is listening is secured HTTPS, the SSL certificate is signed by CA with my full access to all of its information. The initial problem is handshake for the WebSocket communication which comes encrypted. I was thinking I would be able to decrypt it with the private key and that is where the problem occurs. The length of the incoming request (or handshake) is between 490 and 520 bytes, so that is the reason for .Take(256). I was thinking to split the text into multiple, decode them separately and put together after. That, however, brought me here.
One final thought: This is a .NET console application. Could the problem be possibly fixed by converting it to a format that IIS accepts? The IIS on the machine has the certificate installed... could it possibly make a difference?
Thanks in advance!
I'm not sure what you want to achieve:
Decrypt something using RSA
Decrypt TLS layer of HTTP
Decrypt something in Websocket protocol
I think that you should give some more informations how it works. Can you show example input for function function, means:
DecryptTry(X509Certificate2 x509, string stringTodecrypt) { ... }
How 'strindTodecypt' looks like? What do you put there?
How do you connect to this server to get data to decrypt, via TLS?

Why Unable to read Message From "Android Device" Using GSMComm Library ,C#

I am Using GSMComm Library to send and receive Messages (Desktop App)...
Sending Code Works Perfectally..
The Problem is when a message Received , I Was Unable to Read the Message while using Android Device,Replaced At-least 4 Samsung Devices , However It was working Perfectly with GSM-3G Devices
Error Shows Up at Following Line
DecodedShortMessage message = messages[indexx]; with Error Message "Index was outside the bounds of the array."/
Is Android doesn't permit to read Message from Phone Memory while permitting to send message?
I Tried everything that i can,But can't help myself..
private void comm_MessageReceived(object sender, MessageReceivedEventArgs e)
{
try
{
IMessageIndicationObject obj = e.IndicationObject;
if (obj is MemoryLocation)
{
MemoryLocation loc = (MemoryLocation)obj;
string storage=loc.Storage;
int indexx = loc.Index;
DecodedShortMessage[] messages = comm.ReadMessages(PhoneMessageStatus.All, loc.Storage);
//Error Shows up in next Line ,
//Exception Message is "Index was outside the bounds of the array."
DecodedShortMessage message = messages[indexx];
SmsPdu pdu = message.Data;
if (pdu is SmsDeliverPdu)
{
SmsDeliverPdu data = (SmsDeliverPdu)pdu;
MessageBox.Show(data.OriginatingAddress.ToString() + data.UserDataText.ToString());
}
return;
}
MessageBox.Show("Error: Unknown notification object!");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message + " (" + ex.GetType().ToString() + ")");
}
}
References Already Tried
Official Site
Code Project Bluck SMS Sender
Send Receive SMS
yes as i read from forums android doesn't permit to read Message from Phone Memory with gsmcomm you can use a android client to send sms from android to pc by socket or if you have a lot of money you can use androino i see an article about how receive and send sms.
i have a question about how to get the sender and the receiver number from the SmsDeliverPdu obeject because i need the sender and the receiver to validate the sms or how to get the sim number of the phone

C# iPhone push server?

Im attempting to write a push server for the iPhone in C#. I have the following code:
// Create a TCP/IP client socket.
using (TcpClient client = new TcpClient())
{
client.Connect("gateway.sandbox.push.apple.com", 2195);
using (NetworkStream networkStream = client.GetStream())
{
Console.WriteLine("Client connected.");
X509Certificate clientCertificate = new X509Certificate(#"certfile.p12", passwordHere);
X509CertificateCollection clientCertificateCollection = new X509CertificateCollection(new X509Certificate[1] { clientCertificate });
// Create an SSL stream that will close the client's stream.
SslStream sslStream = new SslStream(
client.GetStream(),
false,
new RemoteCertificateValidationCallback(ValidateServerCertificate),
null
);
try
{
sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com");
}
catch (AuthenticationException e)
{
Console.WriteLine("Exception: {0}", e.Message);
if (e.InnerException != null)
{
Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
}
Console.WriteLine("Authentication failed - closing the connection.");
client.Close();
return;
}
}
ect....
Only I keep receiving a exception:
"A call to SSPI failed, see Inner exception"
Inner Exception -> "The message received was unexpected or badly formatted."
Does anyone have any idea whats going wrong here?
Figured it out. Replaced sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com"); with sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com", clientCertificateCollection, SslProtocols.Default, false); And registered the certificates on the PC.
Edit: Here is the code for creating a payload as requested:
private static byte[] GeneratePayload(byte [] deviceToken, string message, string sound)
{
MemoryStream memoryStream = new MemoryStream();
// Command
memoryStream.WriteByte(0);
byte[] tokenLength = BitConverter.GetBytes((Int16)32);
Array.Reverse(tokenLength);
// device token length
memoryStream.Write(tokenLength, 0, 2);
// Token
memoryStream.Write(deviceToken, 0, 32);
// String length
string apnMessage = string.Format ( "{{\"aps\":{{\"alert\":{{\"body\":\"{0}\",\"action-loc-key\":null}},\"sound\":\"{1}\"}}}}",
message,
sound);
byte [] apnMessageLength = BitConverter.GetBytes((Int16)apnMessage.Length);
Array.Reverse ( apnMessageLength );
// message length
memoryStream.Write(apnMessageLength, 0, 2);
// Write the message
memoryStream.Write(System.Text.ASCIIEncoding.ASCII.GetBytes(apnMessage), 0, apnMessage.Length);
return memoryStream.ToArray();
} // End of GeneratePayload
From Zenox's comment:
use a different version of AuthenticateAsClient
sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com", clientCertificateCollection, SslProtocols.Default, false);
Other way is just to use X509Certificate2 and X509CertificateCollection2 classes.
I recently used Growl For Windows to push messages to the Prowl client on the IPhone from .Net code. So you might get your functionatlity without writing a push server yourself.
The "The message received was unexpected or badly formatted." error usually comes when you did not register the p12 certificate in Windows. (Under Vista, just double click on the p12 file and the import wizard will open)
In my case I had to delete all the certificate from my windows 8 and then re-install them in order to send push notifications to apple device.
I do not know why my certificates stop working, I am searching for the correct reason and will update here soon.

Categories

Resources