java.security.cert.CertificateException: Could not parse certificate: java.io.IOException: Empty input - x509certificate

I have a certificate in my javacard applet which the host application requests to verify challenges from the host application signed by the card applet:
The host application computes challenges for the javacard applet to sign as follows.
byte [] card_signature=null;
SecureRandom random = SecureRandom . getInstance( "SHA1PRNG" ) ;
byte [ ]bytes = new byte [ 20 ] ;
random . nextBytes ( bytes) ;
CommandAPDU challenge;
ResponseAPDU resp3;
challenge = new CommandAPDU(IDENTITY_CARD_CLA,SIGN_CHALLENGE, 0x00, 0x00,bytes ,20 );
resp3= c.transmit(challenge);
if(resp3.getSW()==0x9000) {
card_signature = resp3.getData();
String s= DatatypeConverter.printHexBinary(card_signature);
System.out.println("signature: " + s);
}else System.out.println("Challenge signature error " + resp3.getSW());
The javacard applet signs the host application challenges and sends back the signature as follows:
private void sign(APDU apdu) {
if(!pin.isValidated())ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
else{
byte[] buffer = apdu.getBuffer();
byte [] output = new byte [64];
short length = 64;
short x =0;
Signature signature =Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, false);
signature.init(privKey, Signature.MODE_SIGN);
short sigLength = signature.sign(buffer, offset,length, output, x);
//This sequence of three methods sends the data contained in
//'serial' with offset '0' and length 'serial.length'
//to the host application.
apdu.setOutgoing();
apdu.setOutgoingLength((short)output.length);
apdu.sendBytesLong(output,(short)0,(short)output.length);
}
}
To verify the javacard applet signature, the host requests the javacard applet certificate from the javacard. The certificate (as a byte array) is 256 bytes and I gather it can only be sent in blocks of lenghth 240. The javacard applet sends the certificate as follows:
private void send_certificate (APDU apdu) {
if(!pin.isValidated())ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
else{
apdu.setOutgoing();
apdu.setOutgoingLength((short)240);
apdu.sendBytesLong(certificate,(short)0,(short)240);
}
}
The host application then receives the certificate in bytes and constructs the certificate. In addition, it attempts to verify signed challenges with the certificate as follows:
//Get certificate
CommandAPDU card_cert;
ResponseAPDU resp4;
card_cert = new CommandAPDU(IDENTITY_CARD_CLA, SEND_CERTIFICATE, 0x00, 0x00);
resp4 = c.transmit(card_cert);
if(resp4.getSW()==0x9000) {
byte [] response = resp4.getData();
String certf= DatatypeConverter.printHexBinary(response);
System.out.println("CERTIFICATE: " + certf);
CertificateFactory certFac = CertificateFactory.getInstance("X.509");
InputStream is = new ByteArrayInputStream(response);
X509Certificate cert = ( X509Certificate ) certFac .generateCertificate( is ) ;
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initVerify(cert.getPublicKey());
signature.update(card_signature);
if(card_signature !=null) {
boolean ok =signature.verify(card_signature);
if(ok==true)System.out.println("verification completed" );
}
}
I get the error below:
signature: 802800001438BBAE2CE7AD2498B0A8DA91634230A5D8324DBD4039F8376404AB1B7FF1B37DF63D22AFB2B6ABE37B31E8276B28427FA56FCF38EDF05FBC1EEF50C81A1C4F88560048D1C0E6D20B13000B384E0AE3AFED2751927F
CERTIFICATE:8030000000F0308201BD30820167A003020102020500B7D56095300D06092A864886F70D01010505003064310B3009060355040613024245310D300B06035504070C0447656E7431193017060355040A0C104B61486F2053696E742D4C696576656E31143012060355040B0C0B56616B67726F65702049543115301306035504030C0C4A616E20566F7373616572743020170D3130303232343039343330325A180F35313739303130393139323934325A3064310B3009060355040613024245310D300B06035504070C0447656E7431193017060355040A0C104B61486F2053696E742D4C696576656E31143012060355040B0C0B56
Exception in thread "main" java.security.cert.CertificateException: Could not parse certificate: java.io.IOException: Empty input
at sun.security.provider.X509Factory.engineGenerateCertificate(X509Factory.java:110)
at java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:339)
at be.msec.client.Client.main(Client.java:133)
Caused by: java.io.IOException: Empty input
at sun.security.provider.X509Factory.engineGenerateCertificate(X509Factory.java:106)
... 2 more
Is it possible that my approach to sending the certificate to the host application is wrong? Also, could I be retreiving the certficate in the host application in a wrong way? I could not get my solution here: Could not parse certificate: java.io.IOException: Empty input X509Certificate

