Setting SSLContext for AsyncHttpClient - Can not read keystore file - rest

I need to use a AsyncHttpClient in my play application to make POST() call on https protocol. I am using play 2.2.x version.
I tried #Esfand's code mentioned in below question's first answer but it is failing for java.io.FileNotFoundException.
How to use Play WS with SSL?
Here is what I did :
1) I used keytool command to generate keyStore on my C drive .. something like this
keytool -import -trustcacerts -alias mypublickey -file "" -keystore "c:\mypublicstore.jks”
It stores file on C drive with name mypublicstore.jks" (note the double quotes at the end)
2) Then I am using following code to read that
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream inputStream = new FileInputStream("C:\\mypublicstore.jks\"");
String certPass = Play.application().configuration().getString("certificate.password");
keyStore.load(inputStream, certPass.toCharArray());
keyManagerFactory.init(keyStore, certPass.toCharArray());
But it is failing at line 3 of the code. It can not find the file on the system. I tried reading another file on the same location and it works fine then why it can not read jks" type of file? Am I doing something wrong here?
In FileInputStream I should give keystore path or certificate path?
Thanks for your help in advance.

I found out that AHC can not be used with play 2.2.x version. I need to upgrade to 2.3.x version.

Related

Getting error java.security.KeyStoreException: PKCS11 not found while using softhsm as hsm

I am using command line tool "keytool" to create a key pair in softhsm.
I have added security.provider in java.security.
# List of providers and their preference orders (see above):
security.provider.1=sun.security.provider.Sun
security.provider.2=sun.security.rsa.SunRsaSign
security.provider.3=sun.security.ec.SunEC
security.provider.4=com.sun.net.ssl.internal.ssl.Provider
security.provider.5=com.sun.crypto.provider.SunJCE
security.provider.6=sun.security.jgss.SunProvider
security.provider.7=com.sun.security.sasl.Provider
security.provider.8=org.jcp.xml.dsig.internal.dom.XMLDSigRI
security.provider.9=sun.security.smartcardio.SunPCSC
security.provider.10=sun.security.mscapi.SunMSCAPI
security.provider.11=sun.security.pkcs11.SunPKCS11
${java.home}/lib/security/pkcs11.cfg
and My pkcs11.cfg looks like
name = SoftHSM v2
library = C:/SoftHSM2/lib/softhsm2-x64.dll
slot = 0
While running
keytool.exe -keystore NONE -storetype PKCS11 -list
I am getting the error
keytool error: java.security.KeyStoreException: PKCS11 not found.
Can you please help?

MATLAB ignore security certifcates

I need to access some XML from the internet using MATLAB, and to get it I need to download the security certificate from the website manually and use the following function with the downloaded certificate;
% Title: inportcert
% Author: MathWorks Support Team
% Code Version: 1.0
% Type: MATLAB soruce code https://www.mathworks.com/matlabcentral/answers/uploaded_files/1142/importcert.m
function importcert(filename)
if (nargin == 0)
% If no certificate specified show open file dialog to select
[filename,path] = uigetfile({'*.cer;*.crt','Certificates
(*.cer,*.crt)'},'Select Certificate');
if (filename==0), return, end
filename = fullfile(path,filename);
end
% Determine Java keytool location and cacerts location
keytool = fullfile(matlabroot,'sys','java','jre',computer('arch'),'jre','bin','keytool');
cacerts = fullfile(matlabroot,'sys','java','jre',computer('arch'),'jre','lib','security','cacerts');
% Create backup of cacerts
if (~exist([cacerts '.org'],'file'))
% copyfile(cacerts,[cacerts '.org'])
end
% Construct and execute keytool
command = sprintf('"%s" -import -file "%s" -keystore "%s" -storepass
changeit -noprompt',keytool,filename,cacerts);
dos(command);
which will allow me to use the following command;
xmlread('https://finds.org.uk/database/images/index/format/xml');
These certificates expire and I would not be able to manually change the certificates at that point so I was wondering if;
A) Can I automatically download the certificate using MATLAB instead of doing it manually
B) Just ignore the certificate completely, security isn't an issue.
C) Preferably do A or B without the need for Admin rights
NOTE: It seems that you need to go through this process if you're using a Windows-based system, using MacOSX or Linux you will not need to import the certificates and can access the page without getting an SSL Handshake error.

Importing .pfx within BouncyCastle-Keystore

i've a problem concerning the import of a .pfx certificate into a bouncycastle-keystore. The error message says that "...tampered keystore file or incorrect PKCS12 Password...". I've exported the certificates with Windows' CertMgr.
The certificates are exported as .pfx files. I want to import the certificates with their private keys in order to use them in combination with tls' client authentication.
I would appreciate for any help.
Windows's PFX files are just renamed PKCS#12 files, and you don't even need BouncyCastle to import them: you can use Java's built-in KeyStore API (which has no limitations on password length or composition -- if you want "no password" you can use the empty string).
Usually, PKCS12 / PFX import code looks something like this:
FileInputStream fis = new FileInputStream("your.pfx");
String password = "your-password";
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(fis, password.toCharArray());
String alias = ks.aliases().nextElement();
PrivateKey pKey = (PrivateKey)ks.getKey(alias, password.toCharArray());
X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
Not sure about your case - but a lot of tools have implied assumptions about having a password on the private key and/or the same on the PKCS#12 enclosure; it being the same and being 4 or 6 chars. I found that using something like 'abcd1234' is a fairly safe one to use across vendors (or a real one of course).

isSessionValid() returns NO when Facebook native application is installed

