I used this to generate .crt and .key files:
openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes -keyout example.key -out example.crt -subj "/CN=example.com" -addext "subjectAltName=DNS:example.com,DNS:www.example.net,IP:127.0.0.1"
I have this node.js code:
var https = require('https');
var fs = require('fs');
var privateKey = fs.readFileSync('sslcert/example.key', 'utf8');
var certificate = fs.readFileSync('sslcert/example.crt', 'utf8');
var credentials = { key: privateKey, cert: certificate };
var express = require('express');
var app = express();
httpsServer.listen(8443);
I could use Postman and get the response using the 8443 port.
When I use the browser, I get this error:
127.0.0.1:8443 uses an invalid security certificate.
The certificate does not come from a trusted source.
I installed the .crt file on my Windows machine. I also tried to import the .crt file to Firefox. When I try to import it under "Your certificates" I get this error:
This personal certificate can’t be installed because you do not own the corresponding private key which was created when the certificate was requested.
When I import it to "Authorities" it works. Why? My self signed certificate acts as a CA?
Related
var uris = new[]
{
new Uri("https://10.8.173.179:9200"),
};
var connectionPool = new SniffingConnectionPool(uris);
var settings = new ConnectionConfiguration(connectionPool);
settings.BasicAuthentication("elastic", "password");
var lowlevelClient = new ElasticLowLevelClient(settings);
var health = lowlevelClient.Cluster.Health<StringResponse>();
Getting below :
System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
Take a look at the working with certificates documentation.
If you're using a self signed cert, you can use either the following on ConnectionSettings.ServerCertificateValidationCallback(...)
CertificateValidations.AllowAll; to allow all certificates
CertificateValidations.AuthorityIsRoot(cert) and pass it the Certificate Authority (CA) public key to validate that the certificate the server presents is generated with the CA
CertificateValidations.AuthorityPartOfChain(cert) and pass it the certificate.
The application I develop must send a post request each time an event happen on a specific folder.
I've built the JSON I want to post.
My issue is the following : the request must use a P12 certificate. For this I used :
keytool -importkeystore -srcstoretype PKCS12 -srckeystore MYCERTIFICATE.p12 -destkeystore keystore.jks -deststoretype pkcs12
I set a yaml file which contains information about the keystore :
server:
ssl:
key-store-type: PKCS12
key-store: 'classpath:keystore.jks'
key-store-password: password
key-alias: macsf_c
Finally I created a method that send the request to the remote server :
public DocumentDto sendRequest(DocumentDto documentDto) throws IOException {
// set the URL to send the request
URL url = new URL(properties.getProperty("signature.api.url.full"));
// opening the connection
HttpURLConnection con = (HttpURLConnection)url.openConnection();
// set protocol, accept & content type format
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
System.out.println(con.toString());
// create the JSON String
ObjectMapper mapper = new ObjectMapper();
// for test purpose : generate the JSON file
mapper.writeValue(new File("C:\\Users\\Dvera\\Documents\\testSignature\\document.json"), documentDto);
// convert an oject to a json string
String jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(documentDto);
try(OutputStream os = con.getOutputStream()) {
byte[] input = jsonInString.getBytes("utf-8");
os.write(input, 0, input.length);
}
// read the response
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
System.out.println(jsonInString);
return null;
}
Actually i'm not working on the return type. My issue is that I have a 403 error. I do think that i must add the keystore to my request and i'm stuck at this point...
I can't seem to be able to get the merchant session validation working with Ruby. Tried HTTParty and RestClient and I'm getting:
OpenSSL::SSL::SSLError (SSL_connect returned=1 errno=0 state=SSLv3 read finished A: sslv3 alert certificate expired):
I tried the same certificate with this node server example, https://github.com/tomdale/apple-pay-merchant-session-server, and it worked fine, so it must be something in my ruby code.
Has anyone managed to get this working?
I was having the same problem. With the help of the example you referenced and the implementation at https://github.com/norfolkmustard/ApplePayJS (see also the discussion about the implementation at https://forums.developer.apple.com/thread/51580) I was able to get it working.
The key for me was passing in the correct certificate (the Apple Pay Merchant Identity certificate) just as Apple provides it and getting the cert key like so:
Once you have your Merchant ID (session) certificate from Apple, import that into keychain.app on your Mac by double-clicking it, right click on the cert in keychain and export the combined private-key and cert as a .p12 file then, in terminal:-
openssl pkcs12 -in your_merchant_identity_cert_name.p12 -out ApplePay.key.pem -nocerts -nodes
After adding the Apple Pay Merchant Identification cert from Apple and the contents of the ApplePay.key.pem file to an environment variable I was able to construct the following request using Ruby's Net::HTTP class...
class YourControllerName < ApplicationController
def apple_pay_validation
respond_to do |format|
format.json { render json: start_apple_session(params[:url]) } if params[:url].include?('apple.com')
end
end
private
def start_apple_session(url)
uri = URI.parse(url) # the url from event.validationURL
data = {'merchantIdentifier' => "merchant.com.your_site_name", 'domainName' => "your_doamin", 'displayName' => "your_company_name"}
pem = File.read('path/to/your/merchant_id.cer')
key = ENV['APPLE_PAY_MERCHANT_ID_ KEY']
passphrase = 'passphrase set up when exporting certificate in keychain' # Should be an environment variable
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.ssl_version = :TLSv1_2
http.ciphers = ['ECDHE-RSA-AES128-GCM-SHA256']
http.cert = OpenSSL::X509::Certificate.new(pem)
http.key = OpenSSL::PKey::RSA.new(key, passphrase)
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
request = Net::HTTP::Post.new(uri.request_uri, 'Content-Type' => 'application/json')
request.body = data.to_json
response = http.request(request)
response.body
end
end
This was called from my performValidation function (modified from the ApplePayJS repo listed above) which looks like this..
performValidation = (valURL) ->
new Promise((resolve, reject) ->
xhr = new XMLHttpRequest
xhr.open 'GET', '/your_controller_name/apple_pay_validation?url=' + valURL
xhr.onerror = reject
xhr.onload = ->
data = JSON.parse(#responseText)
resolve data
xhr.send()
)
Hopefully that helps save someone some time and gray hairs!
I've pfx sectificate, with which I have to log into a specific URL to send and receive data. It's self-signed certificate.
Made pem files:
openssl pkcs12 -in client_ssl.pfx -out client_smsgate-in.pem -clcerts
openssl pkcs12 -in client_ssl.pfx -out ca_client_smsgate-in.pem -cacerts
Try connections:
require "net/https"
require "uri"
uri = URI.parse("myurl.ru")
pem = File.read("client_smsgate-in.pem")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.ca_file = File.read("ca_client_smsgate-in.pem")
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.cert = OpenSSL::X509::Certificate.new(pem)
http.key = OpenSSL::PKey::RSA.new(pem, 'pass')
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
I've error:
lib/ruby/2.2.0/net/http.rb:923:in 'connect': SSL_connect returned=1 errno=0 state=unknown state: certificate verify failed (OpenSSL::SSL::SSLError)
If check OpenSSL::SSL::VERIFY_NONE, it works. tell me what's wrong, because I have CA certificates to him?
i am using Microsoft's WinHttpRequest COM object to request a web-page with an invalid certificate:
IWinHttpRequest http = new WinHttpRequest();
http.Open("GET", url, false);
http.Send(null);
Except that the call to Send throws an exception:
0x80072F0D - The certificate authority is invalid or incorrect
How do i tell WinHttpRequest that i don't care, and i want it to retrieve the page i asked for?
The solution is to ignore four kinds of SSL errors:
//Code is released into the public domain. No attribution required.
IWinHttpRequest http = new WinHttpRequest();
http.Open("GET", url, false);
//ignore any TLS errors
option = http.Option[WinHttpRequestOption_SslErrorIgnoreFlags];
options = options | SslErrorFlag_Ignore_All;
http.Option[WinHttpRequestOption_SslErrorIgnoreFlags] = option;
//SslErrorFlag_Ignore_All 0x3300
//Unknown certification authority (CA) or untrusted root 0x0100
//Wrong usage 0x0200
//Invalid common name (CN) 0x1000
//Invalid date or certificate expired 0x2000
http.Send(null);