Related

QRS API call returns "The client certificate credentials were not recognized"

Exported Qlik Sense certificate using QMC (client.pfx, root.cer, server.pfx).
Imported certificates into IIS web server using MMC. Server and client certificates to store Personal->Certificates, root to store Trusted Root Certification Authorities.
Requested QRS API from ASP.NET controller using QlikClient certificate from store (code below). Tried various user IDs and directories, including INTERNAL/sa_repository, but in all cases got an error "An error occurred while sending the request. The client certificate credentials were not recognized".
Endpoint for test : https://server:4242/qrs/about
I've searched the web but I haven't managed to find what I'm doing wrong, what credentials I should provide.
On the other hand, as I converted exported certificates to separate .key/.crt files (using https://www.markbrilman.nl/2011/08/howto-convert-a-pfx-to-a-seperate-key-crt-file/) and used them in the Postman from web server, it worked without any problem, actually with any UserId in header (i guess it's ignored in that case).
ASP.NET controller:
public X509Certificate2 LoadQlikCertificate()
{
X509Certificate2 certificate = null;
try
{
// Open certification store (MMC)
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
// Get certiface based on the friendly name
certificate = store.Certificates.Cast<X509Certificate2>().FirstOrDefault(c => c.FriendlyName == "QlikClient");
// Logging for debugging purposes
if (certificate != null)
{
logger.Log(LogLevel.Warning, $"Certificate: {certificate.FriendlyName} {certificate.GetSerialNumberString()}");
}
else
{
logger.Log(LogLevel.Warning, $"Certificate: No certificate");
}
// Close certification store
store.Close();
// Return certificate
return certificate;
}
catch (Exception e)
{
...
}
}
/* Get Qlik API response
***********************/
[HttpGet("getqlikapi")]
public IActionResult GetQlikAPI()
{
// Get Qlik certificate
var certificate = this.LoadQlikCertificate();
try
{
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
// Set server name
string server = "server";
// HARDCODED USER AND DIRECTORY FOR TESTING
string userID = "sa_repository"; // tried also other user ids
string userDirectory = "INTERNAL";
// Set Xrfkey header to prevent cross-site request forgery
string xrfkey = "abcdefg123456789";
// Create URL to REST endpoint
string url = $"https://{server}:4242/qrs/about?xrfkey={xrfkey}";
// The JSON object containing the UserId and UserDirectory
string body = $"{{ 'UserId': '{userID}', 'UserDirectory': '{userDirectory}', 'Attributes': [] }}";
// Encode the json object and get the bytes
byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
// Create the HTTP Request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// Add the method to authentication the user
request.ClientCertificates.Add(certificate);
// POST request will be used
request.Method = "POST";
// The request will accept responses in JSON format
request.Accept = "application/json";
// A header is added to validate that this request contains a valid cross-site scripting key (the same key as the one used in the url)
request.Headers.Add("X-Qlik-Xrfkey", xrfkey);
request.ContentType = "application/json";
request.ContentLength = bodyBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bodyBytes, 0, bodyBytes.Length);
requestStream.Close();
// Make the web request and get response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
// Return string in response
//return new OkObjectResult(stream != null ? new StreamReader(stream).ReadToEnd() : string.Empty);
return new OkObjectResult("test");
}
catch (Exception e)
{
...
}
}
I ran into this issue on a system we are building.
The problem was that the user did not have rights to the certificate.
Open certificate manager (Start > Manage Computer Certificates)
Find the required certificate.
Right-click cert > All Tasks > Manage Private Keys > Add > [Select the appropriate user]
Note: Manage User Certificates does not have the Manage Private Keys option.