I have an issue with SSO using the Facebook SDK for Android. The problem occurs only when the native Facebook application is installed. When it's not installed, everything works fine, specifically:
Facebook facebook = new Facebook(APP_ID);
facebook.authorize(mActivity, , new DialogListener() {
...
});
facebook.isSessionValid(); // returns true
But when the native application is installed, facebook.isSessionValid() still returns false despite the fact that I called the authorize method.
I should add that I created an native Android based Facebook application with the hashkey generated from my debug certificate using keytool.
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
What is going on?
SOLVED! :)
I sure hope this will work for you as well.
The problem is that Windows generates an invalid key.
Run this with your app:
try {
PackageInfo info = getPackageManager().getPackageInfo("**YOURPACKAGENAME**", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.i("PXR", Base64.encodeBytes(md.digest()));
}
}
catch (NameNotFoundException e) {}
catch (NoSuchAlgorithmException e) {}
Don't forget to get Base64 (http://iharder.sourceforge.net/current/java/base64/).
The generated key is on your logcat, replace the old one with this.
Solution thanks to:
http://p-xr.com/implementing-facebook-into-your-app-invalid-key-with-keytool/
In addition to what Lior wrote
you can do the log like this:
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
so you can use Andorid Base64
ref: Invalid Key Hash Troubleshooting

How to check if a file has a digital signature

I'd like to check programatically if a file has been digitally signed or not.
For the moment, I found a rather obscure Microsoft code, that doesn't compile...
Any idea on the subject?
An external tool with command line would also be great, by the way.
The important missing part of the answer mentioning signtool is:
Yes, with the well known signtool.exe you can also find out, if a file is signed. No need to download another tool!
E.g. with the simple line:
signtool verify /pa myfile.exe
if %ERRORLEVEL% GEQ 1 echo This file is not signed.
(For verbose output, add a /v after /pa.)
One may ask: Why this is important? I just sign the files (again) which shall be signed and it works.
My objective is to keep builds clean, and don't sign files a second time because not only the date is changed, but the is binary different after that.
Business example:
My client has a streamlined automated "dev ops" kind build and post build process. There are multiple sources for different file sets, and at the end all is build, tested and bundled to distribution- and for that some files have to be signed. To guarantee that some files don't leave the unit without being signed, we used to sign all important files found on the media, even if they were already signed.
But this hasn´t been clean enough ! Generally:
If we sign a file again, which is already signed, the file date and binary fingerprint changes, and the file looses comparability with it's sources, if it was simply copied.
(At least if you sign with a timestamp, which we always do and I think is highly recommended.)
This is a severe quality loss, because this file is no longer identical to it's predecessors although the file itself has not changed.
If we sign a file again, this also could be a fault when it is a third party file which shouldn't be signed by our company.
You can avoid both by making the signing itself conditional depending on the return code of the preceding signtool verify call mentioned.
Download Sigcheck and use the following command.
sigcheck.exe -a -u -e
An example of a signed dll
File version: 0.0.0.0
Strong Name: Signed
An example of an unsigned dll
File version: 0.0.0.0
Strong Name: Unsigned
Sigcheck is a command-line utility that shows file version number. Good Luck
I found another option (pure .NET code) on the web here.
The code is very simple and works.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
internal class Program
{
private static void Main(string[] args)
{
string filePath = args[0];
if (!File.Exists(filePath))
{
Console.WriteLine("File not found");
return;
}
X509Certificate2 theCertificate;
try
{
X509Certificate theSigner = X509Certificate.CreateFromSignedFile(filePath);
theCertificate = new X509Certificate2(theSigner);
}
catch (Exception ex)
{
Console.WriteLine("No digital signature found: " + ex.Message);
return;
}
bool chainIsValid = false;
/*
*
* This section will check that the certificate is from a trusted authority IE
* not self-signed.
*
*/
var theCertificateChain = new X509Chain();
theCertificateChain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
/*
*
* Using .Online here means that the validation WILL CALL OUT TO THE INTERNET
* to check the revocation status of the certificate. Change to .Offline if you
* don't want that to happen.
*/
theCertificateChain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
theCertificateChain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
theCertificateChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
chainIsValid = theCertificateChain.Build(theCertificate);
if (chainIsValid)
{
Console.WriteLine("Publisher Information : " + theCertificate.SubjectName.Name);
Console.WriteLine("Valid From: " + theCertificate.GetEffectiveDateString());
Console.WriteLine("Valid To: " + theCertificate.GetExpirationDateString());
Console.WriteLine("Issued By: " + theCertificate.Issuer);
}
else
{
Console.WriteLine("Chain Not Valid (certificate is self-signed)");
}
}
}
Since PowerShell 5.1, you can use Get-AuthenticodeSignature to verify the signature of a binary or a PowerShell script.
> Get-AuthenticodeSignature -FilePath .\MyFile.exe
SignerCertificate Status Path
----------------- ------ ----
A59E92E31475F813DDAF41C3CCBC8B78 Valid MyFile.exe
Or
> (Get-AuthenticodeSignature -FilePath .\MyFile.exe).Status
Valid
If you need an external tool, you can use signtool.exe. It is part of the Windows SDK, it takes command line arguments, and you can find out more about it here, http://msdn.microsoft.com/en-us/library/aa387764.aspx
Also you can try to use npm package sign-check for that purposes.
This package implements WinVerifyTrust API and has simple usage:
npm install -g sign-check
sign-check 'path/to/file'
Select the <*>.exe rightclick >properties. if the file is signed then you will get this tab on the property windows of that file.