I am trying to run an HTTPS Server on an Android device using NanoHttpd (my final goal is to run WSS server on Android). I successfully ran HTTP Server and Websocket using NanoH
The other answers didn't work for me. I had to create a BKS-V1 Keystore using a KeyStore Explorer and save it to android assets folder as "keystore.bks". Alternatively, You can also use the following code to make the KeyStore file then just open it using KeyStore Explorer and change its type to BKS-V1.
keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.bks -storepass myKeyStorePass -validity 360 -keysize 2048 -ext SAN=DNS:localhost,IP:127.0.0.1 -validity 9999
I used the following code to make it work.
package com.example.myappname
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.ssl.KeyManagerFactory;
import fi.iki.elonen.NanoHTTPD;
public class Server extends NanoHTTPD {
public Server(int port) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
super(port);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream keyStoreStream = context.get().getAssets().open("keystore.bks");
keyStore.load(keyStoreStream, "myKeyStorePass".toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "myCertificatePass".toCharArray());
makeSecure(NanoHTTPD.makeSSLSocketFactory(keyStore, keyManagerFactory), null);
}
@Override
public Response serve(IHTTPSession session) {
}
}
To use it just write the following code and you will have an HTTPS server running on your Android device.
Server server = new Server(8080);
server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
This code is made possible thanks to the example provided in the following Github issue comment.
https://github.com/NanoHttpd/nanohttpd/issues/535#issuecomment-479269044