APNS push notification error - A call to SSPI failed, see inner exception

I know that this questions has been asked before, but none of that seems to help me.
I am trying to send push notifications from my asp.net application but i get the following error:
"A call to SSPI failed, see inner exception." System.Exception {System.Security.Authentication.AuthenticationException}
"The message received was unexpected or badly formatted" System.Exception {System.ComponentModel.Win32Exception}
And here is the code:
int port = 2195;
String hostname = "gateway.sandbox.push.apple.com";
//load certificate
string certificatePath = HostingEnvironment.ApplicationPhysicalPath + "cert.pem";
string certificatePassword = "xxxxxxx";
X509Certificate2 clientCertificate = new X509Certificate2(certificatePath, certificatePassword);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
TcpClient client = new TcpClient(hostname, port);
SslStream sslStream = new SslStream(
client.GetStream(),
false,
null,
null
);
try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, System.Security.Authentication.SslProtocols.Tls, false);
}
catch (AuthenticationException ex)
{
client.Close();
}
// Encode a test message into a byte array.
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0); //The command
writer.Write((byte)0); //The first byte of the deviceId length (big-endian first byte)
writer.Write((byte)32); //The deviceId length (big-endian second byte)
String deviceId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
writer.Write((deviceId.ToUpper().ToArray()));
String payload = "{\"aps\":{\"alert\":\"Test\",\"badge\":14}}";
writer.Write((byte)0); //First byte of payload length; (big-endian first byte)
writer.Write((byte)payload.Length); //payload length (big-endian second byte)
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
// Close the client connection.
client.Close();
Is there a problem with my certificate, or why could this be happening?
Am i supposed to use a p12 file? If so, how can i get the p12 file if i have the .pem file?
I am developing this on windows, but i am supposed to register the certificate somewhere in windows?
Best regards,
Marius.

Forbidden socket access attempt Exception when reading from socket from a WebMatrix 3/ASP.NET web page?

I have a WebMatrix 3 (same as ASP.NET) web page that opens a socket to a server process running on an Azure hosted Linux VM that listens on a TCP connection for clients. The Linux VM server process is mine too. When I run the WebMatrix 3/ASP.NET web site locally from my home PC using a local copy of IIS it works fine (local publish). When I publish my web site to the web and it is now running on Azure I get the Exception:
An attempt was made to access a socket in a way forbidden by its access permissions
What is really confusing is that the error occurs when I read from the socket but oddly enough not when I connect to it or write to it before-hand. I know this because the Exception message is adorned with the current operation, and that is set to:
Waiting for and then reading the response from the ChatScript server.
You can see this line in the code below. Is there something going on with the Azure side that could be blocking reads from the TCP connection to the Linux VM, yet allows connections to that VM and even sends? I say "even sends" because as you can see from the code below, I immediately send a message to the Linux VM process before I try to read from that connection.
public static string readChatScriptMessage(NetworkStream myNetworkStream)
{
if (myNetworkStream == null)
throw new ArgumentNullException("(readChatScriptMessage) The network stream is unassigned.");
StringBuilder myCompleteMessage = new StringBuilder();
// Check to see if this NetworkStream is readable.
if (myNetworkStream.CanRead)
{
byte[] myReadBuffer = new byte[1024];
int numberOfBytesRead = 0;
// Incoming message may be larger than the buffer size.
do
{
numberOfBytesRead = myNetworkStream.Read(myReadBuffer, 0, myReadBuffer.Length);
myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
}
while (myNetworkStream.DataAvailable);
}
else
{
if (myNetworkStream == null)
throw new InvalidOperationException("(readChatScriptMessage) The network stream is unassigned.");
}
// Print out the received message to the console.
return myCompleteMessage.ToString();
} // public static string readChatScriptMessage(NetworkStream myNetworkStream)
// Lookup the IP address for our chatscript server. (Cache this value
// in a later build since GetHostEntry() is reportedly a slow call.)
ipAddress = Dns.GetHostEntry("myazureapp.cloudapp.net").AddressList[0];
strCurrentOperation = "Validating URL arguments (parameters).";
// LoginName, is mandatory.
strLoginName = checkForValidURLArgument("LoginName", true);
// BotName, is optional.
strBotName = checkForValidURLArgument("BotName", false);
// User message (chat input), is optional. But remember,
// only send a blank message to start a new session
// with ChatScript! After that, send the user's input
// each time.
strMessage = checkForValidURLArgument("Message", false);
strCurrentOperation = "Connecting to Linux VM TCP server.";
// OK, we're good to go. We have the 3 URL arguments we were expecting.
// Connect to the ChatScript server.
tcpCli.Connect(ipAddress, 1024);
strCurrentOperation = "Opening the stream with the server.";
// Open the stream
streamChatScript = tcpCli.GetStream();
StreamReader sr = new StreamReader(streamChatScript);
BinaryWriter sw = new BinaryWriter(streamChatScript);
// Create a message to send to the server, using the URL argument values
// passed to us.
ChatMessage cm = new ChatMessage(strLoginName, strBotName, strMessage);
strCurrentOperation = "Sending the desired chat message to the server.";
// Send the message to the chat server.
string strSendChatMsg = cm.ToString();
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(strSendChatMsg);
for (int i = 0; i < strSendChatMsg.Length; i++)
{
data[i] = (byte)strSendChatMsg[i];
}
// Send the chat message.
streamChatScript.Write(data, 0, data.Length);
strCurrentOperation = "Waiting for and then reading the response from the server.";
strResponseMsg = ChatMessage.readChatScriptMessage(streamChatScript);

Decrypt bytes in asp.net

Following is my Java applet code
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] privKeyBytes = loadPriavteKeyFromFile(fileName, new String(txtPassword.getPassword()));
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
Cipher rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.ENCRYPT_MODE, privKey);
byte[] ciphertext = null;
ciphertext = rsaCipher.doFinal(xmlToSign.getBytes());
String urlString = "http://localhost:3290/SignApplet.aspx";
String senddata = Base64.encodeBase64String(ciphertext);
doHttpUrlConnectionAction(urlString,senddata.getBytes());
JOptionPane.showMessageDialog(this, "XML successfully signed and sent to server.");
on the server side i am trying too decrypt the byte using the public key
byte[] b;
b = Request.BinaryRead(178);
string encodedbytes = new System.Text.UTF8Encoding().GetString(b);
b = Convert.FromBase64String(encodedbytes);
Debug.WriteLine("decrypted bytes:" + new System.Text.UTF8Encoding().GetString(b));
// The path to the certificate.
string Certificate = #"c:\certs\lafa801114sd3.cer";
//// Load the certificate into an X509Certificate object.
X509Certificate cert = new X509Certificate(Certificate);
RSACryptoServiceProvider publicprovider = (RSACryptoServiceProvider)CertUtil.GetCertPublicKey(cert);
byte[] decbytes = publicprovider.Decrypt(b, false);
Debug.WriteLine("decrypted bytes" + new System.Text.UTF8Encoding().GetString(decbytes));
can any one help in following exception which i am getting at byte[] decbytes = publicprovider.Decrypt(b, false); line
A first chance exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
Key does not exist.
and the certificate is not installed in nay key store.Also i can successfully decrypt the data using Java servlet .
i am using asp.net vs2010 on windows 7
the public and private keys are stored in separate files
Here are a few articles that might help you: Java RSA Encrypt - Decrypt .NET (which seems like what you are looking for)
and http://www.jensign.com/JavaScience/dotnet/RSAEncrypt/

confusion about Certificates

I have WCF REST web service hosted by IIS, it works on HTTPS, I generate Certificate on IIS and assign Https to a port
I generate cer through IE browser. I create a test application and regardless Add a client certificate or not or even add a wrong certificate the connection take place and a I get correct response. I am wondering how the message was decrypted if there is no certificate sent.
Either the destination is not secured or I misunderstand the whole thing.
also
The error I have from the callback "CheckValidationResult()" is either
CertCN_NO_MATCH = 0x800B010F
or
"Unknown Certificate Problem" , the certificateProblem (parameter of CheckValidationResult) is 0 for this case
What is CertCN_NO_MATCH eror, what is CN?
See code below.
ServicePointManager.CertificatePolicy = new CertPolicy();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(String.Format("https://{0}/uri", ip));
//request.ClientCertificates.Add(new X509Certificate("D:\\ThePubKey.cer"));
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
using (StreamWriter stream = new StreamWriter(request.GetRequestStream()))
{
stream.Write("RequestType=CheckStatus&ReportType=Fulfillment&ReportID=5");
}
using (StreamReader stream = new StreamReader(request.GetResponse().GetResponseStream()))
{
Response.ContentType = "text/xml";
Response.Output.Write(stream.ReadToEnd());
Response.End();
}
class CertPolicy : ICertificatePolicy
{
public enum CertificateProblem : uint
{
CertEXPIRED = 0x800B0101,
CertVALIDITYPERIODNESTING = 0x800B0102,
CertROLE = 0x800B0103,
CertPATHLENCONST = 0x800B0104,
CertCRITICAL = 0x800B0105,
CertPURPOSE = 0x800B0106,
CertISSUERCHAINING = 0x800B0107,
CertMALFORMED = 0x800B0108,
CertUNTRUSTEDROOT = 0x800B0109,
CertCHAINING = 0x800B010A,
CertREVOKED = 0x800B010C,
CertUNTRUSTEDTESTROOT = 0x800B010D,
CertREVOCATION_FAILURE = 0x800B010E,
CertCN_NO_MATCH = 0x800B010F,
CertWRONG_USAGE = 0x800B0110,
CertUNTRUSTEDCA = 0x800B0112
}
public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
{
// You can do your own certificate checking.
// You can obtain the error values from WinError.h.
// Return true so that any certificate will work with this sample.
String error = "";
using (StringWriter writer = new StringWriter())
{
writer.WriteLine("Certificate Problem with accessing " + request.RequestUri);
writer.Write("Problem code 0x{0:X8},", (int)certificateProblem);
writer.WriteLine(GetProblemMessage((CertificateProblem)certificateProblem));
error = writer.ToString();
}
return true;
}
private String GetProblemMessage(CertificateProblem Problem)
{
String ProblemMessage = "";
CertificateProblem problemList = new CertificateProblem();
String ProblemCodeName = Enum.GetName(problemList.GetType(), Problem);
if (ProblemCodeName != null)
ProblemMessage = ProblemMessage + "-Certificateproblem:" +
ProblemCodeName;
else
ProblemMessage = "Unknown Certificate Problem";
return ProblemMessage;
}
}
I've just replied to this similar question (in Java).
CN is the "Common Name". It ought to be the hostname of the server to which you're connecting (unless it's in the subject alternative name). I guess from your code sample that you're using the IP address directly. In this case, the CN should be that IP address (it tends to be better to use a hostname rather than an IP address). See RFC 2818 (sec 3.1) for the specifications.
Note that the CN or subject alternative name is from the point of view of the client, so if you connect to https://some.example.com/, then the name in the cert should be some.example.com, if you connect to https://localhost/, then the name in the cert should be localhost, even if some.example.com and localhost may be the same server effectively.
(I guess that by default, IIS might generate a certificate for the external name, but you'd have to look at the certificate to know; this should be visible in the certificate properties somewhere.)

Resources